The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
Default new Pi agents to Paperclip Runner (#17142)
Dotta734c26533914
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.mdindex bec91b9fe0..1c7085ffe5 100644--- a/doc/DEVELOPING.md+++ b/doc/DEVELOPING.md@@ -1933,22 +1933,22 @@ agent conversion are outside this playbook.## Paperclip Runner Adapter Conversion-Paperclip Runner offers native Codex, OpenCode, and **ACPX Claude**. New+Paperclip Runner offers native Codex, OpenCode, **ACPX Claude**, and **ACPX Pi**. NewClaude Code agents default to ACPX Claude on Apple Silicon, Intel Mac, Linux x64-and Linux ARM64 with supported glibc. New OpenCode agents default to native-OpenCode on Apple Silicon, Intel Mac, and Linux x64 with supported glibc;-Linux ARM64 remains Legacy until the pinned OpenCode runtime supports it.+and Linux ARM64 with supported glibc. New OpenCode and Pi agents default to their native+runtimes on Apple Silicon, Intel Mac, and Linux x64 with supported glibc;+Linux ARM64 remains Legacy until the pinned runtimes support it.Unsupported or unqualified targets retain Legacy. Claude over Darwin SSH keepsan automatic Legacy default; explicit native executionrequires matching remote assets. The runner override is in Advanced. Ordinary Claude models default to `claude-opus-5-5`; explicit models-and provider routing remain authoritative. Existing agents keep their saved runner. Converting an existing Claude, Codex, or OpenCode agent selects its+and provider routing remain authoritative. Existing agents keep their saved runner. Converting an existing Claude, Codex, OpenCode, or Pi agent selects itscorresponding provider, preserves compatible models, credentials, workspace,and instructions, and resets execution sessions while retaining run history.Other adapters require an explicit provider choice. Legacy ACPX Codex agentsettings normalize to native Codex on configuration updates and before freshruns; immutable run descriptors remain readable. The **Paperclip Runner**experimental setting applies to other native providers. Native Codex, OpenCode,-and ACPX Claude do not require it. Company access checks still apply.+ACPX Claude, and ACPX Pi do not require it. Company access checks still apply.OpenCode requires an explicit `provider/model` before testing or finishing setup.An inactive setup draft can be saved before choosing a model. Automatic native@@ -1956,8 +1956,17 @@ selection uses `allow` permissions and a `per_turn` lifecycle. Native `ask` and`deny` policies remain available in agent configuration. Legacy custom commands,extra arguments, model variants, and inherited permission rules require theLegacy runner; incompatible settings return remediation instead of being ignored.-Saved OpenCode agents keep their runner and runtime policies. Pi defaults are-unchanged.+Saved OpenCode agents keep their runner and runtime policies.++Pi also requires an explicit `provider/model` before testing or hiring; inactive+setup drafts may precede model selection. Install its pinned runtime on the+execution host with `paperclipai runtime setup pi` before testing the connection.+The native default uses `approve-all` permissions, `per_turn` lifecycle, and+`low` thinking. Exact native thinking levels are `off`, `low`, `high`, and `max`.+Legacy `minimal`, `medium`, and `xhigh` thinking, custom commands/arguments, and+raw stdout mode require Legacy. Switching back to Legacy rejects native `max`+thinking, nondefault permission policy, or warm lifecycle instead of discarding+them. Existing Pi agents retain their saved runner and native policies.Agent configuration uses the same section layout across adapters: model andprovider belong to **Adapter**, environment variables have their own section,diff --git a/doc/connections/AI-CONNECTIONS.md b/doc/connections/AI-CONNECTIONS.mdindex 96289490ed..affb9ac7a3 100644--- a/doc/connections/AI-CONNECTIONS.md+++ b/doc/connections/AI-CONNECTIONS.md@@ -25,7 +25,7 @@ The shared `AI_CONNECTION_CAPABILITIES` contract defines these combinations:| --- | --- | --- || Claude / Anthropic | Claude subscription token or Anthropic API key | Claude || OpenAI | ChatGPT/Codex subscription or OpenAI API key | Codex |-| OpenRouter (legacy, no routing metadata) | API key | OpenCode, with an `openrouter/` model |+| OpenRouter (legacy, no routing metadata) | API key | OpenCode or Pi, with an `openrouter/` model || Google | API key | Gemini CLI || Grok / xAI | Grok subscription or xAI API key | Grok |@@ -596,6 +596,7 @@ credentials belong to the connection; the model belongs to the agent.| Codex legacy and Codex New Runner (app-server) | OpenRouter; custom/local OpenAI Responses endpoints || Claude legacy and Claude New Runner (ACPX) | OpenRouter; custom/local Anthropic Messages; Bedrock API key || OpenCode legacy and New Runner | OpenRouter; custom/local Chat Completions |+| Pi legacy and New Runner | OpenRouter; native OpenAI, Anthropic, and Google API keys with a matching `provider/model` || Hermes local | OpenRouter; custom/local Chat Completions || Gemini CLI, Grok | Their native API connections; custom routes are not advertised |@@ -605,7 +606,7 @@ environment probes and task execution. The settings file contains no credential.OpenClaw Gateway, Hermes Gateway, Claude Managed, AWS AgentCore, Process, HTTP,and legacy `acpx_local` are excluded: external agents retain their own model-configuration, and `acpx_local` is retired. Cursor/Pi/Copilot custom routing,+configuration, and `acpx_local` is retired. Cursor/Copilot custom routing, Pi custom gateways and Bedrock,Vertex, ambient AWS identity, arbitrary authentication headers, and automaticcatalog discovery for custom gateways are not part of this implementation.diff --git a/maps/agent-access-map/runs-adapters.md b/maps/agent-access-map/runs-adapters.mdindex 7bfef0f5e1..23d452382f 100644--- a/maps/agent-access-map/runs-adapters.md+++ b/maps/agent-access-map/runs-adapters.md@@ -70,7 +70,17 @@ flag on macOS and GNU/Linux x64; Linux ARM64 retains Legacy. An explicitinactive setup drafts may omit it. Saved runners and permission/lifecyclepolicies remain authoritative. Actor/company checks and board-only discoveryremain unchanged. This is scoped source/control evidence for OpenCode selection,-not live provider execution or agent authorization proof; Pi is unchanged.+not live provider execution or agent authorization proof.+Pi follows the same supported platform/default and model-free inactive-draft+boundary, with explicit pinned-runtime setup required on the execution host.+Native ACPX Pi is admitted with the generic flag off. Existing direct Pi agents+remain Legacy; saved native policies remain authoritative. Incompatible thinking,+launch, permission, or lifecycle settings return remediation on conversion.+Managed Pi accounts accept OpenRouter routing and matching OpenAI, Anthropic,+Google, or OpenRouter API-key models. Subscription methods and custom gateways+remain excluded for Pi. Selection keeps the existing company, user, grant, and+agent-install checks; runtime preparation clears alternate credentials and rejects+custom Pi provider overrides. This adds no cross-company access or runtime installation API.An absent forced-Kubernetes environment is an unqualified sandbox target, nevera local target. Discovery and automatic creation keep the Legacy path withoutprovisioning it; explicit Paperclip selection returns qualification guidance.diff --git a/maps/feature-map/runs-adapters.md b/maps/feature-map/runs-adapters.mdindex 7b40cf08ee..1767da493b 100644--- a/maps/feature-map/runs-adapters.md+++ b/maps/feature-map/runs-adapters.md@@ -73,7 +73,14 @@ unrelated edit. Check that saved native permission/lifecycle choices surviveresuming setup. Custom commands, arguments, variants, and inherited permissionsmust give Legacy remediation when native is selected. A live task with theselected account is separate proof from these setup and persistence controls.-Pi retains its existing default and is outside this rollout.+Repeat with Pi on macOS or GNU/Linux x64 after explicit operator setup of the+pinned runtime (`paperclipai runtime setup pi`). Linux ARM64 retains Legacy.+Resume an inactive model-free draft, connect an account, choose a `provider/model`,+and finish setup with the generic native flag off. Verify Pi branding and native+ACPX Pi execution by completing a simple assigned task. Preserve saved native+thinking/permission/lifecycle settings on resume and unrelated edits. Native+thinking supports `off`, `low`, `high`, `max`; legacy aliases must give remediation,+and returning to Legacy must reject settings it cannot honor.On a fresh forced-Kubernetes instance without an environment row, inspect discoveryand create with automatic selection. Both must retain Legacy without provisioning;an explicit Paperclip request must give target-qualification guidance. Begin thediff --git a/packages/adapter-utils/src/paperclip-runner-permissions.test.ts b/packages/adapter-utils/src/paperclip-runner-permissions.test.tsindex cd61414cc4..fcaeea10fc 100644--- a/packages/adapter-utils/src/paperclip-runner-permissions.test.ts+++ b/packages/adapter-utils/src/paperclip-runner-permissions.test.ts@@ -43,10 +43,16 @@ describe("Paperclip Runner permission defaults", () => {["claude_local", "acpxPermissionMode", "approve-all"],["codex_local", "codexPermissionMode", "never"],["opencode_local", "opencodePermissionMode", "allow"],+ ["pi_local", "acpxPermissionMode", "approve-all"],])("uses full auto when converting %s to the new runner", (adapter, key, value) => {expect(paperclipRunnerTransitionConfig(adapter, undefined)).toMatchObject({ [key]: value });});+ it("keeps Pi models explicit during conversion", () => {+ expect(paperclipRunnerTransitionConfig("pi_local", undefined)).toMatchObject({ provider: "acpx", acpxAgent: "pi", model: "" });+ expect(paperclipRunnerTransitionConfig("pi_local", "openrouter/provider/model")).toMatchObject({ provider: "acpx", acpxAgent: "pi", model: "openrouter/provider/model" });+ });+it("recognizes only exact provider identifiers", () => {expect(isPaperclipRunnerProvider("codex")).toBe(true);expect(isPaperclipRunnerProvider("opencode")).toBe(true);diff --git a/packages/adapter-utils/src/paperclip-runner-permissions.ts b/packages/adapter-utils/src/paperclip-runner-permissions.tsindex bb162657f7..3cb2e323e9 100644--- a/packages/adapter-utils/src/paperclip-runner-permissions.ts+++ b/packages/adapter-utils/src/paperclip-runner-permissions.ts@@ -205,7 +205,7 @@ export function paperclipRunnerTransitionConfig(providerOverride?: unknown,): Record<string, unknown> {const previousProvider =- previousAdapterType === "claude_local"+ (previousAdapterType === "claude_local" || previousAdapterType === "pi_local")? "acpx": previousAdapterType === "opencode_local"? "opencode"@@ -218,11 +218,13 @@ export function paperclipRunnerTransitionConfig(: previousProvider;return {provider,- model: resolvePaperclipRunnerModel(+ model: provider === "acpx" && previousAdapterType === "pi_local"+ ? typeof previousModel === "string" ? previousModel.trim() : ""+ : resolvePaperclipRunnerModel(provider,provider === previousProvider ? previousModel : undefined,),- ...(provider === "acpx" ? { acpxAgent: "claude" } : {}),+ ...(provider === "acpx" ? { acpxAgent: previousAdapterType === "pi_local" ? "pi" : "claude" } : {}),[PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES[provider].configKey]:PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES[provider].defaultMode,lifecycleMode: "per_turn",diff --git a/packages/adapter-utils/src/server-utils.test.ts b/packages/adapter-utils/src/server-utils.test.tsindex 0523c4d09e..083196829b 100644--- a/packages/adapter-utils/src/server-utils.test.ts+++ b/packages/adapter-utils/src/server-utils.test.ts@@ -20,6 +20,7 @@ import {isPaperclipExternalChatQuestionResponseTurn,isPaperclipExternalChatTurn,materializePaperclipSkillCopy,+ normalizePaperclipRunnerAdapterConfig,PAPERCLIP_OPERATIONAL_SKILL_KEY,PAPERCLIP_FEEDBACK_SKILL_KEYS,refreshPaperclipWorkspaceEnvForExecution,@@ -43,6 +44,12 @@ import {WATCHDOG_DEFAULT_MANDATE,} from "./server-utils.js";+it("keeps Pi draft models empty and preserves saved native Pi settings", () => {+ expect(normalizePaperclipRunnerAdapterConfig("paperclip_runner", { provider: "acpx", acpxAgent: "pi", model: "" })).toMatchObject({ provider: "acpx", acpxAgent: "pi", model: "" });+ const saved = { provider: "acpx", acpxAgent: "pi", model: "openrouter/provider/model", piThinkingLevel: "max", acpxPermissionMode: "approve-reads", lifecycleMode: "warm" };+ expect(normalizePaperclipRunnerAdapterConfig("paperclip_runner", saved)).toMatchObject(saved);+});+it("reserves identity credentials even for mixed-case inherited or configured keys", () => {const keys = ["PAPERCLIP_AGENT_KEY_ID", "Paperclip_Agent_Public_Key", "paperclip_agent_private_key"];const inherited = Object.fromEntries(keys.map(key => [key, "host-override"]));diff --git a/packages/adapter-utils/src/server-utils.ts b/packages/adapter-utils/src/server-utils.tsindex 26dac29cd9..a20f02e5a1 100644--- a/packages/adapter-utils/src/server-utils.ts+++ b/packages/adapter-utils/src/server-utils.ts@@ -4299,7 +4299,7 @@ export function normalizePaperclipRunnerAdapterConfig(}if (next.provider === "acpx") {next.acpxAgent ??= "claude";- next.model = resolvePaperclipRunnerModel("acpx", config.model);+ if (next.acpxAgent !== "pi") next.model = resolvePaperclipRunnerModel("acpx", config.model);}return normalizePaperclipOperationalSkillPreference(adapterType, next);}diff --git a/packages/adapters/pi-local/src/ui/build-config.ts b/packages/adapters/pi-local/src/ui/build-config.tsindex 06927f6f8d..cfe790bba7 100644--- a/packages/adapters/pi-local/src/ui/build-config.ts+++ b/packages/adapters/pi-local/src/ui/build-config.ts@@ -5,7 +5,15 @@ export function buildPiLocalConfig(v: CreateConfigValues): Record<string, unknowif (v.cwd) ac.cwd = v.cwd;if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;if (v.model) ac.model = v.model;- if (v.thinkingEffort) ac.thinking = v.thinkingEffort;+ const nativeSelected = v.runner === "paperclip"+ || ((v.runner === undefined || v.runner === "auto") && v.resolvedRunner === "paperclip");+ if (nativeSelected) {+ const thinking = v.adapterSchemaValues?.piThinkingLevel ?? v.thinkingEffort;+ if (thinking) ac.piThinkingLevel = thinking;+ if (v.adapterSchemaValues?.acpxPermissionMode !== undefined) ac.acpxPermissionMode = v.adapterSchemaValues.acpxPermissionMode;+ if (v.paperclipRunnerLifecycleMode !== undefined) ac.lifecycleMode = v.paperclipRunnerLifecycleMode;+ if (v.paperclipRunnerIdleTimeoutMs !== undefined) ac.idleTimeoutMs = v.paperclipRunnerIdleTimeoutMs;+ } else if (v.thinkingEffort) ac.thinking = v.thinkingEffort;// Pi sessions can run until the CLI exits naturally; keep timeout disabled (0)ac.timeoutSec = 0;diff --git a/packages/paperclip-runner/acpx-profiles.json b/packages/paperclip-runner/acpx-profiles.jsonindex 25a6623971..9ad42bdaf3 100644--- a/packages/paperclip-runner/acpx-profiles.json+++ b/packages/paperclip-runner/acpx-profiles.json@@ -32,12 +32,12 @@"requiresProviderPolicy": true},"copilot": {- "agentProfileVersion": 57,+ "agentProfileVersion": 58,"agentServerPackage": "@github/copilot","agentServerVersion": "1.0.88","agentRuntimePackage": null,"agentRuntimeVersion": null,- "commandDigest": "sha256:c643eb4def4a0c9a5c3bf13be42ce653343c61c5d84cda33a989018fe4af3b68",+ "commandDigest": "sha256:6f49e1a37bcde897703701b638dddf010a0b8e2c92c211a30d4a0bd41e48e77d","requiresProviderPolicy": true},"claude": {diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rsindex 5d17a5276b..bde545b624 100644--- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs+++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs@@ -1282,6 +1282,7 @@ fn sidecar_run_tool_operations(run_tool_set: &AuthorizedToolSet) -> Vec<Value> {run_tool_set.operations.iter()+ .filter(|tool| !is_reserved_terminal_operation(&tool.operation_id)).map(|tool| {json!({"name": tool.operation_id,@@ -1694,13 +1695,22 @@ mod tests {#[test]fn sidecar_catalog_leaves_reserved_terminal_tools_to_the_trusted_bridge() {- let operations = vec![AuthorizedTool {+ let mut operations = vec![AuthorizedTool {operation_id: "get_task_context".to_owned(),version: 1,description: "Read the task context.".to_owned(),input_schema: json!({"type":"object"}),response_schema: json!({"type":"object"}),}];+ for name in [PRP_BLOCK_TOOL_NAME, PRP_COMPLETION_TOOL_NAME] {+ operations.push(AuthorizedTool {+ operation_id: name.to_owned(),+ version: 1,+ description: "Trusted terminal operation.".to_owned(),+ input_schema: json!({"type":"object"}),+ response_schema: json!({"type":"object"}),+ });+ }let run_tool_set = AuthorizedToolSet {schema: TOOL_SET_SCHEMA.to_owned(),schema_version: 1,@@ -1716,7 +1726,7 @@ mod tests {.collect::<Vec<_>>(),vec!["get_task_context"]);- assert_eq!(run_tool_set.operations.len(), 1);+ assert_eq!(run_tool_set.operations.len(), 3);assert_eq!(sidecar_tools[0],json!({diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rsindex a8cb35d1ed..ed11dcc658 100644--- a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs+++ b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs@@ -47,7 +47,7 @@ pub(crate) fn acpx_release_profile(agent: &str) -> Option<AcpxReleaseProfile> {agent_runtime_package: None,agent_runtime_version: None,command_digest:- "sha256:c643eb4def4a0c9a5c3bf13be42ce653343c61c5d84cda33a989018fe4af3b68",+ "sha256:6f49e1a37bcde897703701b638dddf010a0b8e2c92c211a30d4a0bd41e48e77d",requires_provider_policy: true,},"claude" => AcpxReleaseProfile {diff --git a/packages/paperclip-runner/scripts/copilot-profile-identity.mjs b/packages/paperclip-runner/scripts/copilot-profile-identity.mjsindex 16c7254033..4d55c9f836 100644--- a/packages/paperclip-runner/scripts/copilot-profile-identity.mjs+++ b/packages/paperclip-runner/scripts/copilot-profile-identity.mjs@@ -7,9 +7,9 @@ import { fileURLToPath } from "node:url";import { resolve, dirname } from "node:path";const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");-const fixture = resolve(root, "test/fixtures/copilot-profile-v57-identity.json");+const fixture = resolve(root, "test/fixtures/copilot-profile-v58-identity.json");const historical = JSON.parse(readFileSync(resolve(root, "test/fixtures/copilot-profile-v12-identity.json"), "utf8"));-const declaration = { ...historical.declaration, agentProfileVersion: 57 };+const declaration = { ...historical.declaration, agentProfileVersion: 58 };delete declaration.permissionIdentitySourceSha256;const sources = {displayEventSourceSha256: "src/drivers/acpx/copilot-events.ts",diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.tsindex 2409e9a039..961571a5ef 100644--- a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts+++ b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts@@ -87,9 +87,19 @@ vi.mock("./installation-integrity.js", () => ({ verifyNativeAcpxInstallation: videscribe("Copilot build-owned installation", () => {it("admits the current profile with environment launch preparation", () => {- expect(QUALIFIED_ACPX_PROFILES.copilot.agentProfileVersion).toBe(57);+ expect(QUALIFIED_ACPX_PROFILES.copilot.agentProfileVersion).toBe(58);expect(QUALIFIED_ACPX_PROFILES.copilot.qualificationStatus).toBeUndefined();- expect(QUALIFIED_ACPX_PROFILES.copilot.commandDigest).toBe("sha256:c643eb4def4a0c9a5c3bf13be42ce653343c61c5d84cda33a989018fe4af3b68");+ expect(QUALIFIED_ACPX_PROFILES.copilot.commandDigest).toBe("sha256:6f49e1a37bcde897703701b638dddf010a0b8e2c92c211a30d4a0bd41e48e77d");+ });++ it("preserves v57 while binding the shared Pi setup and launch repairs in v58", () => {+ const prior = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v57-identity.json", import.meta.url), "utf8"));+ const current = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v58-identity.json", import.meta.url), "utf8"));+ expect(Object.keys(current.declaration).filter(key => current.declaration[key] !== prior.declaration[key]).sort()).toEqual([+ "agentProfileVersion", "guardedInstallationSourceSha256", "profileCompatibilitySourceSha256", "profileInstallationSourceSha256", "runtimeRequestBridgeSourceSha256",+ ]);+ expect(isSupportedAcpxProfileVersion("copilot", 57)).toBe(true);+ expect(current.commandDigest).not.toBe(prior.commandDigest);});it("preserves v56 while binding the extracted core prompts in v57", () => {diff --git a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.tsindex 513a66e763..925ab67ba7 100644--- a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts+++ b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts@@ -48,12 +48,12 @@ export const QUALIFIED_ACPX_PROFILE_DATA = {"protocolVersion": 1,"acpxVersion": "0.13.1","agent": "copilot",- "agentProfileVersion": 57,+ "agentProfileVersion": 58,"agentServerPackage": "@github/copilot","agentServerVersion": "1.0.88","agentRuntimePackage": null,"agentRuntimeVersion": null,- "commandDigest": "sha256:c643eb4def4a0c9a5c3bf13be42ce653343c61c5d84cda33a989018fe4af3b68",+ "commandDigest": "sha256:6f49e1a37bcde897703701b638dddf010a0b8e2c92c211a30d4a0bd41e48e77d","permissionPolicy": "interactive"},"claude": {diff --git a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.tsindex c091c2e947..d38b69645f 100644--- a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts+++ b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts@@ -2259,10 +2259,3 @@ export async function probeAcpxClaudeInstallation(model: string): Promise<void>export async function probeAcpxGrokInstallation(model: string): Promise<void> {await verifyQualifiedAcpxInstallation(resolveQualifiedAcpxProfile("grok", model));}--/** Verify the pinned Pi closure and snapshot lease without launching a provider. */-export async function probeAcpxPiInstallation(model: string): Promise<void> {- const installation = await verifyQualifiedAcpxInstallation(resolveQualifiedAcpxProfile("pi", model));- const lease = await installation.openCommand();- await lease.close();-}diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.tsindex 758da4b8e8..1119594c0e 100644--- a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts+++ b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts@@ -2,13 +2,13 @@ import { QUALIFIED_ACPX_PROFILE_DATA } from "./generated-profiles.js";/** Decodable historical profile revisions, not permission to launch them.* Exact current profile/package/digest admission is checked separately. */-type HistoricalAcpxProfileVersion = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56;+type HistoricalAcpxProfileVersion = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57;type CurrentAcpxProfileVersion = typeof QUALIFIED_ACPX_PROFILE_DATA[keyof typeof QUALIFIED_ACPX_PROFILE_DATA]["agentProfileVersion"];export type AcpxProfileVersion = HistoricalAcpxProfileVersion | CurrentAcpxProfileVersion;const historicalVersions: Readonly<Record<string, readonly HistoricalAcpxProfileVersion[]>> = {pi: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27], claude: [1, 2, 3, 4, 5], codex: [1, 2, 3, 4, 5],- grok: [1, 2, 3, 4, 5], copilot: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56],+ grok: [1, 2, 3, 4, 5], copilot: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57],cursor: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],};diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-installation.test.ts b/packages/paperclip-runner/src/drivers/acpx/profile-installation.test.tsindex 6270a001e7..14e975d6e2 100644--- a/packages/paperclip-runner/src/drivers/acpx/profile-installation.test.ts+++ b/packages/paperclip-runner/src/drivers/acpx/profile-installation.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from "vitest";-import { assertAcpxProfileEnvironment, classifyAcpxProfileError } from "./profile-installation.js";+import { describe, expect, it, vi } from "vitest";+import { assertAcpxProfileEnvironment, classifyAcpxProfileError, probeAcpxPiInstallation } from "./profile-installation.js";describe("Cursor actionable admission errors", () => {it("requires an explicit bound credential and supports both company-secret names", () => {@@ -24,3 +24,16 @@ describe("Cursor actionable admission errors", () => {expect(classifyAcpxProfileError("codex", new Error("unauthorized"))).toBeNull();});});++const piProbe = vi.hoisted(() => ({ verify: vi.fn(), open: vi.fn(), close: vi.fn() }));+vi.mock("./pi-installation.js", () => ({ verifyPiInstallation: piProbe.verify }));+it("probes Pi through its pinned distribution and closes the verified snapshot lease", async () => {+ piProbe.verify.mockResolvedValue({ openCommand: piProbe.open });+ piProbe.open.mockResolvedValue({ close: piProbe.close });+ await probeAcpxPiInstallation("openrouter/anthropic/claude-sonnet-4.5");+ expect(piProbe.verify).toHaveBeenCalledWith(expect.objectContaining({ agent: "pi", qualificationModel: "openrouter/anthropic/claude-sonnet-4.5" }));+ expect(piProbe.close).toHaveBeenCalledTimes(1);+ piProbe.verify.mockRejectedValueOnce(new Error("Pi distribution failed verification"));+ await expect(probeAcpxPiInstallation("openrouter/anthropic/claude-sonnet-4.5")).rejects.toThrow("failed verification");+ expect(piProbe.close).toHaveBeenCalledTimes(1);+});diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-installation.ts b/packages/paperclip-runner/src/drivers/acpx/profile-installation.tsindex c2d7f11ace..5c07c21aab 100644--- a/packages/paperclip-runner/src/drivers/acpx/profile-installation.ts+++ b/packages/paperclip-runner/src/drivers/acpx/profile-installation.ts@@ -65,3 +65,8 @@ export async function probeAcpxCursorInstallation(model: string): Promise<void>const installation = await verifyAcpxProfileInstallation(resolveQualifiedAcpxProfile("cursor", model));await (await installation.openCommand()).close();}++export async function probeAcpxPiInstallation(model: string): Promise<void> {+ const installation = await verifyAcpxProfileInstallation(resolveQualifiedAcpxProfile("pi", model));+ await (await installation.openCommand()).close();+}diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.tsindex a495c0811c..675b2c6cae 100644--- a/packages/paperclip-runner/src/index.ts+++ b/packages/paperclip-runner/src/index.ts@@ -91,7 +91,8 @@ export * from "./semantic-tools/index.js";export * as acceptedCapabilitySemanticTools from "./semantic-tools/index.js";export * from "./compatibility.js";-export { probeAcpxClaudeInstallation, probeAcpxGrokInstallation, probeAcpxPiInstallation } from "./drivers/acpx/installation-integrity.js";+export { probeAcpxClaudeInstallation, probeAcpxGrokInstallation } from "./drivers/acpx/installation-integrity.js";+export { probeAcpxPiInstallation } from "./drivers/acpx/profile-installation.js";export { bundledRemoteProviderPackManifestPath, bundledRemoteRunnerBinary } from "./live/bundled-remote-provider-pack.js";export { RunnerdMuseDriver, describeRunnerdMuseDriver, type RunnerdMuseDriverOptions } from "./drivers/muse/runnerd-muse-driver.js";diff --git a/packages/paperclip-runner/src/live/index.ts b/packages/paperclip-runner/src/live/index.tsindex ab80904063..2f86f2739f 100644--- a/packages/paperclip-runner/src/live/index.ts+++ b/packages/paperclip-runner/src/live/index.ts@@ -6,9 +6,9 @@ export * from "./runnerd-codex-transport.js";export * from "./turn-stream.js";export * from "./linux-process-start.js";-export { probeAcpxClaudeInstallation, probeAcpxGrokInstallation, probeAcpxPiInstallation } from "../drivers/acpx/installation-integrity.js";+export { probeAcpxClaudeInstallation, probeAcpxGrokInstallation } from "../drivers/acpx/installation-integrity.js";export { probeCopilotMetadata, validateCopilotMetadata, type CopilotMetadataResult } from "../drivers/copilot-metadata-probe.js";-export { probeAcpxCursorInstallation } from "../drivers/acpx/profile-installation.js";+export { probeAcpxCursorInstallation, probeAcpxPiInstallation } from "../drivers/acpx/profile-installation.js";export { bundledRemoteProviderPackManifestPath, bundledRemoteRunnerBinary } from "./bundled-remote-provider-pack.js";diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.tsindex 1d571f174e..47ac7a9209 100644--- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts+++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts@@ -1653,9 +1653,11 @@ it.each([const { preparationDeadline, closeDeadline } = runnerdRecoveryInternals.runnerCloseDeadlines(Date.now(), runnerdRecoveryInternals.runnerCloseGraceMs(options),);- // The retained restart failure spent 5.2s stopping idle Pi before its- // remote drain acknowledgement crossed the next command round trip.- await vi.advanceTimersByTimeAsync(5_200);+ // Native Pi allows thirty seconds for snapshot cleanup and five seconds+ // for its lifetime fence before the drain acknowledgement round trip.+ const stopMs = options.provider === "acpx" && options.acpxAgent === "pi"+ && options.closeGraceMs === undefined ? 35_200 : 5_200;+ await vi.advanceTimersByTimeAsync(stopMs);const commands: { commandId: string; status: string; result?: unknown }[] = [];const result = runnerdRecoveryInternals.awaitProviderDrainBarrier({readProviderState: () => null,@@ -1675,7 +1677,7 @@ it.each([await vi.advanceTimersByTimeAsync(5_000);expect(await result).toBe(drained);expect(closeDeadline - preparationDeadline).toBeLessThanOrEqual(2_500);- expect(runnerdRecoveryInternals.runnerCloseGraceMs(options)).toBeLessThanOrEqual(15_000);+ expect(runnerdRecoveryInternals.runnerCloseGraceMs(options)).toBeLessThanOrEqual(45_000);} finally { vi.useRealTimers(); }});@@ -1892,13 +1894,17 @@ it.each([false, true])("binds a vendored source server to its pnpm dependency roexpect(runnerdLaunchProfileInternals.acpxProviderPackageAuthority(join(server, "dist/vendor/paperclip-runner/cli/acpx-runtime-sidecar.cjs"),)).toEqual({ root: selfRooted ? server : workspace, manifest: join(server, "package.json") });+ expect(runnerdLaunchProfileInternals.acpxProviderPackageAuthority(+ join(server, "dist/vendor/paperclip-runner/cli/acpx-runtime-sidecar.cjs"), workspace, "pi",+ )).toEqual({ root: server, manifest: join(server, "package.json") });} finally {await rm(workspace, { recursive: true, force: true });}});-it.each(["source", "scoped-npm", "deployment"])(- "admits the controller-selected Copilot package authority in a %s layout",- async (layout) => {+it.each((["copilot", "pi"] as const).flatMap(agent =>+ ["source", "scoped-npm", "deployment"].map(layout => ({ agent, layout }))))(+ "admits the controller-selected $agent package authority in a $layout layout",+ async ({ agent, layout }) => {const directory = await realpath(await mkdtemp(join(tmpdir(), "copilot-package-authority-")));const runnerRoot = layout === "source"? join(directory, "packages/paperclip-runner")@@ -1909,13 +1915,13 @@ it.each(["source", "scoped-npm", "deployment"])(await writeFile(join(runnerRoot, "package.json"), JSON.stringify({ name: "@paperclipai/paperclip-runner" }));try {const authority = runnerdLaunchProfileInternals.acpxProviderPackageAuthority(- join(runnerRoot, "dist/cli/acpx-runtime-sidecar.cjs"), runnerRoot, "copilot",+ join(runnerRoot, "dist/cli/acpx-runtime-sidecar.cjs"), runnerRoot, agent,);expect(authority).toEqual({ root: runnerRoot, manifest: join(runnerRoot, "package.json") });vi.stubEnv("PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT", authority.root);vi.stubEnv("PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST", authority.manifest);- expect(resolveRunnerProviderAssetsRoot("file:///proc/self/fd/18", "copilot"))- .toBe(join(runnerRoot, "provider-assets/copilot"));+ expect(resolveRunnerProviderAssetsRoot("file:///proc/self/fd/18", agent))+ .toBe(join(runnerRoot, `provider-assets/${agent}`));} finally {vi.unstubAllEnvs();await rm(directory, { recursive: true, force: true });diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.tsindex bc5046222c..45ef831708 100644--- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts+++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts@@ -850,11 +850,11 @@ async function awaitRunnerSuspensionBarrier(input: {}function runnerCloseGraceMs(options: Pick<CapabilityRunnerdCodexTransportOptions, "provider" | "acpxAgent" | "closeGraceMs">): number {- // Idle Pi retirement may consume its five-second RPC stop window. Keep a- // separate five-second drain round trip and the bounded suspension reserve.+ // Native Pi retirement allows thirty seconds for snapshot cleanup and five+ // for its lifetime fence. Keep a drain round trip and suspension reserve too.// Explicit caller deadlines remain authoritative; all settlement proofs stay// mandatory even when the provider already completed its task.- return options.closeGraceMs ?? (options.provider === "acpx" && options.acpxAgent === "pi" ? 15_000 : 10_000);+ return options.closeGraceMs ?? (options.provider === "acpx" && options.acpxAgent === "pi" ? 45_000 : 10_000);}function runnerCloseDeadlines(@@ -3023,7 +3023,7 @@ function acpxProviderPackageAuthority(const workspaceRoot = dirname(serverRoot);// Source/Docker builds share the workspace's pnpm store. Published npm// bundles and self-rooted pnpm deployments retain their server authority.- if (basename(serverRoot) === "server" &&+ if (agent !== "pi" && basename(serverRoot) === "server" &&!existsSync(resolve(serverRoot, "node_modules/.pnpm")) &&existsSync(resolve(workspaceRoot, "node_modules/.pnpm")) &&existsSync(resolve(workspaceRoot, "pnpm-workspace.yaml")) &&@@ -3046,10 +3046,10 @@ function acpxProviderPackageAuthority();}const sidecarPackageRoot = resolve(cliDirectory, "../..");- // Copilot's native closure belongs to the runner package itself. Its asset+ // Native Pi and Copilot closures belong to the runner package itself. Their asset// guard requires the bound manifest directly inside that same package root;// the workspace dependency root used by JS providers is a different owner.- if (agent === "copilot") {+ if (agent === "copilot" || agent === "pi") {return {root: sidecarPackageRoot,manifest: resolve(sidecarPackageRoot, "package.json"),diff --git a/packages/paperclip-runner/test/fixtures/copilot-profile-v58-identity.json b/packages/paperclip-runner/test/fixtures/copilot-profile-v58-identity.jsonnew file mode 100644index 0000000000..73ea4781ee--- /dev/null+++ b/packages/paperclip-runner/test/fixtures/copilot-profile-v58-identity.json@@ -0,0 +1,85 @@+{+ "commandDigest": "sha256:6f49e1a37bcde897703701b638dddf010a0b8e2c92c211a30d4a0bd41e48e77d",+ "declaration": {+ "schema": "paperclip.acpx_profile_declaration.v1",+ "agent": "copilot",+ "agentProfileVersion": 58,+ "acpxVersion": "0.13.1",+ "agentServerVersion": "1.0.88",+ "protocolPolicyRevision": "copilot-agent-manual-v1",+ "acpxPatchSha256": "00d6af17216cb0cad902b48633eb19bf0ec6b05837a984cb24661fca593f09c1",+ "policySha256": "a4be69be43db84052560420a3ca546a665c9165573c24d543eb33d144ba138a3",+ "distributionSourceSha256": "c0a65e247fc47b263bd369a3d5ab505c4b323d4e6493be8a9ecbeb0e9dbb9107",+ "agentFilesBinding": "registered-runtime-context-v1",+ "systemInstructionDelivery": "COPILOT_HOME/copilot-instructions.md:replace-under-lifetime-lease-before-launch:v1",+ "sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1",+ "innerDistributionSourceSha256": "9bb08347eed01f1ab44e065c8b06ead9be3a25973d6e6329dc4c0a099096279a",+ "upstreamAppSha256": "7b48282a19b5b0814a0c96ad5e3a125173d792cc55f9525b2effea962f6063c0",+ "patchedAppSha256": "61f8eebe0c30cc03b311c6818b2acb158a6d16ca58c8bfac5ebd42db095c2679",+ "messageIdentityContract": "copilot-native-message-id-v1",+ "ownedDistributionDelivery": "COPILOT_CLI_DIST_DIR:lease-owned-guarded-inner-distribution:v1",+ "permissionContextContract": "copilot-edit-permission-context-v1",+ "permissionContextSourceSha256": "de2d38d702b3c574161af0c0c04790fb6f6347916eb3916ce7a131a8c229121b",+ "permissionAdapterSourceSha256": "ee5929ed2ee647ad0369465dee9d51a00b2dd28e1ff735b43e969ddc9c164668",+ "permissionLocationsSourceSha256": "f39a81da395b6e23aa2a1a45572a28846e5e81bfd3d764d9a456f74a79c752e9",+ "permissionRedactionSourceSha256": "ad6770c69269087951790e2e87e22ac088e3d432769adf17ebc865ed512e6c4f",+ "permissionClassifierSourceSha256": "1161eabd82e26133e3b3db3ab567f65d52808b03f176e93497e02c8330349fb4",+ "semanticToolReceiptContract": "paperclip.semantic_tool_receipt.v2",+ "semanticReceiptSourceSha256": "b2795726b2234a663fec1a6ca11f0551ae69882fe9e82aa39686e952d036e791",+ "semanticBridgeSourceSha256": "89e3dde25ff35bfd4d7f520fd9d14af3cb9027f182a2d51431d298f1015be580",+ "toolEvidenceSourceSha256": "6eef5039afc75bb851eaf9cd82a6f099e4bd398ca2deb59dd66f5b2a81a7a706",+ "semanticNormalizedInputContract": "validated-forwarded-input-commit-v1",+ "semanticSidecarSourceSha256": "cc90b59bdfe6a82f7fa3e819e8671f71f7b14047e68942e8086618ffbaacf59f",+ "semanticDirectDriverSourceSha256": "ff572638f2cb5d9f8249ff8e2f412311c1e3af209ef0bf7e5ea9f10a21d91103",+ "semanticValidationSourceSha256": "02fbb92681c78c5de5d2f1aae25aabc25a0e5df6b0ff4baccac652192a8da975",+ "semanticNormalizationSourceSha256": "8b628b82e8eacc91cdcc6fdca2210ba4cf282f01e9c6f74e95ff271655b5047e",+ "semanticCompletionContractSourceSha256": "3343df6362252d44d12b079ff78c8f6539d1544f3ce5ec36ff36db70ab0fac31",+ "semanticValidatorsSourceSha256": "f22d9caf2035b600abc1a6625ae23ca97f1409d7e29ed5b7264bb8f9784c7dc9",+ "semanticSchemaBundleSourceSha256": "016391a087cc217aafed4ba1f4efafc6e4881a7525952dce824b7f4d24530603",+ "semanticSidecarProtocolSourceSha256": "03c0c95b900f9dc18f29f6be27b8c79bc0bcab29780190d46a74e95328081236",+ "semanticSidecarReceiptCommitContract": "correlated-tool-resolve-v1",+ "displayEventSourceSha256": "d72f9a6035c247bc6a42c067c05753076c54322c4b58984e93922f3325dc6877",+ "displayProjectionSourceSha256": "75952606b26dd93bbc582c1f0a4424487377272ea745fb3a27ceae031fd5dc7e",+ "configuredEnvironmentSourceSha256": "5c9008d121979a3a8987e6b8a5752172eafdc4a2b5d725a73f3bbb8fb83be8ff",+ "configuredEnvironmentRustSourceSha256": "85c87fae62b8a9377e4f0a4c00302c7519fae4397b1c48253f8f2b7ba7faf994",+ "profileActivitySourceSha256": "4fdb6b0f9125fd8372ba6f27945fa5c8a3d3b2ec891df544092e3dc7a75d5282",+ "profileExtensionsSourceSha256": "a80ddc95eb4505095bfdbbf85c758199949ab20be9c84b34c77f762eb7180571",+ "profileInstallationSourceSha256": "3e61c4cdd4b78e38fcb16eaadae4f1fd65ce3c7127184ea7a80948c8e5d77f88",+ "attachmentPolicySourceSha256": "4f7638b7cc64e18f6a4ba33fd46de2b3d49225e32aeab41f5c695b268fa4f8e2",+ "singleReadEvidenceSourceSha256": "4069393405089bde613cecec04f5123c426594811da4c668bd96f0e7e283550f",+ "nativeSessionRuntimeSourceSha256": "e8a3bee66a1ff1c6f251b5ae57453ffb908336da9c4a6d98f41f94f7ee94a8e8",+ "nativeRuntimeContextSourceSha256": "71607f80dbb8dc5cc6c123d0b8f3995d6c5407277695a8c82cbedc90fb8f4842",+ "nativeRuntimePromptsSourceSha256": "103b83066da72434602e9e461e6278dfb40bb993d2f3b49b2e93df81bbb08b72",+ "nativeSessionContractSourceSha256": "22a8c96ce41ba4f03e976fc37f0cc7c5d05cee99fa789941da31ee1dab440b90",+ "harnessSessionContractSourceSha256": "03f4cd7f76f34f6d82e009b66aa51f18f6e23dc235b660778060e35b6ea07412",+ "harnessBackendSourceSha256": "dc827e281ae6731545b166ee4d709a4f67f594a556dcbe63c70fe8f1aca26249",+ "harnessSessionSourceSha256": "81361733e86b56dd5a66415aefc6f72e69be24acc8d3417370154ebb7fef6e94",+ "transportContractSourceSha256": "4fa9593226ff3280bc12140bfcbc2c0986e4cc8d4733381c334138dd03b08f46",+ "nativeBackendSourceSha256": "2406483fd35a564971c22e10fc2bad26bae16ff5a3fb6c65690fcf156522ab6d",+ "nativeBackendFactorySourceSha256": "7e431c926b76d53c4c08e3a4105353dcd34bd940f6588a1a68f79631f6feeb44",+ "nativeInstructionsSourceSha256": "ee8df5d85b263d5d2d0dc9ede8602cb7daf6388687108fe05e2371f5f56c3492",+ "providerLaunchSourceSha256": "cba71368f82ae8d300123efa09f23744e19e82142788fa9ad238338fefec9624",+ "launchPreparationStoreSourceSha256": "ff6025568bbc0aa6ce545772d73dfca2d3da226740bd3a7b386b069e76cff296",+ "runtimeRequestBridgeSourceSha256": "84817421db88fedfed465886259aef9afc1cea022ba93905d5711f12ccb147dc",+ "runtimeRequestFacadeSourceSha256": "d0ed28e0c5ddad34db8f437e704c8a755eb0b47f27e08e44185f66d1d2205295",+ "runtimeRequestNotificationSourceSha256": "6196c6175f11c69295dc00fc773201f4fdeca26c500653870253c43b81e65211",+ "guardedInstallationSourceSha256": "56a177d3e702914818dca4ca50e061f0d25f988bfc4c0582c36ce23c1696d82f",+ "nativeExecutionSourceSha256": "fc7c6568feb0d8d709e9baa51839420c9b90336b4865a9b8405aba06e4d1e9c4",+ "profileCompatibilitySourceSha256": "a3c6e361726e6cf12174c7d89d0c9ad128a8c7b719297deae383f21345469145",+ "installationSourceSha256": "a1c7c6f103b898216973e77ffbac0ef7572e250aa574d1a4065270e9dfa0dc2d",+ "assetOwnershipSourceSha256": "1785e3f31e5dad5a13b53e25d8cf9482a9bd89a27b6c127830aed6b81acc605c",+ "assetInstallerSourceSha256": "d3bd9514e5920d0cc3567aa50487fb534c57a6f66b8da0d3f22c5f6e499c841f",+ "credentialBindingSourceSha256": "54fd09ad430dac04df98d829061f6701e73b5bf2a0f4de836d2ac36ee511009f",+ "sidecarErrorSourceSha256": "b09af4577f8bf42eee7036b2ad9842202cfc763e72b53c3287f82c6090cdad80",+ "profileSourceSha256": "f5538b3dbefa7634a332b87d5ededcefb56aa7e5790cede1c7a0d948a548a456",+ "metadataProbeSourceSha256": "be4c8416edd27061109bc1f33d0c26071b4facbb3f651beaae6b3c0275cce727",+ "permissionToolIdentitySourceSha256": "770b47305e571a81f344883057d0e4a482a1cd59ac77d045836593a8e739deb1",+ "semanticContinuationSourceSha256": "d248e47a0fe7f2536d1e64cea0b0b410f34104800cd643d995b4473104ecc8e0",+ "runtimeHostSourceSha256": "60e5454f030e87f2afa8b1fb120b26adb126b6b17d0e5e82f49c77f76f466cbb",+ "runtimeAdapterSourceSha256": "e4c764c2c3c7dd655a965b39472bd1ad8d577d1e7258b25594b171c9429752b8",+ "runtimeSandboxSourceSha256": "92dfa53f5a3ed0062913ae417eeccec243b430d444495efde2a8e9c4c02e78ea",+ "cancellationSourceSha256": "a07d1a9e982dec0ae130c1ad1efa5bc75c6a39e013b730ba3ee45256f09ceeca",+ "agentFilesSourceSha256": "fb32f6badc13dfa22f231479509b631b2f0eba0c99b1ab9f3cd5c0c601aa03ba",+ "nativeDistributionSourceSha256": "aed327c389e957483a503cb1bb8b247ee7cd7ff4b528fb4567c39bcb4577690b"+ }+}diff --git a/packages/shared/src/agent-runner.ts b/packages/shared/src/agent-runner.tsindex 65994285f4..0429f0757a 100644--- a/packages/shared/src/agent-runner.ts+++ b/packages/shared/src/agent-runner.ts@@ -6,9 +6,10 @@ export interface AgentRunnerAvailability {defaultRunner: AgentRunner;}-export function paperclipRunnerProfileForHarness(harness: string): { provider: "codex" | "opencode" } | { provider: "acpx"; acpxAgent: "claude" } | undefined {+export function paperclipRunnerProfileForHarness(harness: string): { provider: "codex" | "opencode" } | { provider: "acpx"; acpxAgent: "claude" | "pi" } | undefined {if (harness === "codex_local") return { provider: "codex" };if (harness === "claude_local") return { provider: "acpx", acpxAgent: "claude" };+ if (harness === "pi_local") return { provider: "acpx", acpxAgent: "pi" };if (harness === "opencode_local") return { provider: "opencode" };return undefined;}@@ -28,7 +29,7 @@ function supportsLinuxLibc(libc?: "glibc" | "musl" | "unknown", version?: stringexport function paperclipRunnerSupportsPlatform(harness: string, platform: string, architecture: string, libc?: "glibc" | "musl" | "unknown", glibcVersion?: string): boolean {return !!paperclipRunnerProfileForHarness(harness)- && !(harness === "opencode_local" && platform === "linux" && architecture === "arm64")+ && !(["opencode_local", "pi_local"].includes(harness) && platform === "linux" && architecture === "arm64")&& ((platform === "linux" && supportsLinuxLibc(libc, glibcVersion) && (architecture === "x64" || architecture === "arm64"))|| (platform === "darwin" && (architecture === "arm64" || architecture === "x64")));}diff --git a/packages/shared/src/ai-connections.ts b/packages/shared/src/ai-connections.tsindex 5d3097bb5d..250eece621 100644--- a/packages/shared/src/ai-connections.ts+++ b/packages/shared/src/ai-connections.ts@@ -84,7 +84,7 @@ export const AI_CONNECTION_CAPABILITIES: Record<name: "GitHub Copilot",methods: { api_key: { adapters: ["copilot_runtime"], envKey: "COPILOT_GITHUB_TOKEN" } },},- google: { name: "Google", methods: { api_key: { adapters: ["gemini_local"], envKey: "GEMINI_API_KEY" } } },+ google: { name: "Google", methods: { api_key: { adapters: ["gemini_local", "pi_local"], envKey: "GEMINI_API_KEY" } } },anthropic: {name: "Claude",methods: {@@ -92,20 +92,20 @@ export const AI_CONNECTION_CAPABILITIES: Record<adapters: ["claude_local"],envKey: "CLAUDE_CODE_OAUTH_TOKEN",},- api_key: { adapters: ["claude_local"], envKey: "ANTHROPIC_API_KEY" },+ api_key: { adapters: ["claude_local", "pi_local"], envKey: "ANTHROPIC_API_KEY" },},},openai: {name: "OpenAI",methods: {subscription: { adapters: ["codex_local"], envKey: "CODEX_HOME" },- api_key: { adapters: ["codex_local"], envKey: "OPENAI_API_KEY" },+ api_key: { adapters: ["codex_local", "pi_local"], envKey: "OPENAI_API_KEY" },},},openrouter: {name: "OpenRouter",methods: {- api_key: { adapters: ["opencode_local"], envKey: "OPENROUTER_API_KEY" },+ api_key: { adapters: ["opencode_local", "pi_local"], envKey: "OPENROUTER_API_KEY" },},},xai: {@@ -127,6 +127,9 @@ export function isAiConnectionCompatible(if ("routing" in requirement && requirement.routing) return requirement.method === "api_key" && isAiRoutingCompatible(requirement.routing, adapterType);// A fixed binding contains identity only. The service checks authoritative// connection metadata before resolving credentials or running the harness.+ if (adapterType === "pi_local") return (requirement.method === "api_key" || ("mode" in requirement && requirement.mode === "responsible_user"))+ && ["openrouter", "openai", "anthropic", "google"].includes(requirement.provider)+ && typeof model === "string" && model.startsWith(`${requirement.provider}/`);if ("mode" in requirement && requirement.mode !== "responsible_user" && requirement.method === "api_key")return ["claude_local", "codex_local", "opencode_local", "hermes_local", "gemini_local", "grok_local", "copilot_runtime"].includes(adapterType);const methods = AI_CONNECTION_CAPABILITIES[requirement.provider].methods;diff --git a/packages/shared/src/ai-provider-routing.ts b/packages/shared/src/ai-provider-routing.tsindex ae508d4fff..7095664442 100644--- a/packages/shared/src/ai-provider-routing.ts+++ b/packages/shared/src/ai-provider-routing.ts@@ -83,7 +83,7 @@ export function aiRoutingHarness(if (adapter !== "paperclip_runner") return adapter;if (provider === "acpx" && acpxAgent === "copilot") return "copilot_runtime";const runner =- provider === "acpx" && (acpxAgent === "claude" || acpxAgent === "grok")+ provider === "acpx" && ["claude", "grok", "pi"].includes(String(acpxAgent))? acpxAgent: provider;return (@@ -93,6 +93,7 @@ export function aiRoutingHarness(codex: "codex_local",opencode: "opencode_local",grok: "grok_local",+ pi: "pi_local",} as Record<string, string>)[String(runner)] ?? "unsupported");@@ -107,6 +108,7 @@ export function isAiRoutingCompatible("claude_local","codex_local","opencode_local",+ "pi_local","hermes_local",].includes(harness);if (route.protocol === "responses") return harness === "codex_local";@@ -122,13 +124,12 @@ export function aiRoutingBaseUrl(: (route.baseUrl ?? "").replace(/\/+$/, "");}-/** OpenCode names models with a provider prefix; other harnesses use the raw ID. */export function aiRoutingModel(route: AiProviderRouting,harness: string,model: string,): string {- if (!model || harness !== "opencode_local") return model;+ if (!model || (harness !== "opencode_local" && !(harness === "pi_local" && route.kind === "openrouter"))) return model;const prefix = route.kind === "openrouter" ? "openrouter" : "paperclip";return model.startsWith(`${prefix}/`) ? model : `${prefix}/${model}`;}diff --git a/server/src/__tests__/agent-adapter-validation-routes.test.ts b/server/src/__tests__/agent-adapter-validation-routes.test.tsindex c18af24c09..c134985097 100644--- a/server/src/__tests__/agent-adapter-validation-routes.test.ts+++ b/server/src/__tests__/agent-adapter-validation-routes.test.ts@@ -722,7 +722,7 @@ describe("agent routes adapter validation", () => {const app = await createApp();const res = await requestApp(app, baseUrl => request(baseUrl).post("/api/companies/company-1/adapters/paperclip_runner/test-environment")- .send({ agentId: "11111111-1111-4111-8111-111111111111", adapterConfig: { provider: "acpx", acpxAgent: "pi" } }));+ .send({ agentId: "11111111-1111-4111-8111-111111111111", adapterConfig: { provider: "acpx", acpxAgent: "grok" } }));expect(res.status, JSON.stringify(res.body)).toBe(422);expect(res.body.details).toMatchObject({ code: "paperclip_runner_rollout_disabled" });expect(probe).not.toHaveBeenCalled();@@ -793,9 +793,65 @@ describe("agent routes adapter validation", () => {expect(mockAgentService.create).not.toHaveBeenCalled();});+ it.each(["auto", "legacy"] as const)("creates Pi through the public route with %s selection and the experimental flag off", async runner => {+ const selection = await import("../services/agent-runner-selection.js");+ vi.spyOn(selection, "resolveNewAgentRunnerForCompany").mockImplementation(async (_db, _companyId, input) =>+ selection.resolveNewAgentRunner({ ...input, target: { driver: "local", platform: "darwin", architecture: "arm64" } }));+ const app = await createApp();+ const model = "openrouter/anthropic/claude-sonnet-4.6";+ const response = await requestApp(app, baseUrl => request(baseUrl).post("/api/companies/company-1/agents").send({ name: "Pi", adapterType: "pi_local", runner, adapterConfig: { model } }));+ expect(response.status, JSON.stringify(response.body)).toBe(201);+ expect(mockAgentService.create.mock.calls.at(-1)?.[1]).toMatchObject({ adapterType: runner === "legacy" ? "pi_local" : "paperclip_runner", adapterConfig: runner === "legacy" ? { model } : { provider: "acpx", acpxAgent: "pi", model, piThinkingLevel: "low", acpxPermissionMode: "approve-all" } });+ });++ it("allows model-free Pi only as an inactive setup draft", async () => {+ const selection = await import("../services/agent-runner-selection.js");+ vi.spyOn(selection, "resolveNewAgentRunnerForCompany").mockImplementation(async (_db, _companyId, input) =>+ selection.resolveNewAgentRunner({ ...input, target: { driver: "local", platform: "darwin", architecture: "arm64" } }));+ const originalCreate = mockAgentService.create.getMockImplementation()!;+ mockAgentService.create.mockImplementation(async (...args) => ({ ...await originalCreate(...args), lifecycleHolds: ["setup"] }));+ const app = await createApp();+ const input = { name: "Pi draft", adapterType: "pi_local", adapterConfig: {} };+ const draft = await requestApp(app, baseUrl => request(baseUrl).post("/api/companies/company-1/agents")+ .send({ ...input, setupId: "00000000-0000-4000-8000-000000000092" }));+ expect(draft.status, JSON.stringify(draft.body)).toBe(201);+ expect(mockAgentService.create.mock.calls.at(-1)?.[1]).toMatchObject({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "" } });+ expect(mockAgentService.create.mock.calls.at(-1)?.[2]).toMatchObject({ setupOnly: true, runnerResolved: true });+ mockAgentService.create.mockClear();+ const active = await requestApp(app, baseUrl => request(baseUrl).post("/api/companies/company-1/agents")+ .send({ ...input, setupOnly: true }));+ expect(active.status).toBe(422);+ expect(mockAgentService.create).not.toHaveBeenCalled();+ });++ it("keeps Pi model selection empty when a provisional setup record changes harness", async () => {+ const selection = await import("../services/agent-runner-selection.js");+ vi.spyOn(selection, "resolveNewAgentRunnerForCompany").mockImplementation(async (_db, _companyId, input) =>+ selection.resolveNewAgentRunner({ ...input, target: { driver: "local", platform: "darwin", architecture: "arm64" } }));+ mockAgentService.getById.mockResolvedValue({ ...(await mockAgentService.getById()), adapterType: "process", adapterConfig: {}, status: "paused", lifecycleState: "paused", pauseReason: "setup", lifecycleHolds: ["setup"] });+ const app = await createApp();+ const response = await requestApp(app, baseUrl => request(baseUrl).patch("/api/agents/11111111-1111-4111-8111-111111111111")+ .send({ adapterType: "pi_local", runner: "auto", adapterConfig: {} }));+ expect(response.status, JSON.stringify(response.body)).toBe(200);+ expect(mockAgentService.update.mock.calls.at(-1)?.[1]).toMatchObject({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "" } });+ });++ it.each([{ thinking: "high", status: 200 }, { thinking: "medium", status: 422 }, { command: "custom-pi", status: 422 }])("validates saved Pi settings during direct adapter conversion: %j", async ({ status, ...settings }) => {+ const selection = await import("../services/agent-runner-selection.js");+ vi.spyOn(selection, "resolveNewAgentRunnerForCompany").mockImplementation(async (_db, _companyId, input) =>+ selection.resolveNewAgentRunner({ ...input, target: { driver: "local", platform: "darwin", architecture: "arm64" } }));+ mockAgentService.getById.mockResolvedValue({ ...(await mockAgentService.getById()), adapterType: "pi_local", adapterConfig: { model: "openrouter/anthropic/claude-sonnet-4.5", ...settings } });+ const app = await createApp();+ const response = await requestApp(app, baseUrl => request(baseUrl).patch("/api/agents/11111111-1111-4111-8111-111111111111")+ .send({ adapterType: "paperclip_runner", adapterConfig: {} }));+ expect(response.status, JSON.stringify(response.body)).toBe(status);+ if (status === 200) expect(mockAgentService.update.mock.calls.at(-1)?.[1]).toMatchObject({ adapterType: "paperclip_runner", adapterConfig: { acpxAgent: "pi", model: "openrouter/anthropic/claude-sonnet-4.5", piThinkingLevel: "high" } });+ else expect(mockAgentService.update).not.toHaveBeenCalled();+ });+it("keeps other native provider selection behind its existing flag", async () => {const app = await createApp();- const response = await requestApp(app, baseUrl => request(baseUrl).post("/api/companies/company-1/agents").send({ name: "Native Pi", adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "openrouter/deepseek/deepseek-v4-flash-0731" } }));+ const response = await requestApp(app, baseUrl => request(baseUrl).post("/api/companies/company-1/agents").send({ name: "Native Grok", adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "openrouter/deepseek/deepseek-v4-flash-0731" } }));expect(response.status).toBe(422);expect(response.body.details).toMatchObject({ code: "paperclip_runner_rollout_disabled" });});diff --git a/server/src/__tests__/agent-permissions-routes.test.ts b/server/src/__tests__/agent-permissions-routes.test.tsindex 95ee50519c..0c502b54cf 100644--- a/server/src/__tests__/agent-permissions-routes.test.ts+++ b/server/src/__tests__/agent-permissions-routes.test.ts@@ -1837,7 +1837,7 @@ describe("agent permission routes", () => {for (const adapterCase of sshCapableAdapterCases) {it(`allows creating a ${adapterCase.adapterType} agent with an SSH default environment`, async () => {- const expectedAdapterType = ["codex_local", "claude_local", "opencode_local"].includes(adapterCase.adapterType) ? "paperclip_runner" : adapterCase.adapterType;+ const expectedAdapterType = ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterCase.adapterType) ? "paperclip_runner" : adapterCase.adapterType;const environmentId = "33333333-3333-4333-8333-333333333333";mockEnvironmentService.getById.mockResolvedValue({id: environmentId,@@ -1879,9 +1879,10 @@ describe("agent permission routes", () => {}),{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },);- if (["codex_local", "claude_local", "opencode_local"].includes(adapterCase.adapterType)) {+ if (["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterCase.adapterType)) {if (adapterCase.adapterType === "codex_local") expect(mockAgentService.create.mock.calls[0][1].adapterConfig).toMatchObject({ provider: "codex" });else if (adapterCase.adapterType === "opencode_local") expect(mockAgentService.create.mock.calls[0][1].adapterConfig).toMatchObject({ provider: "opencode", model: adapterCase.adapterConfig.model });+ else if (adapterCase.adapterType === "pi_local") expect(mockAgentService.create.mock.calls[0][1].adapterConfig).toMatchObject({ provider: "acpx", acpxAgent: "pi", model: adapterCase.adapterConfig.model });else expect(mockAgentService.create.mock.calls[0][1].adapterConfig).toMatchObject({ provider: "acpx", acpxAgent: "claude", model: "claude-opus-5-5" });const { AGENT_RUNNER_SSH_PLATFORM_COMMAND } = await import("../services/agent-runner-selection.js");expect(mockRunSshCommand).toHaveBeenCalledWith(expect.objectContaining({ host: "qa.example.invalid" }), AGENT_RUNNER_SSH_PLATFORM_COMMAND, { timeoutMs: 10_000 });diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.tsindex 5f09e9bea3..87e8ad675e 100644--- a/server/src/__tests__/ai-connections.test.ts+++ b/server/src/__tests__/ai-connections.test.ts@@ -74,6 +74,54 @@ beforeAll(async () => {afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); });describe("managed AI connections", () => {+ it.each([+ { provider: "openrouter", envKey: "OPENROUTER_API_KEY", routed: false },+ { provider: "openrouter", envKey: "OPENROUTER_API_KEY", routed: true },+ { provider: "openai", envKey: "OPENAI_API_KEY", routed: false },+ { provider: "anthropic", envKey: "ANTHROPIC_API_KEY", routed: false },+ { provider: "google", envKey: "GEMINI_API_KEY", routed: false },+ ] as const)("prepares native Pi with isolated $provider credentials (routing=$routed)", async ({ provider, envKey, routed }) => {+ const owner = `pi-managed-${provider}-${routed}`;+ await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });+ const token = "fixture-pi-provider-key";+ const account = await service.save(companyId, owner, { provider, method: "api_key", ownership: "personal", name: owner, apiKey: token, allAgents: true, agentIds: [],+ ...(routed ? { routing: { kind: "openrouter" as const, protocol: "chat" as const, auth: "bearer" as const, models: [] } } : {}) }, token);+ if (!routed) await service.setDefault(companyId, owner, account.grantId);+ const selected = routed+ ? { provider, method: "api_key" as const, mode: "delegated" as const, ...account }+ : { provider, method: "api_key" as const, mode: "responsible_user" as const };+ const piInput = { companyId, agentId, responsibleUserId: owner, adapterType: "paperclip_runner", binding: selected,+ config: { provider: "acpx", acpxAgent: "pi", model: `${provider}/provider-model`, piThinkingLevel: "low", env: { OPENAI_API_KEY: "stale-openai", ANTHROPIC_API_KEY: "stale-anthropic" } } };+ const runtime = await prepareManagedAiRuntime(db, piInput);+ try {+ expect(runtime.config).toMatchObject({ provider: "acpx", acpxAgent: "pi", model: piInput.config.model, env: { OPENCODE_CONFIG_CONTENT: "", PAPERCLIP_PI_PROVIDERS: "" } });+ for (const key of ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY", "CODEX_API_KEY"]) expect(runtime.config.env[key]).toBe(key === envKey ? token : "");+ expect(runtime.attribution).toMatchObject({ connectionId: account.connectionId, grantId: account.grantId, provider });+ } finally { await runtime.cleanup(); }+ await expect(prepareManagedAiRuntime(db, { ...piInput, config: { ...piInput.config, env: { PAPERCLIP_PI_PROVIDERS: "{}" } } })).rejects.toThrow("routing is incompatible");+ });++ it.each([200, 401])("reverifies native Pi OpenRouter keys without requiring the Legacy Pi CLI (HTTP %s)", async status => {+ const owner = `pi-adoption-${status}`;+ await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });+ const token = `fixture-pi-adoption-${status}`;+ const account = await service.save(companyId, owner, { provider: "openrouter", method: "api_key", ownership: "personal", name: owner, apiKey: token, allAgents: true, agentIds: [], routing: { kind: "openrouter", protocol: "chat", auth: "bearer", models: [] } }, token);+ const selected = { provider: "openrouter", method: "api_key", mode: "delegated", ...account } as const;+ const runtime = await prepareManagedAiRuntime(db, { companyId, agentId, responsibleUserId: owner, adapterType: "paperclip_runner", binding: selected, config: { provider: "acpx", acpxAgent: "pi", model: "openrouter/anthropic/claude-sonnet-4.5" } });+ const { requireServerAdapter } = await import("../adapters/index.js");+ const { agentEnvironmentTestService } = await import("../services/agent-environment-test.js");+ const native = vi.spyOn(requireServerAdapter("paperclip_runner"), "testEnvironment").mockResolvedValue({ adapterType: "paperclip_runner", status: "pass", testedAt: new Date().toISOString(), checks: [{ code: "acpx_runtime_ready", level: "info", message: "Pinned Pi runtime verified" }] });+ const legacy = vi.spyOn(requireServerAdapter("pi_local"), "testEnvironment").mockRejectedValue(new Error("Legacy Pi CLI must not be required"));+ const request = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({ data: {} }), { status }));+ try {+ const result = await agentEnvironmentTestService(db).testManagedEnvironment("paperclip_runner", { companyId, adapterType: "paperclip_runner", config: runtime.config }, selected, runtime, agentId);+ expect(result.status).toBe(status === 200 ? "pass" : "fail");+ expect(result.checks).toContainEqual(expect.objectContaining({ code: status === 200 ? "ai_connection_api_key_reverified" : "ai_connection_api_key_rejected" }));+ expect(legacy).not.toHaveBeenCalled();+ expect(request).toHaveBeenCalled();+ } finally { native.mockRestore(); legacy.mockRestore(); request.mockRestore(); await runtime.cleanup(); }+ });+it("defers a new plugin agent's Copilot check until its saved-agent lifecycle can acquire the computer", async () => {const { errorHandler } = await import("../middleware/index.js");const owner = "copilot-plugin-bootstrap", pluginId = randomUUID();diff --git a/server/src/__tests__/ai-provider-routing.test.ts b/server/src/__tests__/ai-provider-routing.test.tsindex 4e46b0f80d..c5f520a715 100644--- a/server/src/__tests__/ai-provider-routing.test.ts+++ b/server/src/__tests__/ai-provider-routing.test.ts@@ -1,12 +1,33 @@import { describe, it, expect } from "vitest";import {aiProviderRoutingSchema,+ aiRoutingHarness,+ aiRoutingModel,createAiConnectionSchema,isAiConnectionCompatible,} from "@paperclipai/shared";import { managedProviderRouting } from "../services/ai-provider-routing.js";describe("provider routing", () => {+ it("routes managed OpenRouter accounts to direct and native Pi without OpenCode configuration", () => {+ const routing = aiProviderRoutingSchema.parse({ kind: "openrouter", protocol: "chat" });+ expect(aiRoutingHarness("paperclip_runner", "acpx", "pi")).toBe("pi_local");+ for (const adapterType of ["pi_local", "paperclip_runner"]) {+ expect(isAiConnectionCompatible({ provider: "openrouter", method: "api_key", routing }, adapterType, "openrouter/anthropic/model", "acpx", "pi")).toBe(true);+ }+ expect(aiRoutingModel(routing, "pi_local", "anthropic/model")).toBe("openrouter/anthropic/model");+ expect(aiRoutingModel(routing, "pi_local", "openrouter/anthropic/model")).toBe("openrouter/anthropic/model");+ const projected = managedProviderRouting(routing, "pi_local", "selected-pi-key", "anthropic/model");+ expect(projected).toMatchObject({ config: { model: "openrouter/anthropic/model" }, env: { OPENROUTER_API_KEY: "selected-pi-key" } });+ expect(projected.env).not.toHaveProperty("OPENCODE_CONFIG_CONTENT");+ expect(isAiConnectionCompatible({ provider: "openai", method: "api_key", routing: aiProviderRoutingSchema.parse({ kind: "gateway", protocol: "chat", baseUrl: "https://gateway.example/v1" }) }, "pi_local", "custom/model")).toBe(false);+ });+ it.each(["openai", "anthropic", "google", "openrouter"] as const)("accepts Pi %s API keys only for matching models", provider => {+ expect(isAiConnectionCompatible({ provider, method: "api_key" }, "paperclip_runner", `${provider}/model`, "acpx", "pi")).toBe(true);+ expect(isAiConnectionCompatible({ provider, method: "subscription" }, "pi_local", `${provider}/model`)).toBe(false);+ expect(isAiConnectionCompatible({ provider, method: "subscription", mode: "responsible_user" }, "pi_local", `${provider}/model`)).toBe(true);+ expect(isAiConnectionCompatible({ provider, method: "api_key" }, "pi_local", "different/model")).toBe(false);+ });it.each(["https://user:[email protected]/v1","https://gateway.example/v1?key=secret",diff --git a/server/src/__tests__/dot-runner.test.ts b/server/src/__tests__/dot-runner.test.tsindex c1e34beb64..d1448197f3 100644--- a/server/src/__tests__/dot-runner.test.ts+++ b/server/src/__tests__/dot-runner.test.ts@@ -109,7 +109,7 @@ describe("durable Dot Runner integration", () => {expect(() => resolveNativeRuntimeMode(input)).toThrow("experimental settings");expect(resolveNativeRuntimeMode({ ...input, enabled: false, dotEnabled: true })).toMatchObject({ kind: "native", profile: { backend: "openai_dot_mcp" } });expect(() => resolveNativeRuntimeMode({ ...input, enabled: false, dotEnabled: true,- adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "anthropic/claude-sonnet-4-6" },+ adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "anthropic/claude-sonnet-4-6" },})).toThrow("Paperclip Runner is experimental and disabled");expect(resolveHeartbeatNativeRuntimeMode({ ...input, enabled: false, dotEnabled: false,persisted: { runtimeMode: "native", runtimeModeReason: null, runtimeModeResolvedAt: new Date(), driverKind: "openai_dot_mcp" },diff --git a/server/src/__tests__/native-status-arbiter-corpus.test.ts b/server/src/__tests__/native-status-arbiter-corpus.test.tsindex 432f04603f..6f58845dfd 100644--- a/server/src/__tests__/native-status-arbiter-corpus.test.ts+++ b/server/src/__tests__/native-status-arbiter-corpus.test.ts@@ -850,7 +850,7 @@ describe("P6-31 Section 18.13 executable status-authority corpus", () => {) {const experimentalAdapterConfig = {provider: "acpx",- acpxAgent: "pi",+ acpxAgent: "grok",model: "anthropic/claude-sonnet-4-6",};const runtimeConfig = {diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.tsindex f519ed3991..02c9d65ac3 100644--- a/server/src/routes/agents.ts+++ b/server/src/routes/agents.ts@@ -1865,7 +1865,7 @@ export function agentRoutes(throw unprocessable("Enable Grok Bot, Assistant connections (MCP), and Paperclip Runner before connecting this agent.", { code: "paperclip_runner_grok_disabled" });} else if (!([undefined, "codex", "opencode"].includes(asRecord(config)?.provider as string | undefined)) &&!(asRecord(config)?.provider === "acpx" && asRecord(config)?.acpxAgent === "copilot") &&- agentHarnessType("paperclip_runner", asRecord(config) ?? {}) !== "claude_local" &&+ !["claude_local", "pi_local"].includes(agentHarnessType("paperclip_runner", asRecord(config) ?? {})) &&experimental.enableNativeRunner !== true) {throw unprocessable("Paperclip Runner is experimental and disabled on this instance.",@@ -1936,12 +1936,15 @@ export function agentRoutes(}if (["openai_dot", "muse"].includes(String(input.nextAdapterConfig.provider))) return input.nextAdapterConfig;const defaults = paperclipRunnerTransitionConfig(input.previousAdapterType, input.previousAdapterConfig.model, input.nextAdapterConfig.provider);- if (!["claude_local", "codex_local", "opencode_local"].includes(input.previousAdapterType)+ if (!["claude_local", "codex_local", "opencode_local", "pi_local"].includes(input.previousAdapterType)&& !isPaperclipRunnerProvider(input.nextAdapterConfig.provider)) {throw unprocessable("Select a Paperclip Runner provider before converting this agent.");}const next = { ...defaults, ...input.nextAdapterConfig };- if (!asNonEmptyString(next.model)) next.model = defaults.model;+ if (next.provider === "acpx" && next.acpxAgent === "pi") {+ next.model = input.nextAdapterConfig.model+ ?? (input.previousAdapterType === "pi_local" ? input.previousAdapterConfig.model : "");+ } else if (!asNonEmptyString(next.model)) next.model = defaults.model;return normalizeLegacyRunnerProvider(next);}@@ -2175,11 +2178,12 @@ export function agentRoutes(adapterType: input.adapterType ?? null,},);- const incompleteOpenCodeSetup = input.setupOnly && input.adapterType === "paperclip_runner"- && normalizedAdapterConfig.provider === "opencode"+ const incompleteModelSetup = input.setupOnly && input.adapterType === "paperclip_runner"+ && (normalizedAdapterConfig.provider === "opencode"+ || (normalizedAdapterConfig.provider === "acpx" && normalizedAdapterConfig.acpxAgent === "pi"))&& (normalizedAdapterConfig.model === undefined || normalizedAdapterConfig.model === "");// Inactive drafts can precede model selection. Test/hire always validate the complete profile.- if (!incompleteOpenCodeSetup) await assertAdapterConfigConstraints(+ if (!incompleteModelSetup) await assertAdapterConfigConstraints(input.companyId,input.adapterType,input.constraintAdapterConfig@@ -5378,12 +5382,16 @@ export function agentRoutes(// it gets the selectable check; keeping the agent's current adapter (even// one since disabled) stays allowed, so a disabled harness does not make an// existing agent uneditable.- if (runner !== undefined) {+ const requestedRunnerConfig = asRecord(patchData.adapterConfig) ?? {};+ const convertingPi = existing.adapterType === "pi_local" && patchData.adapterType === "paperclip_runner"+ && (requestedRunnerConfig.provider === undefined+ || (requestedRunnerConfig.provider === "acpx" && [undefined, "pi"].includes(requestedRunnerConfig.acpxAgent as string | undefined)));+ if (runner !== undefined || convertingPi) {await assertCanConfigureAgentSetup(req, existing);const config = hasOwn(patchData, "adapterConfig") ? { ...(replaceAdapterConfig ? {} : existing.adapterConfig), ...asRecord(patchData.adapterConfig) } : existing.adapterConfig;Object.assign(patchData, await resolveNewAgentRunnerForCompany(db, existing.companyId, {- adapterType: typeof patchData.adapterType === "string" ? patchData.adapterType : existing.adapterType,- adapterConfig: config, runner, setupOnly: existing.lifecycleHolds?.includes("setup"),+ adapterType: convertingPi ? "pi_local" : typeof patchData.adapterType === "string" ? patchData.adapterType : existing.adapterType,+ adapterConfig: config, runner: runner ?? "paperclip", setupOnly: existing.lifecycleHolds?.includes("setup"),defaultEnvironmentId: hasOwn(patchData, "defaultEnvironmentId") ? patchData.defaultEnvironmentId as string | null : existing.defaultEnvironmentId,}));}diff --git a/server/src/services/agent-environment-test.ts b/server/src/services/agent-environment-test.tsindex a92ae12f66..f079e736f2 100644--- a/server/src/services/agent-environment-test.ts+++ b/server/src/services/agent-environment-test.ts@@ -548,7 +548,10 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin// requirement stays for subscriptions: a stored login is a file layout// only a provider CLI reads, so proving the runtime lane can consume it// takes a real hello turn.- if (resolvedMethod === "api_key" && !context.config.managedAiRouting) {+ const nativePiOpenRouter = adapterType === "paperclip_runner" && context.config.provider === "acpx"+ && context.config.acpxAgent === "pi" && binding.provider === "openrouter"+ && asRecord(context.config.managedAiRouting)?.kind === "openrouter";+ if (resolvedMethod === "api_key" && (!context.config.managedAiRouting || nativePiOpenRouter)) {const envKey = AI_CONNECTION_CAPABILITIES[binding.provider].methods.api_key?.envKey;const key = envKey ? parseObject(context.config.env)[envKey] : undefined;try {diff --git a/server/src/services/agent-runner-selection.test.ts b/server/src/services/agent-runner-selection.test.tsindex d598e0baf2..8c01150977 100644--- a/server/src/services/agent-runner-selection.test.ts+++ b/server/src/services/agent-runner-selection.test.ts@@ -74,9 +74,52 @@ describe("server-owned Codex runner selection", () => {expect(resolveNewAgentRunner(resolved)).toEqual(resolved);expect(input.adapterConfig).toHaveProperty("search", false);});- it.each(["grok_local", "cursor", "pi_local", "process", "external"])("keeps %s default unchanged", adapterType => {+ it.each(["grok_local", "cursor", "process", "external"])("keeps %s default unchanged", adapterType => {expect(resolveNewAgentRunner({ adapterType, target, adapterConfig: { custom: "preserved" } })).toEqual({ adapterType, adapterConfig: { custom: "preserved" } });});+ it.each(qualifiedTargets.filter(target => !(target.platform === "linux" && target.architecture === "arm64")))("defaults Pi to native on $platform/$architecture and round trips exact thinking", target => {+ const adapterConfig = { model: "openrouter/anthropic/claude-sonnet-4.6", thinking: "high", command: "pi", env: { OPENROUTER_API_KEY: { type: "secret_ref", secretId: "connection" } }, cwd: "/workspace" };+ const selected = resolveNewAgentRunner({ adapterType: "pi_local", adapterConfig, target });+ expect(agentRunnerAvailability("pi_local", target).defaultRunner).toBe("paperclip");+ expect(selected).toEqual({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "pi", model: adapterConfig.model, piThinkingLevel: "high", acpxPermissionMode: "approve-all", lifecycleMode: "per_turn", cwd: adapterConfig.cwd, env: adapterConfig.env } });+ expect(resolveNewAgentRunner(selected)).toEqual(selected);+ expect(resolveNewAgentRunner({ ...selected, runner: "legacy" })).toEqual({ adapterType: "pi_local", adapterConfig: { model: adapterConfig.model, thinking: "high", cwd: adapterConfig.cwd, env: adapterConfig.env } });+ });+ it.each(["minimal", "medium", "xhigh"])("keeps unsupported Pi thinking %s explicit", thinking => {+ const input = { adapterType: "pi_local", target, adapterConfig: { model: "custom/model", thinking } };+ expect(() => resolveNewAgentRunner(input)).toThrow("Legacy runner");+ expect(resolveNewAgentRunner({ ...input, runner: "legacy" })).toEqual({ adapterType: input.adapterType, adapterConfig: input.adapterConfig });+ });+ it.each([{ command: "custom-pi" }, { args: ["--extension", "custom.ts"] }, { extraArgs: "--no-tools" }, { stdoutLogMode: "raw" }, { thinking: "low", piThinkingLevel: "high" }])("rejects unsupported Pi configuration %j", extra => {+ expect(() => resolveNewAgentRunner({ adapterType: "pi_local", target, adapterConfig: { model: "custom/model", ...extra } })).toThrow("Legacy runner");+ });+ it.each([undefined, "", "model", "provider/"])("requires a Pi provider/model outside inactive setup: %s", model => {+ expect(() => resolveNewAgentRunner({ adapterType: "pi_local", target, adapterConfig: { model } })).toThrow("provider/model");+ });+ it("allows an inactive Pi draft before model selection and preserves saved native policy", () => {+ expect(resolveNewAgentRunner({ adapterType: "pi_local", target, setupOnly: true })).toMatchObject({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "", piThinkingLevel: "low" } });+ const saved = { adapterType: "paperclip_runner", target, adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "custom/model", piThinkingLevel: "max", acpxPermissionMode: "approve-reads", lifecycleMode: "warm", idleTimeoutMs: 1234 } };+ expect(resolveNewAgentRunner(saved)).toEqual({ adapterType: saved.adapterType, adapterConfig: saved.adapterConfig });+ expect(() => resolveNewAgentRunner({ ...saved, runner: "legacy" })).toThrow("Legacy Pi cannot honor");+ });+ it.each([{ driver: "local", platform: "win32", architecture: "x64" }, { driver: "local", platform: "linux", architecture: "arm64", libc: "glibc" as const, glibcVersion: "2.39" }, { driver: "ssh", platform: "linux", architecture: "arm64", libc: "glibc" as const, glibcVersion: "2.39" }, { driver: "sandbox" }, { driver: "local", platform: "linux", architecture: "x64", libc: "musl" as const }])("keeps Pi legacy on unqualified $driver/$platform targets", target => {+ const input = { adapterType: "pi_local", adapterConfig: { model: "custom/model", thinking: "medium" }, target };+ expect(agentRunnerAvailability("pi_local", target).defaultRunner).toBe("legacy");+ expect(resolveNewAgentRunner(input)).toEqual({ adapterType: input.adapterType, adapterConfig: input.adapterConfig });+ expect(() => resolveNewAgentRunner({ ...input, runner: "paperclip" })).toThrow("unavailable");+ });+ it.each(["minimal", "medium", "xhigh"])("honors an explicit Legacy Pi thinking edit to %s when resuming a native draft", thinking => {+ expect(resolveNewAgentRunner({ adapterType: "paperclip_runner", runner: "legacy", adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "custom/model", piThinkingLevel: "max", thinking } })).toEqual({ adapterType: "pi_local", adapterConfig: { model: "custom/model", thinking } });+ });+ it("honors disabled and overridden Pi adapters", () => {+ const input = { adapterType: "pi_local", target, adapterConfig: { model: "custom/model" } };+ state.overridden.add("pi_local");+ expect(resolveNewAgentRunner(input).adapterType).toBe("pi_local");+ state.overridden.clear(); state.disabled = ["paperclip_runner"];+ expect(resolveNewAgentRunner(input).adapterType).toBe("pi_local");+ state.disabled = ["pi_local"];+ expect(() => resolveNewAgentRunner(input)).toThrow("Pi is disabled");+ });it.each(qualifiedTargets.filter(target => !(target.platform === "linux" && target.architecture === "arm64")))("defaults OpenCode to its native provider on $platform/$architecture", target => {const adapterConfig = { model: "openrouter/anthropic/claude-sonnet-4.6", dangerouslySkipPermissions: true, command: "opencode", env: { OPENROUTER_API_KEY: { type: "secret_ref", secretId: "connection" } }, cwd: "/workspace", instructionsFilePath: "/workspace/AGENTS.md" };const selected = resolveNewAgentRunner({ adapterType: "opencode_local", adapterConfig, target });@@ -422,11 +465,12 @@ describe("server-owned Codex runner selection", () => {});describe("Codex creation runner contract", () => {- it("graduates only Codex and retains saved provider identity", () => {+ it("graduates qualified harnesses and retains saved provider identity", () => {expect(paperclipRunnerProfileForHarness("codex_local")).toEqual({ provider: "codex" });expect(paperclipRunnerProfileForHarness("claude_local")).toEqual({ provider: "acpx", acpxAgent: "claude" });expect(paperclipRunnerProfileForHarness("opencode_local")).toEqual({ provider: "opencode" });- for (const harness of ["grok_local", "cursor", "pi_local", "process"]) expect(paperclipRunnerProfileForHarness(harness)).toBeUndefined();+ expect(paperclipRunnerProfileForHarness("pi_local")).toEqual({ provider: "acpx", acpxAgent: "pi" });+ for (const harness of ["grok_local", "cursor", "process"]) expect(paperclipRunnerProfileForHarness(harness)).toBeUndefined();expect(agentHarnessType("paperclip_runner", { provider: "codex" })).toBe("codex_local");expect(agentHarnessType("paperclip_runner", { provider: "acpx", acpxAgent: "claude" })).toBe("claude_local");expect(agentHarnessType("paperclip_runner", { provider: "unknown" })).toBe("unknown");diff --git a/server/src/services/agent-runner-selection.ts b/server/src/services/agent-runner-selection.tsindex 27c3fb80e2..2727a602f0 100644--- a/server/src/services/agent-runner-selection.ts+++ b/server/src/services/agent-runner-selection.ts@@ -23,7 +23,7 @@ export interface AgentRunnerSelection {function runnerAdaptersAvailable(harness: string, driver: string): boolean {const disabled = new Set(getDisabledAdapterTypes());- return ["codex_local", "claude_local", "opencode_local"].includes(harness)+ return ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(harness)&& !disabled.has(harness) && !disabled.has("paperclip_runner")&& !!findActiveServerAdapter(harness) && !!findActiveServerAdapter("paperclip_runner")&& !hasActiveAdapterOverride(harness) && !hasActiveAdapterOverride("paperclip_runner")@@ -45,6 +45,28 @@ function incompatible(fields: string[]): never {throw unprocessable(`Paperclip Runner cannot honor these settings: ${fields.join(", ")}. Remove them or select Legacy runner in Advanced.`, { code: "agent_runner_config_incompatible", fields });}+function resolvePiRunnerConfig(config: Record<string, unknown>): Record<string, unknown> {+ const unsupported = ["extraArgs", "args", "modelReasoningEffort", "reasoningEffort", "effort"]+ .filter(key => config[key] !== undefined && config[key] !== "" && !(Array.isArray(config[key]) && config[key].length === 0));+ if (config.command && config.command !== "pi") unsupported.push("command");+ if (config.model !== undefined && typeof config.model !== "string") unsupported.push("model");+ if (config.stdoutLogMode !== undefined && config.stdoutLogMode !== "compact") unsupported.push("stdoutLogMode");+ const thinking = config.piThinkingLevel ?? config.thinking;+ if (thinking !== undefined && !["off", "low", "high", "max"].includes(String(thinking))) unsupported.push("thinking");+ if (config.piThinkingLevel !== undefined && config.thinking !== undefined && config.piThinkingLevel !== config.thinking) unsupported.push("thinking", "piThinkingLevel");+ if (unsupported.length) incompatible(unsupported);+ const translated = { ...config };+ for (const key of ["command", "extraArgs", "args", "thinking", "stdoutLogMode"]) delete translated[key];+ return {+ ...translated,+ provider: "acpx", acpxAgent: "pi",+ model: typeof config.model === "string" ? config.model.trim() : "",+ piThinkingLevel: thinking ?? "low",+ acpxPermissionMode: config.acpxPermissionMode ?? "approve-all",+ lifecycleMode: config.lifecycleMode ?? "per_turn",+ };+}+function resolveOpenCodeRunnerConfig(config: Record<string, unknown>): Record<string, unknown> {const unsupported = ["extraArgs", "args", "variant", "modelReasoningEffort", "reasoningEffort", "effort"].filter(key => config[key] !== undefined && config[key] !== "" && !(Array.isArray(config[key]) && config[key].length === 0));@@ -103,12 +125,25 @@ export function resolveNewAgentRunner(input: AgentRunnerSelection): { adapterTyplet config = { ...input.adapterConfig };const harness = agentHarnessType(adapterType, config);const native = adapterType === "paperclip_runner";- if (["codex_local", "claude_local", "opencode_local"].includes(adapterType) && getDisabledAdapterTypes().includes(adapterType)) throw unprocessable(`${adapterType === "opencode_local" ? "OpenCode" : adapterType === "claude_local" ? "Claude" : "Codex"} is disabled on this instance. Enable its adapter or choose another harness.`, { code: "agent_runner_unavailable" });+ if (["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && getDisabledAdapterTypes().includes(adapterType)) throw unprocessable(`${adapterType === "pi_local" ? "Pi" : adapterType === "opencode_local" ? "OpenCode" : adapterType === "claude_local" ? "Claude" : "Codex"} is disabled on this instance. Enable its adapter or choose another harness.`, { code: "agent_runner_unavailable" });if (native && (input.runner === undefined || input.runner === "paperclip" || (harness !== "codex_local" && input.runner !== "legacy"))) return { adapterType, adapterConfig: normalizeLegacyRunnerProvider(config) };const availability = agentRunnerAvailability(harness, input.target);const choice = input.runner ?? "auto";const useNative = choice === "paperclip" || (choice === "auto" && availability.defaultRunner === "paperclip");if (!useNative) {+ if (harness === "pi_local") {+ if (!native) return { adapterType, adapterConfig: config };+ const thinking = config.thinking ?? config.piThinkingLevel ?? "low";+ const unsupported = [+ ...(config.acpxPermissionMode !== undefined && config.acpxPermissionMode !== "approve-all" ? ["acpxPermissionMode"] : []),+ ...(config.lifecycleMode !== undefined && config.lifecycleMode !== "per_turn" ? ["lifecycleMode"] : []),+ ...(config.acpxSessionMode !== undefined ? ["acpxSessionMode"] : []),+ ...(!["off", "minimal", "low", "medium", "high", "xhigh"].includes(String(thinking)) ? [config.thinking !== undefined ? "thinking" : "piThinkingLevel"] : []),+ ];+ if (unsupported.length) throw unprocessable(`Legacy Pi cannot honor these settings: ${unsupported.join(", ")}. Keep Paperclip Runner or explicitly choose compatible settings.`, { code: "agent_runner_config_incompatible", fields: unsupported });+ for (const key of ["provider", "acpxAgent", "acpxPermissionMode", "acpxSessionMode", "piThinkingLevel", "lifecycleMode", "idleTimeoutMs"]) delete config[key];+ return { adapterType: "pi_local", adapterConfig: { ...config, thinking } };+ }if (harness === "opencode_local") {if (!native) return { adapterType, adapterConfig: config };if (config.opencodePermissionMode !== undefined && config.opencodePermissionMode !== "allow") incompatible(["opencodePermissionMode"]);@@ -138,6 +173,17 @@ export function resolveNewAgentRunner(input: AgentRunnerSelection): { adapterTyp? "Paperclip Runner is unavailable for this sandbox. Choose an immutable OCI image digest and run its environment connection probe to qualify the OS, architecture and libc, or select Legacy runner in Advanced.": "Paperclip Runner is unavailable for this harness and environment. Select Legacy runner in Advanced.", { code: "agent_runner_unavailable" });if (native) return { adapterType, adapterConfig: normalizeLegacyRunnerProvider(config) };+ if (harness === "pi_local") {+ config = resolvePiRunnerConfig(config);+ if (input.setupOnly && !config.model) return { adapterType: "paperclip_runner", adapterConfig: config };+ if (typeof config.model !== "string" || !/^[^/\s]+\/\S+$/.test(config.model)) throw unprocessable("Pi requires an explicit provider/model. Select a model before testing or hiring.", { code: "agent_runner_config_incompatible", fields: ["model"] });+ try { resolvePaperclipRunnerNativeProviderInput({ backend: "acpx_runtime", adapterConfig: config }); }+ catch (error) {+ if (error instanceof PaperclipRunnerProviderProfileError) throw unprocessable(error.message, { code: error.code });+ throw error;+ }+ return { adapterType: "paperclip_runner", adapterConfig: config };+ }if (harness === "opencode_local") {config = resolveOpenCodeRunnerConfig(config);if (input.setupOnly && !config.model) return { adapterType: "paperclip_runner", adapterConfig: config };@@ -212,7 +258,7 @@ export function resolveNewAgentRunner(input: AgentRunnerSelection): { adapterTyp}export async function resolveNewAgentRunnerForCompany(db: Db, companyId: string, input: AgentRunnerSelection & { defaultEnvironmentId?: string | null }) {- if (!["codex_local", "claude_local", "opencode_local"].includes(agentHarnessType(input.adapterType ?? "process", input.adapterConfig))+ if (!["codex_local", "claude_local", "opencode_local", "pi_local"].includes(agentHarnessType(input.adapterType ?? "process", input.adapterConfig))|| input.runner === "legacy" || (input.adapterType === "paperclip_runner" && (input.runner === undefined || input.runner === "paperclip"))) return resolveNewAgentRunner(input);const target = await resolveAgentRunnerTargetForCompany(db, companyId, input.defaultEnvironmentId);return resolveNewAgentRunner({ ...input, target });@@ -249,7 +295,7 @@ export async function resolveAgentRunnerTargetForCompany(db: Db, companyId: striconst qualified = await readSandboxPlatformQualification(db, environment, companyId);if (qualified) target = { driver, ...qualified };}- if (driver === "ssh" && environment && ["codex_local", "claude_local", "opencode_local"].some(harness => runnerAdaptersAvailable(harness, driver))) {+ if (driver === "ssh" && environment && ["codex_local", "claude_local", "opencode_local", "pi_local"].some(harness => runnerAdaptersAvailable(harness, driver))) {const parsed = await resolveEnvironmentDriverConfigForRuntime(db, companyId, environment);if (parsed.driver !== "ssh") throw unprocessable("The selected SSH environment is unavailable.");let output: string;diff --git a/server/src/services/ai-connection-runtime.ts b/server/src/services/ai-connection-runtime.tsindex ca89b1621c..2620e8cbb5 100644--- a/server/src/services/ai-connection-runtime.ts+++ b/server/src/services/ai-connection-runtime.ts@@ -53,6 +53,7 @@ export const AI_AUTH_ENV_KEYS = ["OPENCODE_CONFIG","OPENCODE_CONFIG_DIR","PAPERCLIP_OPENCODE_PROVIDERS",+ "PAPERCLIP_PI_PROVIDERS","ANTHROPIC_BASE_URL","OPENAI_BASE_URL","XAI_BASE_URL",@@ -247,7 +248,7 @@ export async function prepareManagedAiRuntime("CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","PAPERCLIP_OPENCODE_PROVIDERS",- "PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_CODEX_PROVIDERS", "OPENCODE_CONFIG_CONTENT", "OPENCODE_CONFIG", "OPENCODE_CONFIG_DIR", "GOOGLE_GEMINI_BASE_URL", "ANTHROPIC_BEDROCK_BASE_URL",+ "PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_CODEX_PROVIDERS", "PAPERCLIP_PI_PROVIDERS", "OPENCODE_CONFIG_CONTENT", "OPENCODE_CONFIG", "OPENCODE_CONFIG_DIR", "GOOGLE_GEMINI_BASE_URL", "ANTHROPIC_BEDROCK_BASE_URL",]) {if (configuredEnv[key])throw unprocessable(@@ -339,7 +340,7 @@ export async function prepareManagedAiRuntime(if (!routing && subscriptionFile) await writeFile(authFile, value, { mode: 0o600 });else if (!routing) env[capability.envKey] = value;if (- !routing && input.binding.provider === "openai" &&+ !routing && input.binding.provider === "openai" && harness === "codex_local" &&selection.attribution.method === "api_key") {env.CODEX_API_KEY = value;@@ -347,13 +348,13 @@ export async function prepareManagedAiRuntime(mode: 0o600,});}- if (!routing && input.binding.provider === "openrouter") {+ if (!routing && input.binding.provider === "openrouter" && harness === "opencode_local") {env.OPENCODE_CONFIG_CONTENT = JSON.stringify({provider: { openrouter: { options: { apiKey: value, headers: OPENROUTER_ATTRIBUTION_HEADERS } } },});env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";}- if (!routing && input.binding.provider === "google") {+ if (!routing && input.binding.provider === "google" && harness === "gemini_local") {// Gemini headless CLI requires an explicit auth choice even with an API key.// Seed only the disposable connection home, never the operator's settings.const geminiHome = path.join(home, ".gemini");diff --git a/server/src/services/ai-provider-routing.ts b/server/src/services/ai-provider-routing.tsindex 22f86d6063..5efc70561b 100644--- a/server/src/services/ai-provider-routing.ts+++ b/server/src/services/ai-provider-routing.ts@@ -42,6 +42,9 @@ export function managedProviderRouting(env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model;env.CLAUDE_CODE_SUBAGENT_MODEL = model;}+ } else if (harness === "pi_local" && route.kind === "openrouter") {+ env.OPENROUTER_API_KEY = credential;+ config.model = aiRoutingModel(route, harness, model);} else if (harness === "opencode_local") {const provider = route.kind === "openrouter" ? "openrouter" : "paperclip";if (route.kind === "openrouter") env.OPENROUTER_API_KEY = credential;diff --git a/server/src/services/built-in-agents.ts b/server/src/services/built-in-agents.tsindex b35c86afe3..bdadbe6c1c 100644--- a/server/src/services/built-in-agents.ts+++ b/server/src/services/built-in-agents.ts@@ -1762,7 +1762,7 @@ export function builtInAgentService(db: Db) {const adapterConfig = resolvedInput.adapterConfig ?? existing.adapterConfig;assertAdapterAllowed(definition, adapterType, adapterConfig);const selectedHarness = agentHarnessType(adapterType, adapterConfig);- const sameQualifiedHarness = ["codex_local", "claude_local", "opencode_local"].includes(selectedHarness)+ const sameQualifiedHarness = ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(selectedHarness)&& agentHarnessType(existing.adapterType, existing.adapterConfig) === selectedHarness;const runner = resolvedInput.runner ?? (sameQualifiedHarness && existing.metadata?.paperclipBuiltInSetupRequired !== true? agentRunner(existing.adapterType) : undefined);diff --git a/server/src/services/company-portability.ts b/server/src/services/company-portability.tsindex e88eb0a933..e6868da382 100644--- a/server/src/services/company-portability.ts+++ b/server/src/services/company-portability.ts@@ -5307,7 +5307,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {"OpenAI Dot is experimental and disabled on this instance.",{ code: "paperclip_runner_dot_disabled" },);- } else if (config.provider !== "codex" && config.provider !== "opencode" && config.provider !== undefined && agentHarnessType("paperclip_runner", config) !== "claude_local" && experimental.enableNativeRunner !== true) {+ } else if (config.provider !== "codex" && config.provider !== "opencode" && config.provider !== undefined && !["claude_local", "pi_local"].includes(agentHarnessType("paperclip_runner", config)) && experimental.enableNativeRunner !== true) {throw unprocessable("Paperclip Runner is experimental and disabled on this instance.",{ code: "paperclip_runner_rollout_disabled" },@@ -5651,7 +5651,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {runner = agentRunner(existingImportAgent.adapterType);}}- const retainedNative = runner === "paperclip" && ["codex_local", "claude_local", "opencode_local"].includes(selectedHarness)+ const retainedNative = runner === "paperclip" && ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(selectedHarness)? [manifestAgent, existingImportAgent].find((agent) => agent?.adapterType === "paperclip_runner"&& agentHarnessType(agent.adapterType, agent.adapterConfig) === selectedHarness): undefined;diff --git a/server/src/services/native-runtime/runtime-mode.test.ts b/server/src/services/native-runtime/runtime-mode.test.tsindex 8c4f02e48f..381d77fc2d 100644--- a/server/src/services/native-runtime/runtime-mode.test.ts+++ b/server/src/services/native-runtime/runtime-mode.test.ts@@ -54,7 +54,7 @@ describe("resolveNativeRuntimeMode", () => {expect(resolveNativeRuntimeMode({ ...eligible, enabled: false,adapterConfig: { provider: "acpx", acpxAgent: "copilot", model: "gpt-5.6-luna" },})).toMatchObject({ kind: "native", profile: { backend: "acpx_runtime" } });- for (const acpxAgent of ["pi", "cursor", "codex"]) {+ for (const acpxAgent of ["grok", "cursor", "codex"]) {expect(() => resolveNativeRuntimeMode({ ...eligible, enabled: false,adapterConfig: { provider: "acpx", acpxAgent, model: "gpt-5.6-luna" },})).toThrow(expect.objectContaining({ code: "paperclip_runner_rollout_disabled" }));@@ -96,16 +96,22 @@ describe("resolveNativeRuntimeMode", () => {})).toMatchObject({ kind: "native", profile: { backend: "opencode_server" } });});- it("still rejects Pi while the rollout flag is disabled", () => {+ it("still rejects Grok while the rollout flag is disabled", () => {expect(() => resolveNativeRuntimeMode({...eligible,enabled: false,- adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "openrouter/deepseek/deepseek-v4-flash-0731" },+ adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "openrouter/deepseek/deepseek-v4-flash-0731" },})).toThrow(expect.objectContaining({code: "paperclip_runner_rollout_disabled",}));});+ it("admits Pi without the generic rollout flag", () => {+ expect(resolveNativeRuntimeMode({ ...eligible, enabled: false,+ adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "openrouter/anthropic/claude-sonnet-4.6", piThinkingLevel: "max" },+ })).toMatchObject({ kind: "native", profile: { backend: "acpx_runtime" } });+ });+it("rejects unknown Paperclip Runner providers", () => {expect(() => resolveNativeRuntimeMode({...eligible,@@ -250,7 +256,7 @@ describe("resolveNativeRuntimeMode", () => {it("keeps a persisted experimental run native while the flag rejects a fresh start", () => {const disabled = { ...eligible, enabled: false,- adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "openrouter/deepseek/deepseek-v4-flash-0731" },+ adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "openrouter/deepseek/deepseek-v4-flash-0731" },};expect(resolveHeartbeatNativeRuntimeMode({...disabled,@@ -522,7 +528,7 @@ describe("resolveHeartbeatRuntimeMode compatibility", () => {...compatibilityInput,enabled: false,adapterType: "paperclip_runner",- adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "openrouter/anthropic/claude-sonnet-4.6" },+ adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "openrouter/anthropic/claude-sonnet-4.6" },})).toThrow(NativeRunnerSelectionError);});it("admits native Claude without enabling other ACPX providers", () => {diff --git a/server/src/services/native-runtime/runtime-mode.ts b/server/src/services/native-runtime/runtime-mode.tsindex e1c6fb24d4..5cd19debdd 100644--- a/server/src/services/native-runtime/runtime-mode.ts+++ b/server/src/services/native-runtime/runtime-mode.ts@@ -140,7 +140,7 @@ export function resolveNativeRuntimeMode(input: {throw ineligible("paperclip_runner_grok_disabled", "Enable Grok Bot, Paperclip Runner, and Assistant connections (MCP) before assigning new work.");} else if (runnerProfile.provider !== "codex" && runnerProfile.provider !== "opencode"&& !(runnerProfile.provider === "acpx"- && (runnerProfile.acpxAgent === "claude" || runnerProfile.acpxAgent === "copilot"))+ && (["claude", "copilot", "pi"].includes(runnerProfile.acpxAgent ?? "")))&& !input.enabled) {throw ineligible("paperclip_runner_rollout_disabled",diff --git a/ui/src/adapters/adapter-display-registry.test.ts b/ui/src/adapters/adapter-display-registry.test.tsindex d2de92e6f8..1ee731693e 100644--- a/ui/src/adapters/adapter-display-registry.test.ts+++ b/ui/src/adapters/adapter-display-registry.test.ts@@ -31,6 +31,7 @@ describe("adapter display registry", () => {expect(getAdapterLabel("hermes_gateway")).toBe("Hermes Gateway");expect(getAdapterLabel("opencode_local")).toBe("OpenCode");expect(getAdapterLabel("pi_local")).toBe("Pi");+ expect(agentDisplayAdapterType({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "pi" } })).toBe("pi_local");expect(getAdapterLabels()).toMatchObject({codex_local: "Codex",diff --git a/ui/src/adapters/adapter-display-registry.ts b/ui/src/adapters/adapter-display-registry.tsindex eb47db8e76..c93a4e67db 100644--- a/ui/src/adapters/adapter-display-registry.ts+++ b/ui/src/adapters/adapter-display-registry.ts@@ -222,7 +222,7 @@ export function agentDisplayAdapterType(agent: { adapterType: string; adapterConreturn agent.adapterConfig.provider;}const harness = agentHarnessType(agent.adapterType, agent.adapterConfig);- return ["codex_local", "claude_local", "opencode_local"].includes(harness) ? harness : agent.adapterType;+ return ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(harness) ? harness : agent.adapterType;}export function isKnownAdapterType(type: string): boolean {diff --git a/ui/src/components/AgentActionButtons.tsx b/ui/src/components/AgentActionButtons.tsxindex b2d7006512..f9498d9a23 100644--- a/ui/src/components/AgentActionButtons.tsx+++ b/ui/src/components/AgentActionButtons.tsx@@ -437,7 +437,7 @@ export function AgentActionButtons({<Button variant="outline" size={size} disabled={disabled} onClick={() => navigate(`/agents/new?${new URLSearchParams({name: agent.name, adapterType: agent.adapterType, setupAgentId: agent.id,runnerProvider: String(agent.adapterConfig.provider === "acpx" ? agent.adapterConfig.acpxAgent : agent.adapterConfig.provider ?? "codex"),- ...(agent.adapterType === "paperclip_runner" ? { runner: "paperclip" } : ["codex_local", "claude_local", "opencode_local"].includes(agent.adapterType) ? { runner: "legacy" } : {}),+ ...(agent.adapterType === "paperclip_runner" ? { runner: "paperclip" } : ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(agent.adapterType) ? { runner: "legacy" } : {}),})}`)}>Finish setup</Button>) : (<PauseResumeButtondiff --git a/ui/src/components/AgentConfigForm.render.test.tsx b/ui/src/components/AgentConfigForm.render.test.tsxindex c4357cb6c5..f1919aad98 100644--- a/ui/src/components/AgentConfigForm.render.test.tsx+++ b/ui/src/components/AgentConfigForm.render.test.tsx@@ -887,15 +887,19 @@ describe("AgentConfigForm environment selector", () => {expect(result.onSave).toHaveBeenCalledWith({ name: "Renamed Claude" });});- it.each([{ provider: "opencode", model: "openrouter/anthropic/claude-sonnet-4.6" }, { provider: "unknown-provider" }])("preserves saved native $provider configuration with the experimental gate off", async adapterConfig => {+ it.each([{ provider: "opencode", model: "openrouter/anthropic/claude-sonnet-4.6" }, { provider: "acpx", acpxAgent: "pi", model: "openrouter/anthropic/claude-sonnet-4.6", piThinkingLevel: "max", acpxPermissionMode: "approve-reads", lifecycleMode: "warm" }, { provider: "unknown-provider" }])("preserves saved native $provider configuration with the experimental gate off", async adapterConfig => {mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableNativeRunner: false });const result = await renderForm([], { adapterType: "paperclip_runner", adapterConfig }, { showAdapterTypeField: true });roots.push(result.root);- if (adapterConfig.provider === "opencode") {- expect(result.container.querySelector('[aria-label="Harness"]')?.textContent).toContain("OpenCode");+ if (adapterConfig.provider === "opencode" || adapterConfig.acpxAgent === "pi") {+ expect(result.container.querySelector('[aria-label="Harness"]')?.textContent).toContain(adapterConfig.provider === "opencode" ? "OpenCode" : "Pi");await clickByText(result.container, "Advanced");expect(result.container.querySelector('[aria-label="Runner"]')?.textContent).toContain("Paperclip Runner");} else expect(result.container.querySelector('[aria-label="Runner"]')).toBeNull();+ if (adapterConfig.acpxAgent === "pi") {+ expect(result.container.querySelector('[aria-label="Pi thinking level"]')).not.toBeNull();+ expect(result.container.querySelector('[aria-label="Thinking effort"]')).toBeNull();+ }await act(async () => setInputValue(result.container.querySelector<HTMLInputElement>('[placeholder="Agent name"]')!, "Renamed native agent"));await flushReact();await clickByText(result.container, "Save");diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsxindex 99eaffea9a..140449f0b2 100644--- a/ui/src/components/AgentConfigForm.tsx+++ b/ui/src/components/AgentConfigForm.tsx@@ -1400,7 +1400,8 @@ export function AgentConfigForm(props: AgentConfigFormProps) {: adapterType === "opencode_local"? eff("adapterConfig", "variant", String(config.variant ?? "")): eff("adapterConfig", thinkingEffortKey, String(config[thinkingEffortKey] ?? ""));- const showThinkingEffort = adapterType !== "gemini_local"+ const showThinkingEffort = !(harnessType === "pi_local" && fieldsAdapterType === "paperclip_runner")+ && adapterType !== "gemini_local"&& adapterType !== "cursor_cloud"&& (adapterType !== "paperclip_runner" || isRunnerHarness);const codexSearchEnabled = adapterType === "codex_local"@@ -1758,7 +1759,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {setOverlay((prev) => ({...prev,adapterType: t,- runner: ["codex_local", "claude_local", "opencode_local"].includes(t) ? "auto" : undefined,+ runner: ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(t) ? "auto" : undefined,adapterConfig: {model:t === "gemini_local"diff --git a/ui/src/components/ConfigureBuiltInAgentModal.tsx b/ui/src/components/ConfigureBuiltInAgentModal.tsxindex ad609aff73..7121207404 100644--- a/ui/src/components/ConfigureBuiltInAgentModal.tsx+++ b/ui/src/components/ConfigureBuiltInAgentModal.tsx@@ -68,7 +68,7 @@ export function ConfigureBuiltInAgentModal({const { definition } = state;const [adapterType, setAdapterType] = useState<string>(- () => state.agent && ["codex_local", "claude_local", "opencode_local"].includes(agentHarnessType(state.agent.adapterType, state.agent.adapterConfig)) ? agentHarnessType(state.agent.adapterType, state.agent.adapterConfig) : state.agent?.adapterType ?? defaultAdapterType(state),+ () => state.agent && ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(agentHarnessType(state.agent.adapterType, state.agent.adapterConfig)) ? agentHarnessType(state.agent.adapterType, state.agent.adapterConfig) : state.agent?.adapterType ?? defaultAdapterType(state),);const [runner, setRunner] = useState<AgentRunnerChoice | undefined>();const environmentId = state.agent?.defaultEnvironmentId ?? null;@@ -143,7 +143,7 @@ export function ConfigureBuiltInAgentModal({: { adapterType, adapterConfig };const result = await builtInAgentsApi.provision(companyId, definition.key, {...adapterInput,- ...(["codex_local", "claude_local", "opencode_local"].includes(adapterType) && runner !== undefined ? { runner } : {}),+ ...(["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && runner !== undefined ? { runner } : {}),...(budgetMonthlyCents !== undefined ? { budgetMonthlyCents } : {}),});return result;@@ -189,7 +189,7 @@ export function ConfigureBuiltInAgentModal({/></Field>- {["codex_local", "claude_local", "opencode_local"].includes(adapterType) && <details className="space-y-3">+ {["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && <details className="space-y-3"><summary className="cursor-pointer text-sm text-muted-foreground">Advanced</summary><AgentRunnerSelect value={runner ?? (state.agent ? agentRunner(state.agent.adapterType) : "auto")}pending={adapters.isFetching} error={adapters.error?.message} onRetry={() => { void adapters.refetch(); }}diff --git a/ui/src/components/OnboardingWizard.tsx b/ui/src/components/OnboardingWizard.tsxindex 24014dca2e..1d53b81727 100644--- a/ui/src/components/OnboardingWizard.tsx+++ b/ui/src/components/OnboardingWizard.tsx@@ -169,6 +169,7 @@ const copilotOnboardingQualified = PAPERCLIP_RUNNER_ACPX_PROFILES.some();function restoreOnboardingAdapterType(savedAdapterType: unknown, provider?: unknown, savedCopilot?: unknown): AdapterType {+ if (savedAdapterType === "paperclip_runner" && provider === "pi") return "pi_local";if (savedAdapterType === "paperclip_runner" && provider === "opencode") return "opencode_local";if (savedAdapterType === "paperclip_runner" && savedCopilot !== true && (provider === undefined || provider === "codex")) return "codex_local";return typeof savedAdapterType === "string" && (savedAdapterType !== "paperclip_runner" || (savedCopilot === true && copilotOnboardingQualified))@@ -612,7 +613,7 @@ function OnboardingWizardInner({restoreOnboardingAdapterType(saved?.adapterType, saved?.runnerProvider, saved?.onboardingCopilot),);const [runner, setRunner] = useState<AgentRunnerChoice>(() => saved?.runner === "legacy" || saved?.runner === "paperclip"- ? saved.runner : saved?.adapterType === "paperclip_runner" && (saved?.runnerProvider === undefined || ["codex", "claude", "acpx", "opencode"].includes(String(saved?.runnerProvider))) ? "paperclip" : "auto");+ ? saved.runner : saved?.adapterType === "paperclip_runner" && (saved?.runnerProvider === undefined || ["codex", "claude", "acpx", "opencode", "pi"].includes(String(saved?.runnerProvider))) ? "paperclip" : "auto");/*** Whether a model source has been chosen, as opposed to which one* `adapterType` happens to hold.@@ -642,7 +643,7 @@ function OnboardingWizardInner({const savedNativeRunnerDraft = saved?.adapterType === "paperclip_runner" && !(saved?.onboardingCopilot === true && copilotOnboardingQualified);const [cwd, setCwd] = useState((saved?.cwd as string) ?? "");const [model, setModel] = useState(- savedNativeRunnerDraft && saved?.runnerProvider !== undefined && !["codex", "claude", "acpx", "opencode"].includes(String(saved.runnerProvider)) ? "" : (saved?.model as string) ?? "",+ savedNativeRunnerDraft && saved?.runnerProvider !== undefined && !["codex", "claude", "acpx", "opencode", "pi"].includes(String(saved.runnerProvider)) ? "" : (saved?.model as string) ?? "",);const [command, setCommand] = useState(saved?.adapterType === "paperclip_runner" ? "" : (saved?.command as string) ?? "",@@ -1048,7 +1049,7 @@ function OnboardingWizardInner({if (requestCopilotModels) void refreshAdapterModels();}, [requestCopilotModels, copilotModelScope, refreshAdapterModels]);const copilotModelReady = Boolean(copilotConnection && copilotEnvironmentReady && !adapterModelsError && !adapterModelsFetching && adapterModels?.some((entry) => entry.id === model.trim()));- const needsRunnerDiscovery = ["codex_local", "claude_local", "opencode_local"].includes(adapterType) && runner === "auto";+ const needsRunnerDiscovery = ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && runner === "auto";const resolvedRunner = runner === "auto"? runnerDiscovery.data?.find(item => item.type === adapterType)?.defaultRunner: runner;@@ -2032,7 +2033,7 @@ function OnboardingWizardInner({...defaultCreateValues,adapterType,runner,- ...(isCopilot ? { adapterSchemaValues: { provider: "acpx", acpxAgent: "copilot" } } : {}),+ ...(isCopilot ? { adapterSchemaValues: { provider: "acpx", acpxAgent: "copilot" } } : adapterType === "pi_local" ? { adapterSchemaValues: savedConfig } : {}),resolvedRunner: setupRunner ?? resolvedRunner,model:adapterType === "gemini_local"@@ -2262,7 +2263,7 @@ function OnboardingWizardInner({{adapterConfig: testedConfig,...(restoredSetup?.companyId === createdCompanyId ? { agentId: restoredSetup.id } : {}),- ...(["codex_local", "claude_local", "opencode_local"].includes(adapterType) && runner !== "auto" ? { runner } : {}),+ ...(["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && runner !== "auto" ? { runner } : {}),...(managedBindingForStep() ? { aiConnection: managedBindingForStep() } : {}),environmentId,}@@ -2524,7 +2525,7 @@ function OnboardingWizardInner({...(restoredSetup?.companyId === createdCompanyId ? { reportsTo: restoredSetup.reportsTo } : {}),adapterType,adapterConfig: hireAdapterConfig,- ...(["codex_local", "claude_local", "opencode_local"].includes(adapterType) && runner !== "auto" ? { runner } : {}),+ ...(["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && runner !== "auto" ? { runner } : {}),...(shouldApplyStoredClaudeLogin ? { applyStoredClaudeLogin: true } : {}),// The server owns what the first agent is told now: this marker seeds// the chief-of-staff persona over the agent's entry instruction file.@@ -3257,7 +3258,7 @@ function OnboardingWizardInner({) : null}</motion.div>- {sourceSelected && ["codex_local", "claude_local", "opencode_local"].includes(adapterType) && <details className="space-y-3">+ {sourceSelected && ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && <details className="space-y-3"><summary className="cursor-pointer text-sm text-muted-foreground">Advanced</summary><AgentRunnerSelect value={runner} disabled={loading || adapterEnvLoading}pending={runnerDiscovery.isFetching} error={runnerDiscovery.error?.message} onRetry={() => { void runnerDiscovery.refetch(); }}diff --git a/ui/src/components/ai-connections/AiConnectionField.test.tsx b/ui/src/components/ai-connections/AiConnectionField.test.tsxindex 9603e6fd1f..cc9e639517 100644--- a/ui/src/components/ai-connections/AiConnectionField.test.tsx+++ b/ui/src/components/ai-connections/AiConnectionField.test.tsx@@ -5,7 +5,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, expect, it, vi } from "vitest";import type { ComponentProps } from "react";import type { AiManagedConnectionSummary } from "@paperclipai/shared";-import { AiConnectionField } from "./AiConnectionField";+import { AiConnectionField, aiProviderForAdapter } from "./AiConnectionField";import type { AiConnectionCredentialStep } from "./AiConnectionCredentialStep";const mocks = vi.hoisted(() => ({ list: vi.fn(), setDefault: vi.fn() }));@@ -147,3 +147,36 @@ it("uses the server's connection-manager permission for company-wide access", asawait click("Connect another account");expect(credentialProps).toMatchObject({ allAgents: true });});++it("offers Pi account selection before choosing its required model", async () => {+ mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [], canManageConnections: true });+ expect(aiProviderForAdapter("pi_local")).toBe("openrouter");+ flushSync(() => root.render(<QueryClientProvider client={client}>+ <AiConnectionField companyId="company" agentId="agent" agentName="Pi" adapterType="pi_local" model=""+ value={{ provider: "openrouter", method: "api_key", mode: "responsible_user" }} onChange={onChange} />+ </QueryClientProvider>));+ await settle();+ expect(document.querySelector('[role="combobox"][aria-label="Connection"]')).not.toBeNull();+ expect(container.textContent).not.toContain("does not support the current harness");+ await click("Connect another account");+ expect(document.body.textContent).toContain("Advanced provider setup");+});++it.each(["openai", "anthropic", "google", "openrouter"] as const)("keeps a matching saved Pi %s API-key account selectable", async provider => {+ const saved = account({ provider, method: "api_key", name: "Pi provider account", status: "connected" });+ mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [saved], canManageConnections: true });+ flushSync(() => root.render(<QueryClientProvider client={client}>+ <AiConnectionField companyId="company" agentId="agent" agentName="Pi" adapterType="pi_local" model={`${provider}/provider-model`}+ value={{ provider, method: "api_key", mode: "delegated", connectionId: saved.id, grantId: saved.grantId }} onChange={onChange} />+ </QueryClientProvider>));+ await settle();+ expect(container.textContent).toContain("Pi provider account");+ expect(container.textContent).not.toContain("incompatible");+ expect(container.textContent).not.toContain("does not support");+ const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;+ flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));+ await settle();+ const choice = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(node => node.textContent?.includes("Pi provider account"));+ expect(choice).toBeDefined();+ expect(choice?.getAttribute("aria-disabled")).not.toBe("true");+});diff --git a/ui/src/components/ai-connections/AiConnectionField.tsx b/ui/src/components/ai-connections/AiConnectionField.tsxindex 04f00a595a..5fcbe5e275 100644--- a/ui/src/components/ai-connections/AiConnectionField.tsx+++ b/ui/src/components/ai-connections/AiConnectionField.tsx@@ -33,6 +33,7 @@ export function aiProviderForAdapter(claude_local: "anthropic",codex_local: "openai",opencode_local: "openrouter",+ pi_local: "openrouter",grok_local: "xai",copilot_runtime: "github",gemini_local: "google",@@ -124,7 +125,7 @@ export function AiConnectionField({);return (<div className="space-y-4">- {value && value.mode !== "router" && (adapterType !== "opencode_local" || Boolean(model)) && !isAiConnectionCompatible(value, adapterType, model) && (+ {value && value.mode !== "router" && (!["opencode_local", "pi_local"].includes(adapterType) || Boolean(model)) && !isAiConnectionCompatible(value, adapterType, model) && (<p role="alert" className="text-sm text-destructive">This connection does not support the current harness and model. Choosea compatible connection before saving.@@ -144,6 +145,7 @@ export function AiConnectionField({</label>}{value?.mode !== "router" && <AiConnectionSelectadapterType={adapterType}+ model={model}requirement={{ companyId, provider }}connections={accounts.data?.connections ?? []}value={value}diff --git a/ui/src/components/ai-connections/AiConnectionSelect.tsx b/ui/src/components/ai-connections/AiConnectionSelect.tsxindex bb5fbbe04e..4eb82c01f1 100644--- a/ui/src/components/ai-connections/AiConnectionSelect.tsx+++ b/ui/src/components/ai-connections/AiConnectionSelect.tsx@@ -41,7 +41,8 @@ export function AiConnectionSelect({onReconnect,onChange,adapterType,-}: AiConnectionPickerProps & { adapterType: string }) {+ model,+}: AiConnectionPickerProps & { adapterType: string; model?: string }) {const selectId = useId();const personal = personalAiDefault(connections, requirement, currentUserId);const selected =@@ -50,6 +51,8 @@ export function AiConnectionSelect({: connections.find((c) => c.id === value?.connectionId && c.grantId === value?.grantId,);+ const compatibilityModel = (provider: string) => adapterType === "pi_local"+ ? model || `${provider}/` : provider === "openrouter" ? "openrouter/" : undefined;const compatible = connections.filter((c) =>@@ -57,7 +60,7 @@ export function AiConnectionSelect({isAiConnectionCompatible(c,adapterType,- c.provider === "openrouter" ? "openrouter/" : undefined,+ compatibilityModel(c.provider),),).sort(@@ -80,7 +83,7 @@ export function AiConnectionSelect({mode: "responsible_user",},adapterType,- requirement.provider === "openrouter" ? "openrouter/" : undefined,+ compatibilityModel(requirement.provider),);const incompatible =selected && !compatible.some((c) => c.id === selected.id);diff --git a/ui/src/components/ai-connections/useConnectionModels.test.tsx b/ui/src/components/ai-connections/useConnectionModels.test.tsxindex ac575945f5..2df022de52 100644--- a/ui/src/components/ai-connections/useConnectionModels.test.tsx+++ b/ui/src/components/ai-connections/useConnectionModels.test.tsx@@ -49,13 +49,13 @@ async function mount(accounts: AiManagedConnectionSummary[] = [account], harnessawait render(value);}-it.each(["opencode_local", "codex_local", "claude_local", "hermes_local"])("automatically discovers an empty OpenRouter connection's models for %s", async harness => {+it.each(["opencode_local", "pi_local", "codex_local", "claude_local", "hermes_local"])("automatically discovers an empty OpenRouter connection's models for %s", async harness => {await mount([account], harness);await vi.waitFor(() => expect(result?.models).toHaveLength(3));expect(agentsApi.adapterModels).toHaveBeenCalledWith("company", "opencode_local", { provider: "openrouter" });- expect(result?.models.map(m => m.id)).toEqual(catalog.map(m => harness === "opencode_local" ? m.id : m.id.slice("openrouter/".length)));+ expect(result?.models.map(m => m.id)).toEqual(catalog.map(m => ["opencode_local", "pi_local"].includes(harness) ? m.id : m.id.slice("openrouter/".length)));expect(result?.models.map(m => m.label)).toEqual(catalog.map(m => m.label));- expect(result?.resolveModel("anthropic/custom-model")).toBe(harness === "opencode_local" ? "openrouter/anthropic/custom-model" : "anthropic/custom-model");+ expect(result?.resolveModel("anthropic/custom-model")).toBe(["opencode_local", "pi_local"].includes(harness) ? "openrouter/anthropic/custom-model" : "anthropic/custom-model");});it("also discovers models for legacy OpenRouter connections without routing metadata", async () => {diff --git a/ui/src/components/ai-connections/useConnectionModels.ts b/ui/src/components/ai-connections/useConnectionModels.tsindex 1173a8e899..0e53b0842b 100644--- a/ui/src/components/ai-connections/useConnectionModels.ts+++ b/ui/src/components/ai-connections/useConnectionModels.ts@@ -36,7 +36,7 @@ export function useConnectionModels(? { kind: "openrouter", protocol: "chat", auth: "bearer", models: [] }: undefined);const modelOptions = discover- ? (catalog.data ?? []).map((m) => ({ ...m, id: harness === "opencode_local" ? m.id : m.id.replace(/^openrouter\//, "") }))+ ? (catalog.data ?? []).map((m) => ({ ...m, id: ["opencode_local", "pi_local"].includes(harness) ? m.id : m.id.replace(/^openrouter\//, "") })): routing?.models ?? [];return effectiveRouting? {diff --git a/ui/src/components/new-agent/NewAgentSetup.tsx b/ui/src/components/new-agent/NewAgentSetup.tsxindex a026ca9606..e79f33bd43 100644--- a/ui/src/components/new-agent/NewAgentSetup.tsx+++ b/ui/src/components/new-agent/NewAgentSetup.tsx@@ -28,7 +28,7 @@ import type {Agent,EnvBinding,} from "@paperclipai/shared";-import { ADAPTER_AUTH_MISSING_CHECK_CODE } from "@paperclipai/shared";+import { ADAPTER_AUTH_MISSING_CHECK_CODE, paperclipRunnerProfileForHarness } from "@paperclipai/shared";import { useNavigate, useSearchParams } from "@/lib/router";import { agentsApi } from "@/api/agents";import { ApiError } from "@/api/client";@@ -96,9 +96,9 @@ export function NewAgentSetup() {key={`${selectedCompanyId}:${params.get("name")}:${params.get("adapterType")}:${params.get("runnerProvider") ?? "codex"}:${params.get("runner") ?? "auto"}`}companyId={selectedCompanyId}name={params.get("name") ?? ""}- adapterType={params.get("adapterType") === "paperclip_runner" && ["codex", "claude", "opencode"].includes(params.get("runnerProvider") ?? "codex") ? params.get("runnerProvider") === "claude" ? "claude_local" : params.get("runnerProvider") === "opencode" ? "opencode_local" : "codex_local" : params.get("adapterType") ?? ""}- initialRunner={params.get("runner") ?? (params.get("adapterType") === "paperclip_runner" && ["codex", "claude", "opencode"].includes(params.get("runnerProvider") ?? "codex") ? "paperclip" : params.has("setupAgentId") && ["codex_local", "claude_local", "opencode_local"].includes(params.get("adapterType") ?? "") ? "legacy" : "auto")}- preserveNativeHarness={params.get("adapterType") === "paperclip_runner" && ["codex", "claude", "opencode"].includes(params.get("runnerProvider") ?? "codex")}+ adapterType={params.get("adapterType") === "paperclip_runner" && ["codex", "claude", "opencode", "pi"].includes(params.get("runnerProvider") ?? "codex") ? params.get("runnerProvider") === "claude" ? "claude_local" : params.get("runnerProvider") === "opencode" ? "opencode_local" : params.get("runnerProvider") === "pi" ? "pi_local" : "codex_local" : params.get("adapterType") ?? ""}+ initialRunner={params.get("runner") ?? (params.get("adapterType") === "paperclip_runner" && ["codex", "claude", "opencode", "pi"].includes(params.get("runnerProvider") ?? "codex") ? "paperclip" : params.has("setupAgentId") && ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(params.get("adapterType") ?? "") ? "legacy" : "auto")}+ preserveNativeHarness={params.get("adapterType") === "paperclip_runner" && ["codex", "claude", "opencode", "pi"].includes(params.get("runnerProvider") ?? "codex")}runnerProvider={params.get("runnerProvider") ?? "codex"}createdAgentId={params.get("createdAgentId")}setupAgentId={params.get("setupAgentId")}@@ -141,7 +141,7 @@ function Setup({? "claude_local": runnerProvider === "opencode"? "opencode_local"- : runnerProvider === "codex" ? "codex_local" : runnerProvider+ : runnerProvider === "pi" ? "pi_local" : runnerProvider === "codex" ? "codex_local" : runnerProvider: adapterType;const connectionAdapter =brandType === "claude_local" || brandType === "codex_local" || brandType === "grok_local"@@ -163,7 +163,6 @@ function Setup({createdAgentId ? "saved" : connectionAdapter ? "connect" : "runtime",);const [model, setModel] = useState("");- const efforts = isRunner ? [] : setupEfforts(adapterType, model);const [effort, setEffort] = useState("");const [modelOpen, setModelOpen] = useState(false);const [environmentOverride, setEnvironmentOverride] = useState("");@@ -202,9 +201,16 @@ function Setup({currentCreated ??(savedAgent.data?.companyId === companyId ? savedAgent.data : null);const completed = Boolean(created && created.pauseReason !== "setup");- const savedNativeOpenCode = brandType === "opencode_local" && (Boolean(setupAgentId) || runner === "legacy")+ useEffect(() => {+ if (brandType !== "pi_local" || created?.adapterType !== "paperclip_runner"+ || created.runtimeConfig.aiConnection) return;+ const env = (created.adapterConfig.env ?? {}) as Record<string, unknown>;+ if (Object.values(PROVIDER_ENV_KEYS).some(key => env[key] !== undefined)) return;+ setRuntimeAiBinding(current => current ?? { provider: "openrouter", method: "api_key", mode: "responsible_user" });+ }, [brandType, created?.id, created?.adapterType]);+ const savedNativeMultiProvider = multiProvider && (Boolean(setupAgentId) || runner === "legacy")&& created?.adapterType === "paperclip_runner";- const requestAdapterType = savedNativeOpenCode || (preserveNativeHarness && runner === "paperclip")+ const requestAdapterType = savedNativeMultiProvider || (preserveNativeHarness && runner === "paperclip")? "paperclip_runner" : adapterType;const [saving, setSaving] = useState(false);const [testState, setTestState] = useState<TestState | "warn">("idle");@@ -328,6 +334,8 @@ function Setup({queryFn: () => adaptersApi.list({ companyId, environmentId }),});const defaultRunner = adapters.data?.find(adapter => adapter.type === adapterType)?.defaultRunner;+ const efforts = brandType === "pi_local" && (runner === "paperclip" || (runner === "auto" && defaultRunner === "paperclip"))+ ? ["off", "low", "high", "max"] : isRunner ? [] : setupEfforts(adapterType, model);useEffect(() => {const transition = qualificationTransition.current;if (transition?.run === generation.current && transition.companyId === companyId@@ -385,7 +393,7 @@ function Setup({) && (requestAdapterType !== "paperclip_runner" || adapterType === "paperclip_runner" || adapterInventory.data?.some(adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled));const connectionSettingsReady = Boolean(available &&- (!["codex_local", "claude_local", "opencode_local"].includes(adapterType) || runner !== "auto" || Boolean(adapters.data)) &&+ (!["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) || runner !== "auto" || Boolean(adapters.data)) &&!environmentError &&!envs.isPending &&!settings.isPending &&@@ -401,7 +409,7 @@ function Setup({!caps.error &&(!(managedOnly || forced.forced) || environmentId),);- const needsCurrentSetup = ["codex_local", "claude_local", "opencode_local"].includes(adapterType);+ const needsCurrentSetup = ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType);const ready = Boolean(created) && connectionSettingsReady && (!needsCurrentSetup || (envs.isSuccess && !envs.isFetching&& settings.isSuccess && !settings.isFetching@@ -429,32 +437,42 @@ function Setup({...(isRunner? {adapterSchemaValues: {- provider: (runnerProvider === "claude" || runnerProvider === "grok" || runnerProvider === "copilot") ? "acpx" : runnerProvider,+ provider: ["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? "acpx" : runnerProvider,...(isDot ? { allowUnmeteredProvider } : {}),- ...((runnerProvider === "claude" || runnerProvider === "grok" || runnerProvider === "copilot") ? { acpxAgent: runnerProvider } : {}),+ ...(["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),},}: {}),};- const config = getUIAdapter(preserveNativeHarness && runner === "paperclip" ? "paperclip_runner" : adapterType).buildAdapterConfig(preserveNativeHarness && runner === "paperclip" ? { ...values, adapterSchemaValues: runnerProvider === "claude" ? { provider: "acpx", acpxAgent: "claude", acpxPermissionMode: "approve-all" } : { provider: runnerProvider } } : values);- if (preserveNativeHarness && runner === "paperclip") {- Object.assign(config, runnerProvider === "claude" ? { provider: "acpx", acpxAgent: "claude", acpxPermissionMode: "approve-all", lifecycleMode: "per_turn" } : runnerProvider === "opencode" ? { provider: "opencode", opencodePermissionMode: "allow", lifecycleMode: "per_turn" } : { provider: "codex", codexPermissionMode: "never", lifecycleMode: "per_turn" });+ const profile = paperclipRunnerProfileForHarness(brandType);+ const nativeSchema = profile ? {+ ...profile,+ ...(profile.provider === "acpx" ? { acpxPermissionMode: "approve-all" } : {}),+ ...(brandType === "pi_local" && effort ? { piThinkingLevel: effort } : {}),+ } : {};+ const config = getUIAdapter(preserveNativeHarness && runner === "paperclip" && brandType !== "pi_local" ? "paperclip_runner" : adapterType).buildAdapterConfig(preserveNativeHarness && runner === "paperclip" ? { ...values, adapterSchemaValues: nativeSchema } : values);+ if (preserveNativeHarness && runner === "paperclip" && profile) {+ Object.assign(config, nativeSchema, profile.provider === "opencode" ? { opencodePermissionMode: "allow" } : profile.provider === "codex" ? { codexPermissionMode: "never" } : {}, { lifecycleMode: "per_turn" });}if (isRunner)Object.assign(config, {- provider: (runnerProvider === "claude" || runnerProvider === "grok" || runnerProvider === "copilot") ? "acpx" : runnerProvider,- ...((runnerProvider === "claude" || runnerProvider === "grok" || runnerProvider === "copilot") ? { acpxAgent: runnerProvider } : {}),+ provider: ["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? "acpx" : runnerProvider,+ ...(["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),...(model ? { model } : {}),});- if (brandType === "opencode_local" && created) {+ if (multiProvider && created) {// The simplified setup page does not edit these saved runtime policies.const saved = created.adapterConfig;for (const [key, value] of Object.entries(saved)) {if (!(key in config)) config[key] = value;}- for (const key of ["dangerouslySkipPermissions", "opencodePermissionMode", "lifecycleMode", "idleTimeoutMs"]) {+ for (const key of ["dangerouslySkipPermissions", "opencodePermissionMode", "acpxPermissionMode", "acpxSessionMode", "lifecycleMode", "idleTimeoutMs"]) {if (saved[key] !== undefined) config[key] = saved[key];}+ if (brandType === "pi_local" && created.adapterType === "paperclip_runner" && runner !== "legacy" && effort) {+ config.piThinkingLevel = effort;+ delete config.thinking;+ }config.model = model;config.env = { ...((saved.env as object) ?? {}), ...((config.env as object) ?? {}) };}@@ -544,8 +562,8 @@ function Setup({role: existing.length ? "general" : "ceo", ...(leader ? { reportsTo: leader.id } : {}),adapterType: requestAdapterType, runner,adapterConfig: requestAdapterType === "paperclip_runner" ? {- provider: ["claude", "grok", "copilot"].includes(runnerProvider) ? "acpx" : runnerProvider,- ...(["claude", "grok", "copilot"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),+ provider: ["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? "acpx" : runnerProvider,+ ...(["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),} : {}, defaultEnvironmentId: environmentOverride || (forced.forced || managedOnly ? environmentId : null),runtimeConfig: buildNewAgentRuntimeConfig({ heartbeatEnabled: false }),}).then(agent => {@@ -562,9 +580,9 @@ function Setup({const agent = savedAgent.data;if (agent.pauseReason !== "setup") { setScreen("saved"); return; }const config = agent.adapterConfig;- if (brandType === "opencode_local") setRunner(agent.adapterType === "paperclip_runner" ? "paperclip" : "legacy");+ if (multiProvider) setRunner(agent.adapterType === "paperclip_runner" ? "paperclip" : "legacy");setModel(typeof config.model === "string" ? config.model : "");- setEffort(String(config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort ?? config.thinkingEffort ?? ""));+ setEffort(String(config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort ?? config.thinkingEffort ?? config.piThinkingLevel ?? config.thinking ?? ""));setEnvironmentOverride(agent.defaultEnvironmentId ?? "");setRepository(typeof config.repoUrl === "string" ? config.repoUrl : "");setBranch(typeof config.repoStartingRef === "string" ? config.repoStartingRef : "");@@ -662,7 +680,7 @@ function Setup({companyId,adapterType: requestAdapterType,providerAdapter: brandType,- ...(["codex_local", "claude_local", "opencode_local"].includes(adapterType) && runner !== "auto" ? { runner } : {}),+ ...(["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && runner !== "auto" ? { runner } : {}),adapterConfig: config,testCredentials: pendingCredentials(nextConnection),aiConnection: runtimeAiBinding ?? nextConnection?.aiConnection,@@ -717,7 +735,7 @@ function Setup({role: created.role,reportsTo: created.reportsTo,adapterType: requestAdapterType,- ...(["codex_local", "claude_local", "opencode_local"].includes(adapterType) && runner !== "auto" ? { runner } : {}),+ ...(["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && runner !== "auto" ? { runner } : {}),adapterConfig: config,defaultEnvironmentId:environmentOverride ||@@ -983,7 +1001,7 @@ function Setup({}).catch(cause => setError(cause instanceof Error ? cause.message : "Could not save agent setup."));}}/></fieldset> : <p role="status" className="text-sm text-muted-foreground">Loading connection settings…</p>}- {["codex_local", "claude_local", "opencode_local"].includes(adapterType) && <details className="mt-5 space-y-3">+ {["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && <details className="mt-5 space-y-3"><summary className="cursor-pointer text-sm text-muted-foreground">Advanced</summary><AgentRunnerSelect value={runner} disabled={busy}pending={adapters.isFetching} error={adapters.error?.message} onRetry={() => { void adapters.refetch(); }}@@ -1336,7 +1354,7 @@ function Setup({</Field></div>)}- {["codex_local", "claude_local", "opencode_local"].includes(adapterType) && <details className="space-y-3">+ {["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && <details className="space-y-3"><summary className="cursor-pointer text-sm text-muted-foreground">Advanced</summary><AgentRunnerSelect value={runner} disabled={busy}pending={adapters.isFetching} error={adapters.error?.message} onRetry={() => { void adapters.refetch(); }}diff --git a/ui/src/pages/CompanyImport.test.tsx b/ui/src/pages/CompanyImport.test.tsxindex cd714efa92..be7a80b5e7 100644--- a/ui/src/pages/CompanyImport.test.tsx+++ b/ui/src/pages/CompanyImport.test.tsx@@ -1227,6 +1227,26 @@ describe("CompanyImport", () => {expect(lastImportMeta().adapterOverrides?.coder).toBeUndefined();});+ it("keeps native Pi identity and saved policies with the experimental flag off", async () => {+ mockAdaptersApi.list.mockResolvedValue([+ { type: "claude_local", disabled: false },+ { type: "pi_local", disabled: false, supportedRunners: ["paperclip", "legacy"], defaultRunner: "paperclip" },+ { type: "paperclip_runner", disabled: false },+ ]);+ const preview = buildMixedAdapterPreviewResult();+ preview.manifest.agents[0]!.adapterType = "paperclip_runner";+ preview.manifest.agents[0]!.adapterConfig = { provider: "acpx", acpxAgent: "pi", model: "provider/model", piThinkingLevel: "max", acpxPermissionMode: "approve-reads", lifecycleMode: "warm" };+ mockCompaniesApi.importPreview.mockResolvedValue(preview);+ await renderPage();+ await enterGithubUrl();+ await clickButton(text => text === "Preview import");+ expect(findAdapterSelects()[0]!.value).toBe("pi_local");+ expect(container.textContent).not.toContain("requires its experimental feature to be enabled");+ await clickButton(text => text.startsWith("Import 3 file"));+ await settle();+ expect(lastImportMeta().adapterOverrides?.coder).toBeUndefined();+ });+it.each([{ sourceType: "codex_local", sourceRunner: "legacy" as const, runner: "paperclip" as const, sourcePolicy: {}, expectedBypass: undefined },{ sourceType: "codex_local", sourceRunner: undefined, runner: "legacy" as const, sourcePolicy: { dangerouslyBypassApprovalsAndSandbox: false }, expectedBypass: false },diff --git a/ui/src/pages/CompanyImport.tsx b/ui/src/pages/CompanyImport.tsxindex 0f4c213be8..3c5d4f2f7e 100644--- a/ui/src/pages/CompanyImport.tsx+++ b/ui/src/pages/CompanyImport.tsx@@ -576,7 +576,7 @@ function importAdapterValues(sourceAdapterType?: string,runner?: AgentRunnerChoice,): CreateConfigValues {- const nativeHarness = sourceAdapterType === "paperclip_runner" && ["codex_local", "claude_local", "opencode_local"].includes(choice);+ const nativeHarness = sourceAdapterType === "paperclip_runner" && ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(choice);const nativeCodex = nativeHarness && choice === "codex_local";const savedBypass = sourceConfig?.dangerouslyBypassApprovalsAndSandbox?? (nativeCodex ? undefined : sourceConfig?.dangerouslyBypassSandbox);@@ -594,6 +594,7 @@ function importAdapterValues(: resolveCodexLocalCliPolicy(sourceConfig).bypass,} : {}),...(sourceConfig && choice === "opencode_local" ? { model: typeof sourceConfig.model === "string" ? sourceConfig.model : "" } : {}),+ ...(sourceConfig && choice === "pi_local" ? { model: typeof sourceConfig.model === "string" ? sourceConfig.model : "", thinkingEffort: String(sourceConfig.piThinkingLevel ?? sourceConfig.thinking ?? "") } : {}),...(sourceConfig && choice === "claude_local" ? { model: typeof sourceConfig.model === "string" ? sourceConfig.model : "", thinkingEffort: String(sourceConfig.modelReasoningEffort ?? sourceConfig.reasoningEffort ?? sourceConfig.effort ?? "") } : {}),...(nativeHarness && sourceConfig ? {cwd: typeof sourceConfig.cwd === "string" ? sourceConfig.cwd : "",@@ -1683,7 +1684,7 @@ export function CompanyImport() {const nativeCodex = a.adapterType === "paperclip_runner"&& (a.adapterConfig?.provider === "codex" || a.adapterConfig?.provider === undefined);const nativeHarness = nativeCodex || (a.adapterType === "paperclip_runner"- && ["claude_local", "opencode_local"].includes(agentHarnessType(a.adapterType, a.adapterConfig)));+ && ["claude_local", "opencode_local", "pi_local"].includes(agentHarnessType(a.adapterType, a.adapterConfig)));const adapterChoice = a.adapterType === "paperclip_runner" && a.adapterConfig?.provider === "openai_dot"? "openai_dot" : a.adapterType === "paperclip_runner" && a.adapterConfig?.provider === "muse" ? "muse" : nativeHarness ? agentHarnessType(a.adapterType, a.adapterConfig) : a.adapterType;let fallbackAdapterType: string | null = null;@@ -1737,7 +1738,7 @@ export function CompanyImport() {if (selectedType === agent.adapterChoice && !adapterConfigEditedSlugs.has(agent.slug)&& (!configVals || configVals.runner === importAdapterValues(selectedType, agent.adapterConfig, agent.adapterType, agent.runner).runner)) continue;const retainsNativeHarness = agent.adapterType === "paperclip_runner"- && selectedType === agent.adapterChoice && ["codex_local", "claude_local", "opencode_local"].includes(selectedType);+ && selectedType === agent.adapterChoice && ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(selectedType);const apiType = selectedType === "openai_dot" || selectedType === "muse" || retainsNativeHarness ? "paperclip_runner" : selectedType;const override: CompanyPortabilityAdapterOverride = { adapterType: apiType };if (configVals?.runner !== undefined) override.runner = configVals.runner;@@ -1758,7 +1759,7 @@ export function CompanyImport() {const build = getUIAdapter(nativeClaudeForm ? "paperclip_runner" : configVals.adapterType).buildAdapterConfig;const edited = build(configVals);if (agent.adapterType === "paperclip_runner" && selectedType === agent.adapterChoice- && ["codex_local", "claude_local", "opencode_local"].includes(selectedType) && configVals.adapterType === selectedType+ && ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(selectedType) && configVals.adapterType === selectedType&& agentHarnessType("paperclip_runner", configVals.adapterSchemaValues) === selectedType) {const original = importAdapterValues(selectedType, agent.adapterConfig, agent.adapterType, configVals.runner);const baseline = build(original);diff --git a/ui/src/pages/NewAgent.test.tsx b/ui/src/pages/NewAgent.test.tsxindex 3138ac41d5..eeb73e79ca 100644--- a/ui/src/pages/NewAgent.test.tsx+++ b/ui/src/pages/NewAgent.test.tsx@@ -1022,6 +1022,23 @@ describe("New agent setup", () => {expect(secrets.create).toHaveBeenCalledTimes(1);},);+ it("resumes an empty native Pi draft with account selection and exact thinking controls", async () => {+ const id = "00000000-0000-4000-8000-000000000093";+ settings.getExperimental.mockResolvedValue({ enableNativeRunner: false });+ state.params = new URLSearchParams({ name: "Pi", adapterType: "pi_local", setupAgentId: id });+ state.adapters = state.adapters.map((adapter: any) => adapter.type === "pi_local"+ ? { ...adapter, supportedRunners: ["paperclip", "legacy"], defaultRunner: "paperclip" } : adapter);+ api.get.mockResolvedValue({ id, companyId: "company-1", name: "Pi", adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "pi", model: "", piThinkingLevel: "max" }, runtimeConfig: {}, pauseReason: "setup", status: "paused" });+ await renderCurrentParams();+ await settle();+ expect(container.querySelector('[role="combobox"][aria-label="Connection"]')).not.toBeNull();+ expect((container.querySelector('[aria-label="Model"]') as HTMLInputElement).value).toBe("");+ const thinking = container.querySelector('[aria-label="Thinking effort"]') as HTMLSelectElement;+ expect(thinking.value).toBe("max");+ expect([...thinking.options].map(option => option.value)).toEqual(["", "off", "low", "high", "max"]);+ expect(container.querySelector('[aria-label="OPENROUTER_API_KEY"]')).toBeNull();+ });+it.each(["auto", "legacy"] as const)("keeps OpenCode %s selection consistent between testing and hiring", async runner => {settings.getExperimental.mockResolvedValue({ enableNativeRunner: false });state.adapters = state.adapters.map((adapter: any) => adapter.type === "opencode_local"