mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
Bind Pi 1.0 reasoning modes through rich ACP and recovery
Require explicit native-effective thinking modes, reject drift across reconnects, and retain observed settings in qualification artifacts. Version the profile and pinned wrapper closure for the new contract. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
b70cf84ea6
commit
f5c5fde380
72 files changed
+1786
-181
No files matched your search
@@ -1,6 +1,51 @@
|
||||
# Pi rich ACP runtime
|
||||
|
||||
## Pi 1.0 candidate (2026-10-02, profile v12)
|
||||
## Pi 1.0 candidate (2026-10-02, profile v13)
|
||||
|
||||
Pi remains pinned to **`@earendil-works/pi-coding-agent@1.0.0`**, with
|
||||
`pi-acp@0.0.33`, ACPX `0.13.1`, and Node `24.21.0`. Profile 13 adds explicit
|
||||
reasoning-mode selection and rejects previous profile identities. It is a new
|
||||
qualification candidate; profile-12 results below remain historical evidence.
|
||||
|
||||
The normal Pi configuration records `piThinkingLevel` as `off`, `low`, `high`,
|
||||
or `max`. New configurations and qualification cases explicitly select `low`.
|
||||
The runner binds that setting to the session identity and requires native
|
||||
confirmation of the effective level before sending the prompt, including after
|
||||
session restoration. An unsupported level, absent acknowledgement, or effective
|
||||
level different from the requested value must fail admission. Changing the
|
||||
level requires a new compatible session; a warm session cannot silently retain
|
||||
its previous setting.
|
||||
|
||||
The wrapper obtains available levels from Pi's native
|
||||
`get_available_thinking_levels` RPC, exposes them through ACP session modes and
|
||||
the `thought_level` configuration option, and confirms changes with native
|
||||
`get_state`. This avoids advertising the static `minimal`, `medium`, or `xhigh`
|
||||
aliases when the selected model does not support them. For the pinned DeepSeek
|
||||
model, Pi 1.0 supports `off`, `low`, `high`, and `max`. Pi's implicit `medium`
|
||||
default resolves to `high`; Pi 0.84.2 also resolved that default to `high`, so
|
||||
this is a configuration gap rather than evidence of a new Pi 1.0 default.
|
||||
|
||||
The [provider-free wire proof](../../packages/paperclip-runner/test-fixtures/pi-acp/thinking-modes.v13.darwin-arm64.json)
|
||||
records actual Pi 1.0 request bodies changing from `high` to `low` through ACP,
|
||||
truthful `max` restoration, blocked non-loopback connections, and owned-process
|
||||
retirement. Synthetic responses establish propagation, not paid qualification.
|
||||
|
||||
The paid profile-12 hello passed in the actual installed application. Its first
|
||||
question continuation failed at the unchanged 120-second native deadline after
|
||||
1,019 reasoning deltas and no emitted tool call or question. The required tool
|
||||
was present with its exact schema. This establishes model activity without the
|
||||
required interaction; it does not prove the reasoning setting caused the timeout.
|
||||
The test remains failed. Profile-13 deterministic, local paid, Runner, native
|
||||
control, and Daytona results must be established independently.
|
||||
|
||||
| Capability | Native / ACP surface | Paperclip surface | Remaining boundary |
|
||||
| --- | --- | --- | --- |
|
||||
| Supported thinking levels | `get_available_thinking_levels`; ACP available session modes and `thought_level` choices | Pi reasoning-level configuration | Only the exact qualified model is admitted. Other models and their level sets remain unqualified. |
|
||||
| Set and verify thinking level | Native `set_thinking_level`, then `get_state`; ACP `session/set_mode` / config option | Saved agent setting, typed runner input, effective-mode admission | Live setting changes during an active turn are not exposed; a new compatible session is required. |
|
||||
| Recover selected level | Native restored state plus explicit effective-level verification | Mode-bound durable session identity | Old profiles and missing or mismatched mode identity cannot reuse a warm session. |
|
||||
| Provider notice severity and pricing provenance | `paperclip/pi_notice` and canonical `provider.notice.recorded` | Retained run event and usage metadata | The activity row currently renders a generic provider-update label and warning icon even for informational pricing estimates. P2: render the safe summary and severity; do not imply an estimated price is a bill. |
|
||||
|
||||
## Historical Pi 1.0 profile-v12 checkpoint (2026-10-02)
|
||||
|
||||
The candidate now pins **`@earendil-works/pi-coding-agent@1.0.0`** with
|
||||
`pi-acp@0.0.33`, ACPX `0.13.1`, and portable Node `24.21.0`. Pi v11 and older
|
||||
|
||||
@@ -2,64 +2,72 @@
|
||||
|
||||
## Current Pi 1.0 qualification checkpoint — October 2, 2026
|
||||
|
||||
Pi now uses `@earendil-works/pi-coding-agent@1.0.0`, `pi-acp@0.0.33`,
|
||||
ACPX `0.13.1`, and profile **12**. Its exact model remains
|
||||
`openrouter/deepseek/deepseek-v4-flash-0731`. Cursor v10 and Copilot v12
|
||||
remain gated while Pi qualification is completed. The held Pi admission branch
|
||||
is preparation for testing normal installation; it is not production qualification.
|
||||
Pi uses `@earendil-works/pi-coding-agent@1.0.0`, `pi-acp@0.0.33`, and ACPX
|
||||
`0.13.1`. Profile **13** adds explicit, native-acknowledged reasoning selection
|
||||
for the exact model `openrouter/deepseek/deepseek-v4-flash-0731`. New Pi
|
||||
configuration and qualification cases select `low`. This candidate is not yet
|
||||
production qualified. Cursor v10 and Copilot v12 remain gated.
|
||||
|
||||
The first paid Pi 1.0 local hello on profile 11 failed: Pi's serialized RPC
|
||||
message updates no longer carry the old SDK-shaped partial message. That failure
|
||||
is retained, with $0.000142518 observed on the dedicated OpenRouter key and
|
||||
complete owned-process cleanup. Profile 12 repairs the actual RPC boundary;
|
||||
its local-only tests exercise the real Pi CLI, wrapper and owned extension.
|
||||
They do not replace authenticated product tests.
|
||||
Profile 12 passed one paid local hello through the actual installed public
|
||||
CLI/server and normal runtime setup. The next question-continuation case failed
|
||||
at the unchanged 120-second native deadline: Pi emitted 1,019 reasoning deltas,
|
||||
but no tool call or question. The tool and schema were present. One native turn
|
||||
was submitted; the two visible start rows were canonical and mirrored activity,
|
||||
not evidence of two provider requests. Both attempts completed owned-process,
|
||||
IPC, temporary-root, installed-inventory, and post-run accounting checks.
|
||||
|
||||
At runtime source `b9e5d6ecdb05ab7244c90976e07c950f8d09b15b`, the fresh
|
||||
macOS ARM64 daemon and verified pack pass the original no-key startup test
|
||||
(6.741 seconds to settlement) and all 48 native/ACP contract tests without skips.
|
||||
The original evidence collector rejected Node 24's summary format after the
|
||||
runtime checks had passed. Its failure is preserved; independently reviewed
|
||||
offline finalization verifies those same logs and full asset inventories without
|
||||
rerunning the tests. The fresh native Intel build also passed all 48 contract
|
||||
tests, but its canonical startup failed at the unchanged 30-second deadline
|
||||
(35.032 seconds to settlement). A later instrumented run passed at 22.959 seconds;
|
||||
it used a read-verified, warmed filesystem state and does not erase the original
|
||||
failure. A four-run I/O-pool comparison was inconclusive, so no production
|
||||
thread-pool change was adopted. Intel startup and the final installed-package
|
||||
local/Daytona tests remain separate gates.
|
||||
The dedicated key recorded $0.000510742 for the hello and $0.004995065 for the
|
||||
failed question. Including the earlier profile-11 failure ($0.000142518), its
|
||||
observed total was $0.005648325 at that reconciliation. These are observed key
|
||||
usage changes, not native per-request bills. No failed result has been regraded.
|
||||
|
||||
Testing the actual public package installation exposed a packaging defect:
|
||||
ambient npm 10 pruned 84 files from the pinned Pi dependency closure. Setup now
|
||||
uses npm 11.19.0 bundled in the independently verified Node archive. The repaired
|
||||
provisioner reproduces the original profile-12 closure with ambient npm disabled;
|
||||
fresh public-package installation proof remains required.
|
||||
Diagnosis found that the runner did not select the ACP reasoning mode. The
|
||||
pinned model's implicit Pi `medium` setting resolves to `high`; this behavior
|
||||
also existed in Pi 0.84.2. Pi 1.0 exposes a genuine `low` level. Profile 13 carries
|
||||
an explicit setting through configuration, transport, and durable identity,
|
||||
and requires the native effective level to match before a prompt is sent.
|
||||
It does not increase the timeout. The timed-out HTTP body was not captured,
|
||||
so source-derived default mapping does not establish the cause of that failure.
|
||||
Fresh qualification must use the new profile and exact final build.
|
||||
|
||||
Normal Daytona setup now has an explicit operator command to import a verified
|
||||
Historical source `4c58da84fd86a0cd7bc1d952987b031786fc6b2b` passed full Runner
|
||||
verification and normal Intel startup at 28.295 seconds under the original
|
||||
30-second limit, plus all 48 native/ACP contract tests. The Intel result has
|
||||
only 1.705 seconds of margin and does not establish broad cold-start reliability.
|
||||
Its fresh Linux daemon, Pi pack, and image were built and inventoried; live
|
||||
Daytona qualification remained pending. The public Mac installation reproduced
|
||||
the complete Pi dependency closure using npm 11.19.0 from the verified Node
|
||||
archive. None of these artifacts qualifies profile 13.
|
||||
|
||||
The same source's full repository check failed six stale test assertions and
|
||||
an `ETXTBSY` binary-staging error; the downstream Grok check then lacked built
|
||||
server output. Typecheck, token gates, and Product E2E typecheck/unit checks
|
||||
passed. The stale assertions have targeted repairs. A Linux process owner was
|
||||
not captured for `ETXTBSY`; two exact native fixtures later passed on ARM with
|
||||
all owned daemon handles closed, which does not resolve the Linux failure.
|
||||
The next complete source run retains bounded executable-holder evidence around
|
||||
check boundaries. A later run on obsolete harness source was canceled by the
|
||||
lead and is retained as incomplete, not successful verification.
|
||||
|
||||
Normal Daytona setup has an explicit operator command to import a verified
|
||||
Linux companion into the installed server. It binds the trusted manifest to the
|
||||
installed source, Pi profile, daemon and complete provider-pack inventory, then
|
||||
uses the ordinary remote execution path without test-only binary or pack
|
||||
overrides. Its 31 focused tests cover asynchronous bounded verification,
|
||||
cancellation, existing-cache validation, contained paths and owned cleanup.
|
||||
These tests do not establish live Daytona qualification or release publication.
|
||||
|
||||
Full repository typecheck, tests, token gates, Product E2E typecheck/unit checks,
|
||||
and build passed on the earlier source `efe019a79f50440d7bd6c3bc6c75fb8f18953093`.
|
||||
Its Runner verification also passed. These results are historical prerequisites;
|
||||
profile 12 and the final installation changes still need their own verification.
|
||||
installed source, Pi profile, daemon, and complete provider-pack inventory, then
|
||||
uses ordinary remote execution without test-only binary or pack overrides.
|
||||
The final installed import, image publication, and paid proof remain required.
|
||||
|
||||
The dedicated Pi test key has a $5 lifetime OpenRouter-credit limit. Its BYOK
|
||||
charges are not included in that provider-enforced limit. Qualification therefore
|
||||
also requires the reviewed operational policy verifying no configured BYOK
|
||||
credentials, fresh account/key evidence, one paid case at a time, and usage
|
||||
monitoring. The key's $5 reservation is counted once within the combined $100
|
||||
campaign budget. Native price estimates are never substituted for provider bills.
|
||||
charges are outside that provider-enforced limit, so qualification additionally
|
||||
uses the reviewed no-BYOK operational policy, fresh account/key evidence, one
|
||||
paid case at a time, and usage monitoring. The $5 reservation is counted once
|
||||
within the combined $100 campaign budget. Native price estimates are never
|
||||
substituted for provider bills.
|
||||
|
||||
The [Pi capability inventory](runner-pi-capabilities.md#pi-10-candidate-2026-10-02-profile-v12)
|
||||
records Pi 1.0's native interfaces, wrapper changes, and unused capabilities.
|
||||
The comparison below remains the supported-surface map; older paid observations
|
||||
retain their named historical profiles. Current Pi 1.0 paid Product, Runner
|
||||
protocol, native controls, and Daytona qualification are still pending.
|
||||
The [Pi capability inventory](runner-pi-capabilities.md#pi-10-candidate-2026-10-02-profile-v13)
|
||||
records native interfaces, ACP mappings, user surfaces, and explicit gaps.
|
||||
The comparison below remains the supported-surface map; old observations retain
|
||||
their exact historical profile identities. Final source checks and profile-13
|
||||
local Product, Runner protocol, native-control, and Daytona qualification remain
|
||||
pending.
|
||||
|
||||
Historical source checkpoint (2026-10-01): **Cursor v10, Copilot v12 and Pi v10
|
||||
remain unqualified**. Copilot receipt v2 distinguishes original provider
|
||||
|
||||
@@ -125,6 +125,7 @@ export {
|
||||
normalizeLegacyRunnerProvider,
|
||||
resolvePaperclipRunnerPermissionMode,
|
||||
resolvePaperclipRunnerCursorMode,
|
||||
resolvePaperclipRunnerPiThinkingLevel,
|
||||
} from "./paperclip-runner-permissions.js";
|
||||
export {
|
||||
PAPERCLIP_RUNNER_INGRESS_PORT,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolvePaperclipRunnerPiThinkingLevel } from "./paperclip-runner-permissions.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -92,3 +93,17 @@ describe("Cursor session mode admission", () => {
|
||||
expect(() => resolvePaperclipRunnerCursorMode(provider, agent, "plan")).toThrow("only for Cursor");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pi thinking configuration", () => {
|
||||
it.each([undefined, "off", "low", "high", "max"] as const)("persists exact level %s with low as the fresh-config default", value => {
|
||||
expect(resolvePaperclipRunnerPiThinkingLevel("acpx", "pi", value)).toBe(value ?? "low");
|
||||
});
|
||||
it.each(["medium", "minimal", "xhigh", "", null, 1])("rejects unsupported alias %s", value => {
|
||||
expect(() => resolvePaperclipRunnerPiThinkingLevel("acpx", "pi", value)).toThrow();
|
||||
});
|
||||
it("rejects foreign provider settings", () => {
|
||||
expect(() => resolvePaperclipRunnerPiThinkingLevel("codex", "pi", "low")).toThrow(/only/);
|
||||
expect(() => resolvePaperclipRunnerPiThinkingLevel("acpx", "cursor", "low")).toThrow(/only/);
|
||||
expect(resolvePaperclipRunnerPiThinkingLevel("codex", undefined, undefined)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -247,3 +247,15 @@ export const PAPERCLIP_RUNNER_ACPX_PROFILES = Object.freeze([
|
||||
{ value: "copilot", label: "GitHub Copilot", qualified: false, credentialEnvironment: ["COPILOT_GITHUB_TOKEN"] },
|
||||
{ value: "pi", label: "Pi", qualified: true, credentialEnvironment: ["OPENROUTER_API_KEY"] },
|
||||
] as const);
|
||||
|
||||
/** Exact Pi native thinking levels; aliases that silently clamp are not configuration. */
|
||||
export type PaperclipRunnerPiThinkingLevel = "off" | "low" | "high" | "max";
|
||||
export function resolvePaperclipRunnerPiThinkingLevel(provider: unknown, agent: unknown, value: unknown): PaperclipRunnerPiThinkingLevel | undefined {
|
||||
if (provider !== "acpx" || agent !== "pi") {
|
||||
if (value !== undefined) throw new Error("piThinkingLevel is supported only for Pi");
|
||||
return undefined;
|
||||
}
|
||||
if (value === undefined) return "low";
|
||||
if (value === "off" || value === "low" || value === "high" || value === "max") return value;
|
||||
throw new Error("Pi thinking level must be off, low, high, or max");
|
||||
}
|
||||
@@ -345,3 +345,11 @@ describe("buildPaperclipRunnerConfig", () => {
|
||||
expect(config).not.toHaveProperty("idleTimeoutMs");
|
||||
});
|
||||
});
|
||||
|
||||
it.each([undefined, "off", "low", "high", "max"] as const)("builds exact Pi thinking configuration %s", piThinkingLevel => {
|
||||
const config = buildPaperclipRunnerConfig(makeValues({ adapterType: "paperclip_runner", model: "openrouter/deepseek/deepseek-v4-flash-0731", adapterSchemaValues: { provider: "acpx", acpxAgent: "pi", piThinkingLevel } }));
|
||||
expect(config.piThinkingLevel).toBe(piThinkingLevel ?? "low");
|
||||
});
|
||||
it("rejects silently clamped Pi aliases during configuration", () => {
|
||||
expect(() => buildPaperclipRunnerConfig(makeValues({ adapterType: "paperclip_runner", adapterSchemaValues: { provider: "acpx", acpxAgent: "pi", piThinkingLevel: "medium" } }))).toThrow();
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
resolvePaperclipRunnerIdleTimeoutMs,
|
||||
resolvePaperclipRunnerPermissionMode,
|
||||
resolvePaperclipRunnerCursorMode,
|
||||
resolvePaperclipRunnerPiThinkingLevel,
|
||||
PAPERCLIP_RUNNER_ACPX_PROFILES,
|
||||
type CreateConfigValues,
|
||||
} from "@paperclipai/adapter-utils";
|
||||
@@ -99,6 +100,7 @@ export function buildPaperclipRunnerConfig(v: CreateConfigValues): Record<string
|
||||
: "codex";
|
||||
const acpxAgent = PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === schemaValues.acpxAgent)?.value ?? "claude";
|
||||
const cursorMode = resolvePaperclipRunnerCursorMode(provider, acpxAgent, schemaValues.acpxSessionMode);
|
||||
const piThinkingLevel = resolvePaperclipRunnerPiThinkingLevel(provider, acpxAgent, schemaValues.piThinkingLevel);
|
||||
|
||||
const schemaModel = typeof schemaValues.model === "string"
|
||||
? schemaValues.model.trim()
|
||||
@@ -188,6 +190,7 @@ export function buildPaperclipRunnerConfig(v: CreateConfigValues): Record<string
|
||||
"opencodePermissionMode",
|
||||
"acpxPermissionMode",
|
||||
"acpxSessionMode",
|
||||
"piThinkingLevel",
|
||||
"managedProfileId",
|
||||
"managedAgentsRetentionAcknowledged",
|
||||
"maxSessionListCostUsd",
|
||||
@@ -247,6 +250,7 @@ export function buildPaperclipRunnerConfig(v: CreateConfigValues): Record<string
|
||||
? {
|
||||
acpxAgent,
|
||||
...(cursorMode === undefined ? {} : { acpxSessionMode: cursorMode }),
|
||||
...(piThinkingLevel === undefined ? {} : { piThinkingLevel }),
|
||||
model: configuredModel || schemaModel || (acpxAgent === "grok" ? "grok-4.7" : resolvePaperclipRunnerModel("acpx", undefined)),
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
{
|
||||
"path": "schemas/provider-descriptor.schema.json",
|
||||
"id": "https://paperclip.dev/schemas/prp/v1/provider-descriptor.schema.json",
|
||||
"sha256": "f5badf70748d6a761a3487f001ce8282582b161cb5b80fabb6bb5f683d28c512"
|
||||
"sha256": "87fc155cf7c94fd6a526829f50f3d4a649769f1024b473013eee3436878b0f5d"
|
||||
},
|
||||
{
|
||||
"path": "schemas/provider-event.schema.json",
|
||||
|
||||
@@ -52,10 +52,42 @@
|
||||
"params": { "type": "object" }
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"allOf": [{
|
||||
"if": { "properties": { "command": { "const": "turn.steer" } } },
|
||||
"then": { "properties": { "params": { "$ref": "#/$defs/turnControl" } } }
|
||||
}]
|
||||
"allOf": [
|
||||
{
|
||||
"if": { "properties": { "command": { "const": "turn.steer" } } },
|
||||
"then": { "properties": { "params": { "$ref": "#/$defs/turnControl" } } }
|
||||
},
|
||||
{
|
||||
"if": { "properties": { "command": { "const": "session.open" } } },
|
||||
"then": { "properties": { "params": { "$ref": "#/$defs/sessionOpenThinkingLevel" } } }
|
||||
}
|
||||
]
|
||||
},
|
||||
"piThinkingLevel": { "enum": ["off", "low", "high", "max"] },
|
||||
"sessionOpenThinkingLevel": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"agent": { "type": "string" },
|
||||
"piThinkingLevel": { "$ref": "#/$defs/piThinkingLevel" }
|
||||
},
|
||||
"if": { "properties": { "agent": { "const": "pi" } }, "required": ["agent"] },
|
||||
"then": {
|
||||
"required": ["piThinkingLevel"],
|
||||
"properties": {
|
||||
"piThinkingLevel": { "$ref": "#/$defs/piThinkingLevel" },
|
||||
"expectedIdentity": {
|
||||
"type": ["object", "null"],
|
||||
"properties": { "piThinkingLevel": { "$ref": "#/$defs/piThinkingLevel" } },
|
||||
"required": ["piThinkingLevel"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"else": {
|
||||
"properties": {
|
||||
"piThinkingLevel": false,
|
||||
"expectedIdentity": { "type": ["object", "null"], "properties": { "piThinkingLevel": false } }
|
||||
}
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"type": "object",
|
||||
|
||||
@@ -26,9 +26,17 @@
|
||||
"agentRuntimePackage": { "type": ["string", "null"], "maxLength": 240 },
|
||||
"agentRuntimeVersion": { "type": ["string", "null"], "maxLength": 120 },
|
||||
"acpxRecordId": { "type": ["string", "null"], "maxLength": 240 },
|
||||
"piThinkingLevel": { "enum": ["off", "low", "high", "max"] },
|
||||
"turnControls": { "$ref": "#/$defs/turnControls" }
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"if": { "required": ["piThinkingLevel"] },
|
||||
"then": {
|
||||
"properties": { "provider": { "const": "acpx" }, "agent": { "const": "pi" } },
|
||||
"required": ["agent"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
|
||||
@@ -14,7 +14,7 @@ use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::acpx_provider_session::{
|
||||
AcpxPermissionMode, AcpxProviderRuntimePolicy, AcpxProviderSession, AcpxProviderSessionConfig,
|
||||
AcpxProviderSessionIdentity, AcpxTurnControlCapabilities, CursorMode,
|
||||
AcpxProviderSessionIdentity, AcpxTurnControlCapabilities, CursorMode, PiThinkingLevel,
|
||||
};
|
||||
use crate::acpx_sidecar_transport::AcpxSidecarTransportConfig;
|
||||
#[cfg(test)]
|
||||
@@ -137,6 +137,8 @@ struct AcpxProviderDescriptor {
|
||||
permission_mode: AcpxPermissionMode,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cursor_mode: Option<CursorMode>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pi_thinking_level: Option<PiThinkingLevel>,
|
||||
permission_mode_pinned: bool,
|
||||
#[serde(default)]
|
||||
provider_policy: Option<AcpxProviderRuntimePolicy>,
|
||||
@@ -207,7 +209,7 @@ impl AcpxProviderDescriptor {
|
||||
"0.0.33",
|
||||
Some("@earendil-works/pi-coding-agent"),
|
||||
Some("1.0.0"),
|
||||
"sha256:47306e6d2a9b59e8f9189f725ebb7a0a7f91826044d1739e1a35ab31f228ba1f",
|
||||
"sha256:fe1e6da01b2a9e4c691ca27cf689d2d6de846a93be6b23fc1e103c9addd7b177",
|
||||
),
|
||||
"cursor" => (
|
||||
self.model.as_str(),
|
||||
@@ -249,6 +251,7 @@ impl AcpxProviderDescriptor {
|
||||
|| self.model.len() > 240
|
||||
|| self.model.contains('\0')
|
||||
|| ((self.agent == "cursor") != self.cursor_mode.is_some())
|
||||
|| ((self.agent == "pi") != self.pi_thinking_level.is_some())
|
||||
|| (matches!(self.agent.as_str(), "pi" | "cursor" | "copilot")
|
||||
&& self.provider_policy.is_none())
|
||||
|| self.agent_server_package != expected.1
|
||||
@@ -345,6 +348,7 @@ impl AcpxProviderDescriptor {
|
||||
working_directory: PathBuf::from(&self.cwd),
|
||||
permission_mode: self.permission_mode,
|
||||
cursor_mode: self.cursor_mode,
|
||||
pi_thinking_level: self.pi_thinking_level,
|
||||
permission_mode_pinned: self.permission_mode_pinned,
|
||||
provider_policy: self.provider_policy.clone(),
|
||||
system_instructions: self.instructions.clone(),
|
||||
@@ -445,6 +449,9 @@ impl AcpxProviderDescriptor {
|
||||
"acpxRecordId": identity.map(|value| value.acpx_record_id.as_str()),
|
||||
"permissionMode": self.permission_mode,
|
||||
});
|
||||
if let Some(level) = self.pi_thinking_level {
|
||||
descriptor["piThinkingLevel"] = json!(level);
|
||||
}
|
||||
if let Some(mode) = self.cursor_mode {
|
||||
descriptor["cursorMode"] = json!(mode);
|
||||
}
|
||||
@@ -580,9 +587,10 @@ impl AcpxDurableState {
|
||||
.map_err(|error| DurableRunnerError::invalid(error.to_string()))?;
|
||||
if identity.profile_digest != self.descriptor.command_digest
|
||||
|| identity.cursor_mode != self.descriptor.cursor_mode
|
||||
|| identity.pi_thinking_level != self.descriptor.pi_thinking_level
|
||||
{
|
||||
return Err(DurableRunnerError::invalid(
|
||||
"ACPX durable identity no longer matches its qualified profile or Cursor mode",
|
||||
"ACPX durable identity no longer matches its qualified profile or provider mode",
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1194,16 +1202,21 @@ impl AcpxCommandExecutor {
|
||||
session_event_payload(&state.descriptor, &identity, process_id, turn_controls);
|
||||
let goal = self.goal_control("session.goal.get", &json!({}))?;
|
||||
self.save_state()?;
|
||||
let mut result = json!({
|
||||
"status": if resumed { "resumed" } else { "started" },
|
||||
"provider": "acpx",
|
||||
"driver": "acpx_runtime",
|
||||
"providerVersion": "0.13.1",
|
||||
"providerSessionId": identity.acpx_record_id,
|
||||
"sessionId": identity.agent_session_id,
|
||||
"processId": process_id,
|
||||
});
|
||||
if let Some(level) = identity.pi_thinking_level {
|
||||
// This identity is admitted only after the sidecar's effective-mode ACK.
|
||||
result["piThinkingLevel"] = json!(level);
|
||||
}
|
||||
Ok(CommandExecution {
|
||||
result: json!({
|
||||
"status": if resumed { "resumed" } else { "started" },
|
||||
"provider": "acpx",
|
||||
"driver": "acpx_runtime",
|
||||
"providerVersion": "0.13.1",
|
||||
"providerSessionId": identity.acpx_record_id,
|
||||
"sessionId": identity.agent_session_id,
|
||||
"processId": process_id,
|
||||
}),
|
||||
result,
|
||||
events: [(
|
||||
if resumed {
|
||||
"session.resumed"
|
||||
@@ -2530,6 +2543,7 @@ mod tests {
|
||||
effective_model: descriptor.model.clone(),
|
||||
permission_mode: Some(descriptor.permission_mode),
|
||||
cursor_mode: descriptor.cursor_mode,
|
||||
pi_thinking_level: descriptor.pi_thinking_level,
|
||||
provider_lifetime_fence_candidates: [60_001, 60_002, 60_003],
|
||||
};
|
||||
let operations = Vec::new();
|
||||
@@ -2780,6 +2794,7 @@ mod tests {
|
||||
effective_model: "gpt-5.6-sol".to_owned(),
|
||||
permission_mode: Some(AcpxPermissionMode::ApproveReads),
|
||||
cursor_mode: None,
|
||||
pi_thinking_level: None,
|
||||
provider_lifetime_fence_candidates: [60_001, 60_002, 60_003],
|
||||
};
|
||||
|
||||
@@ -2821,7 +2836,7 @@ mod tests {
|
||||
"pi",
|
||||
"pi-acp",
|
||||
"0.0.33",
|
||||
"sha256:47306e6d2a9b59e8f9189f725ebb7a0a7f91826044d1739e1a35ab31f228ba1f",
|
||||
"sha256:fe1e6da01b2a9e4c691ca27cf689d2d6de846a93be6b23fc1e103c9addd7b177",
|
||||
Some("@earendil-works/pi-coding-agent"),
|
||||
Some("1.0.0"),
|
||||
"openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
@@ -2841,8 +2856,68 @@ mod tests {
|
||||
if agent == "cursor" {
|
||||
value["cursorMode"] = json!("agent");
|
||||
}
|
||||
if agent == "pi" {
|
||||
value["piThinkingLevel"] = json!("low");
|
||||
}
|
||||
let valid: AcpxProviderDescriptor = serde_json::from_value(value.clone()).unwrap();
|
||||
valid.validate(&context()).unwrap();
|
||||
if agent == "pi" {
|
||||
assert_eq!(
|
||||
valid.public_descriptor(None)["piThinkingLevel"],
|
||||
json!("low")
|
||||
);
|
||||
let mut missing = value.clone();
|
||||
missing.as_object_mut().unwrap().remove("piThinkingLevel");
|
||||
assert!(serde_json::from_value::<AcpxProviderDescriptor>(missing)
|
||||
.unwrap()
|
||||
.validate(&context())
|
||||
.is_err());
|
||||
for alias in ["medium", "minimal", "xhigh", "Low"] {
|
||||
let mut wrong = value.clone();
|
||||
wrong["piThinkingLevel"] = json!(alias);
|
||||
assert!(serde_json::from_value::<AcpxProviderDescriptor>(wrong).is_err());
|
||||
}
|
||||
let operations = Vec::new();
|
||||
let tools = AuthorizedToolSet {
|
||||
schema: TOOL_SET_SCHEMA.to_owned(),
|
||||
schema_version: 1,
|
||||
catalog_digest: authorized_tool_catalog_digest(&operations).unwrap(),
|
||||
operations,
|
||||
};
|
||||
let launch_digest = format!("sha256:{}", "a".repeat(64));
|
||||
let mut state = AcpxDurableState::new(valid.clone(), tools, launch_digest.clone());
|
||||
state.identity = Some(AcpxProviderSessionIdentity {
|
||||
kind: "acpx".to_owned(),
|
||||
normalized_session_id: "session-1".to_owned(),
|
||||
acpx_record_id: "record-1".to_owned(),
|
||||
backend_session_id: "backend-1".to_owned(),
|
||||
agent_session_id: "agent-1".to_owned(),
|
||||
profile_digest: valid.command_digest.clone(),
|
||||
workspace_digest: format!("sha256:{}", "b".repeat(64)),
|
||||
requested_model: valid.model.clone(),
|
||||
effective_model: valid.model.clone(),
|
||||
permission_mode: Some(valid.permission_mode),
|
||||
cursor_mode: None,
|
||||
pi_thinking_level: Some(PiThinkingLevel::Low),
|
||||
provider_lifetime_fence_candidates: [60_001, 60_002, 60_003],
|
||||
});
|
||||
state.validate(&context(), &launch_digest).unwrap();
|
||||
for level in [None, Some(PiThinkingLevel::High)] {
|
||||
state.identity.as_mut().unwrap().pi_thinking_level = level;
|
||||
assert!(state.validate(&context(), &launch_digest).is_err());
|
||||
}
|
||||
} else {
|
||||
assert!(valid
|
||||
.public_descriptor(None)
|
||||
.get("piThinkingLevel")
|
||||
.is_none());
|
||||
let mut wrong = value.clone();
|
||||
wrong["piThinkingLevel"] = json!("low");
|
||||
assert!(serde_json::from_value::<AcpxProviderDescriptor>(wrong)
|
||||
.unwrap()
|
||||
.validate(&context())
|
||||
.is_err());
|
||||
}
|
||||
if matches!(agent, "cursor" | "copilot") {
|
||||
let mut previous_v9 = value.clone();
|
||||
previous_v9["commandDigest"] = json!(match agent {
|
||||
@@ -3096,6 +3171,7 @@ mod tests {
|
||||
effective_model: original_descriptor.model.clone(),
|
||||
permission_mode: Some(original_descriptor.permission_mode),
|
||||
cursor_mode: original_descriptor.cursor_mode,
|
||||
pi_thinking_level: original_descriptor.pi_thinking_level,
|
||||
provider_lifetime_fence_candidates: [60_001, 60_002, 60_003],
|
||||
};
|
||||
let operations = Vec::new();
|
||||
@@ -3423,6 +3499,7 @@ mod tests {
|
||||
effective_model: descriptor.model.clone(),
|
||||
permission_mode: Some(descriptor.permission_mode),
|
||||
cursor_mode: descriptor.cursor_mode,
|
||||
pi_thinking_level: descriptor.pi_thinking_level,
|
||||
provider_lifetime_fence_candidates,
|
||||
};
|
||||
let operations = Vec::new();
|
||||
@@ -3595,6 +3672,7 @@ mod tests {
|
||||
effective_model: provider_descriptor.model.clone(),
|
||||
permission_mode: Some(provider_descriptor.permission_mode),
|
||||
cursor_mode: provider_descriptor.cursor_mode,
|
||||
pi_thinking_level: provider_descriptor.pi_thinking_level,
|
||||
provider_lifetime_fence_candidates,
|
||||
});
|
||||
state.provider_exit_unconfirmed = true;
|
||||
|
||||
@@ -11,6 +11,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::acpx_provider_session::{
|
||||
AcpxPermissionMode, AcpxProviderSessionConfig, AcpxProviderSessionIdentity, CursorMode,
|
||||
PiThinkingLevel,
|
||||
};
|
||||
use crate::durable::{
|
||||
create_private_temporary_file, open_private_regular_file, verify_private_directory,
|
||||
@@ -50,6 +51,8 @@ struct PersistedAcpxProviderSessionIdentity {
|
||||
permission_mode: AcpxPermissionMode,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cursor_mode: Option<CursorMode>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pi_thinking_level: Option<PiThinkingLevel>,
|
||||
provider_lifetime_fence_candidates: [u16; 3],
|
||||
}
|
||||
|
||||
@@ -73,6 +76,7 @@ impl PersistedAcpxProviderSessionIdentity {
|
||||
effective_model: identity.effective_model,
|
||||
permission_mode,
|
||||
cursor_mode: identity.cursor_mode,
|
||||
pi_thinking_level: identity.pi_thinking_level,
|
||||
provider_lifetime_fence_candidates: identity.provider_lifetime_fence_candidates,
|
||||
})
|
||||
}
|
||||
@@ -90,6 +94,7 @@ impl PersistedAcpxProviderSessionIdentity {
|
||||
effective_model: self.effective_model.clone(),
|
||||
permission_mode: Some(self.permission_mode),
|
||||
cursor_mode: self.cursor_mode,
|
||||
pi_thinking_level: self.pi_thinking_level,
|
||||
provider_lifetime_fence_candidates: self.provider_lifetime_fence_candidates,
|
||||
}
|
||||
}
|
||||
@@ -111,6 +116,7 @@ impl AcpxSuspensionCheckpoint {
|
||||
|| identity.effective_model != config.model
|
||||
|| identity.permission_mode != Some(config.permission_mode)
|
||||
|| identity.cursor_mode != config.cursor_mode
|
||||
|| identity.pi_thinking_level != config.pi_thinking_level
|
||||
|| config
|
||||
.expected_identity
|
||||
.as_ref()
|
||||
|
||||
@@ -43,6 +43,16 @@ pub enum CursorMode {
|
||||
Ask,
|
||||
}
|
||||
|
||||
/// Exact native Pi modes. No aliases, clamping, or implicit Rust default.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PiThinkingLevel {
|
||||
Off,
|
||||
Low,
|
||||
High,
|
||||
Max,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AcpxProviderSessionIdentity {
|
||||
@@ -59,6 +69,8 @@ pub struct AcpxProviderSessionIdentity {
|
||||
pub permission_mode: Option<AcpxPermissionMode>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cursor_mode: Option<CursorMode>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pi_thinking_level: Option<PiThinkingLevel>,
|
||||
pub provider_lifetime_fence_candidates: [u16; 3],
|
||||
}
|
||||
|
||||
@@ -80,6 +92,7 @@ pub struct AcpxProviderSessionConfig {
|
||||
pub working_directory: PathBuf,
|
||||
pub permission_mode: AcpxPermissionMode,
|
||||
pub cursor_mode: Option<CursorMode>,
|
||||
pub pi_thinking_level: Option<PiThinkingLevel>,
|
||||
pub permission_mode_pinned: bool,
|
||||
pub provider_policy: Option<AcpxProviderRuntimePolicy>,
|
||||
pub system_instructions: String,
|
||||
@@ -115,6 +128,11 @@ impl AcpxProviderSessionConfig {
|
||||
"ACPX Cursor mode must be explicit for Cursor and absent for other agents",
|
||||
));
|
||||
}
|
||||
if (self.agent == "pi") != self.pi_thinking_level.is_some() {
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX Pi thinking level must be explicit for Pi and absent for other agents",
|
||||
));
|
||||
}
|
||||
if matches!(self.agent.as_str(), "pi" | "cursor" | "copilot")
|
||||
&& self.provider_policy.is_none()
|
||||
{
|
||||
@@ -187,6 +205,7 @@ impl AcpxProviderSessionConfig {
|
||||
|| expected_identity.effective_model != self.model
|
||||
|| expected_identity.permission_mode != Some(self.permission_mode)
|
||||
|| expected_identity.cursor_mode != self.cursor_mode
|
||||
|| expected_identity.pi_thinking_level != self.pi_thinking_level
|
||||
{
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX expected identity conflicts with the requested session",
|
||||
@@ -1266,6 +1285,9 @@ fn session_open_params(config: &AcpxProviderSessionConfig, sidecar_tools: &[Valu
|
||||
"tools": &sidecar_tools,
|
||||
"expectedIdentity": config.expected_identity,
|
||||
});
|
||||
if let Some(level) = config.pi_thinking_level {
|
||||
params["piThinkingLevel"] = json!(level);
|
||||
}
|
||||
if let Some(mode) = config.cursor_mode {
|
||||
params["cursorMode"] = json!(mode);
|
||||
}
|
||||
@@ -1379,6 +1401,7 @@ fn verify_open_response(
|
||||
|| identity.effective_model != config.model
|
||||
|| identity.permission_mode != Some(config.permission_mode)
|
||||
|| identity.cursor_mode != config.cursor_mode
|
||||
|| identity.pi_thinking_level != config.pi_thinking_level
|
||||
|| config
|
||||
.expected_identity
|
||||
.as_ref()
|
||||
@@ -1603,7 +1626,7 @@ mod permission_mode_tests {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cursor_mode_tests {
|
||||
mod provider_mode_tests {
|
||||
use super::*;
|
||||
|
||||
fn config() -> AcpxProviderSessionConfig {
|
||||
@@ -1625,6 +1648,7 @@ mod cursor_mode_tests {
|
||||
working_directory: std::env::temp_dir(),
|
||||
permission_mode: AcpxPermissionMode::ApproveReads,
|
||||
cursor_mode: Some(CursorMode::Plan),
|
||||
pi_thinking_level: None,
|
||||
permission_mode_pinned: true,
|
||||
provider_policy: Some(AcpxProviderRuntimePolicy { read_only: false }),
|
||||
system_instructions: String::new(),
|
||||
@@ -1651,6 +1675,7 @@ mod cursor_mode_tests {
|
||||
effective_model: "explicit-model".to_owned(),
|
||||
permission_mode: Some(AcpxPermissionMode::ApproveReads),
|
||||
cursor_mode: Some(CursorMode::Plan),
|
||||
pi_thinking_level: None,
|
||||
provider_lifetime_fence_candidates: [60_001, 60_002, 60_003],
|
||||
}
|
||||
}
|
||||
@@ -1739,4 +1764,137 @@ mod cursor_mode_tests {
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
fn pi_config() -> AcpxProviderSessionConfig {
|
||||
let mut config = config();
|
||||
config.agent = "pi".to_owned();
|
||||
config.model = "openrouter/deepseek/deepseek-v4-flash-0731".to_owned();
|
||||
config.cursor_mode = None;
|
||||
config.pi_thinking_level = Some(PiThinkingLevel::Low);
|
||||
config
|
||||
}
|
||||
|
||||
fn pi_identity(config: &AcpxProviderSessionConfig) -> AcpxProviderSessionIdentity {
|
||||
let mut identity = identity();
|
||||
identity.requested_model = config.model.clone();
|
||||
identity.effective_model = config.model.clone();
|
||||
identity.cursor_mode = None;
|
||||
identity.pi_thinking_level = config.pi_thinking_level;
|
||||
identity
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pi_thinking_level_is_closed_explicit_and_pi_only() {
|
||||
for (name, level) in [
|
||||
("off", PiThinkingLevel::Off),
|
||||
("low", PiThinkingLevel::Low),
|
||||
("high", PiThinkingLevel::High),
|
||||
("max", PiThinkingLevel::Max),
|
||||
] {
|
||||
assert_eq!(
|
||||
serde_json::from_value::<PiThinkingLevel>(json!(name)).unwrap(),
|
||||
level
|
||||
);
|
||||
assert_eq!(serde_json::to_value(level).unwrap(), json!(name));
|
||||
}
|
||||
for value in [
|
||||
json!("medium"),
|
||||
json!("minimal"),
|
||||
json!("xhigh"),
|
||||
json!("Low"),
|
||||
json!(" low"),
|
||||
json!(null),
|
||||
json!(1),
|
||||
] {
|
||||
assert!(serde_json::from_value::<PiThinkingLevel>(value).is_err());
|
||||
}
|
||||
let mut config = pi_config();
|
||||
config.validate().unwrap();
|
||||
config.pi_thinking_level = None;
|
||||
assert!(config.validate().is_err());
|
||||
config = self::config();
|
||||
config.pi_thinking_level = Some(PiThinkingLevel::Low);
|
||||
assert!(config.validate().is_err());
|
||||
config.pi_thinking_level = None;
|
||||
config.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pi_thinking_open_requires_exact_effective_ack_for_every_level() {
|
||||
let mut config = pi_config();
|
||||
for level in [
|
||||
PiThinkingLevel::Off,
|
||||
PiThinkingLevel::Low,
|
||||
PiThinkingLevel::High,
|
||||
PiThinkingLevel::Max,
|
||||
] {
|
||||
config.pi_thinking_level = Some(level);
|
||||
assert_eq!(
|
||||
session_open_params(&config, &[])["piThinkingLevel"],
|
||||
json!(level)
|
||||
);
|
||||
let identity = pi_identity(&config);
|
||||
let response = json!({"sidecarPid": 100, "status": {}, "identity": identity});
|
||||
assert_eq!(
|
||||
verify_open_response(&response, 100, &config).unwrap(),
|
||||
identity
|
||||
);
|
||||
for wrong in [
|
||||
None,
|
||||
Some(PiThinkingLevel::Off),
|
||||
Some(PiThinkingLevel::Low),
|
||||
Some(PiThinkingLevel::High),
|
||||
Some(PiThinkingLevel::Max),
|
||||
] {
|
||||
if wrong == Some(level) {
|
||||
continue;
|
||||
}
|
||||
let mut changed = response.clone();
|
||||
changed["identity"]["piThinkingLevel"] = json!(wrong);
|
||||
assert!(verify_open_response(&changed, 100, &config).is_err());
|
||||
}
|
||||
let mut missing = response.clone();
|
||||
missing["identity"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("piThinkingLevel");
|
||||
assert!(verify_open_response(&missing, 100, &config).is_err());
|
||||
let mut alias = response.clone();
|
||||
alias["identity"]["piThinkingLevel"] = json!("medium");
|
||||
assert!(verify_open_response(&alias, 100, &config).is_err());
|
||||
}
|
||||
let non_pi = self::config();
|
||||
assert!(session_open_params(&non_pi, &[])
|
||||
.get("piThinkingLevel")
|
||||
.is_none());
|
||||
let mut foreign = identity();
|
||||
foreign.pi_thinking_level = Some(PiThinkingLevel::Low);
|
||||
assert!(verify_open_response(
|
||||
&json!({"sidecarPid":100,"status":{},"identity":foreign}),
|
||||
100,
|
||||
&non_pi
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pi_thinking_reopen_and_suspend_reject_missing_or_changed_mode() {
|
||||
let mut config = pi_config();
|
||||
let identity = pi_identity(&config);
|
||||
config.expected_identity = Some(identity.clone());
|
||||
config.validate().unwrap();
|
||||
for level in [None, Some(PiThinkingLevel::High)] {
|
||||
let mut old = identity.clone();
|
||||
old.pi_thinking_level = level;
|
||||
config.expected_identity = Some(old.clone());
|
||||
assert!(config.validate().is_err());
|
||||
assert!(
|
||||
verify_suspend_response(&json!({"suspended":true,"identity":old}), &identity)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
config.expected_identity = Some(identity.clone());
|
||||
config.pi_thinking_level = Some(PiThinkingLevel::High);
|
||||
assert!(config.validate().is_err());
|
||||
}
|
||||
}
|
||||
@@ -247,6 +247,9 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
"bootstrap"
|
||||
| "goals"
|
||||
| "bootstrap-wrong-pi-thinking"
|
||||
| "bootstrap-missing-pi-thinking"
|
||||
| "bootstrap-alias-pi-thinking"
|
||||
| "bootstrap-wrong-model"
|
||||
| "bootstrap-wrong-run"
|
||||
| "controls"
|
||||
@@ -804,6 +807,12 @@ fn bootstrap_success(
|
||||
"effectiveModel": if mode == "bootstrap-wrong-model" { "wrong-model" } else { model },
|
||||
"permissionMode": params.get("permissionMode"),
|
||||
"cursorMode": params.get("cursorMode"),
|
||||
"piThinkingLevel": match mode {
|
||||
"bootstrap-wrong-pi-thinking" => json!("high"),
|
||||
"bootstrap-missing-pi-thinking" => Value::Null,
|
||||
"bootstrap-alias-pi-thinking" => json!("medium"),
|
||||
_ => params.get("piThinkingLevel").cloned().unwrap_or(Value::Null),
|
||||
},
|
||||
"providerLifetimeFenceCandidates": [60001, 60002, 60003],
|
||||
},
|
||||
"status": {},
|
||||
|
||||
@@ -51,6 +51,7 @@ fn config(directory: &std::path::Path) -> AcpxProviderSessionConfig {
|
||||
working_directory: directory.to_owned(),
|
||||
permission_mode: AcpxPermissionMode::ApproveReads,
|
||||
cursor_mode: None,
|
||||
pi_thinking_level: None,
|
||||
permission_mode_pinned: true,
|
||||
provider_policy: None,
|
||||
system_instructions: "Complete the supplied task.".to_owned(),
|
||||
@@ -78,6 +79,7 @@ fn identity() -> AcpxProviderSessionIdentity {
|
||||
effective_model: "gpt-5.6-sol".to_owned(),
|
||||
permission_mode: Some(AcpxPermissionMode::ApproveReads),
|
||||
cursor_mode: None,
|
||||
pi_thinking_level: None,
|
||||
provider_lifetime_fence_candidates: [60_001, 60_002, 60_003],
|
||||
}
|
||||
}
|
||||
@@ -290,3 +292,49 @@ fn cursor_mode_round_trips_checkpoint_and_rejects_changed_or_missing_recovery_mo
|
||||
assert!(recovered.admit_recovery(&other).is_err());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pi_thinking_level_round_trips_and_rejects_legacy_or_changed_recovery() {
|
||||
use paperclip_runner_core::acpx_provider_session::{
|
||||
AcpxProviderRuntimePolicy, PiThinkingLevel,
|
||||
};
|
||||
let directory = temporary_directory("pi-thinking");
|
||||
let mut config = config(&directory);
|
||||
config.agent = "pi".to_owned();
|
||||
config.model = "openrouter/deepseek/deepseek-v4-flash-0731".to_owned();
|
||||
config.pi_thinking_level = Some(PiThinkingLevel::Low);
|
||||
config.provider_policy = Some(AcpxProviderRuntimePolicy { read_only: false });
|
||||
let mut identity = identity();
|
||||
identity.requested_model = config.model.clone();
|
||||
identity.effective_model = config.model.clone();
|
||||
identity.pi_thinking_level = Some(PiThinkingLevel::Low);
|
||||
let checkpoint = AcpxSuspensionCheckpoint::from_suspension(&config, identity.clone()).unwrap();
|
||||
let store = AcpxSuspensionCheckpointStore::new(&directory).unwrap();
|
||||
store.save(&checkpoint).unwrap();
|
||||
let recovered = store.load().unwrap().unwrap();
|
||||
assert_eq!(recovered.admit_recovery(&config).unwrap(), identity);
|
||||
let wire = serde_json::to_value(&recovered).unwrap();
|
||||
assert_eq!(wire["identity"]["piThinkingLevel"], json!("low"));
|
||||
for level in [
|
||||
None,
|
||||
Some(PiThinkingLevel::Off),
|
||||
Some(PiThinkingLevel::High),
|
||||
Some(PiThinkingLevel::Max),
|
||||
] {
|
||||
let mut changed_config = config.clone();
|
||||
changed_config.pi_thinking_level = level;
|
||||
assert!(recovered.admit_recovery(&changed_config).is_err());
|
||||
let mut changed = wire.clone();
|
||||
changed["identity"]["piThinkingLevel"] = json!(level);
|
||||
let changed: AcpxSuspensionCheckpoint = serde_json::from_value(changed).unwrap();
|
||||
assert!(changed.admit_recovery(&config).is_err());
|
||||
}
|
||||
let mut legacy = wire;
|
||||
legacy["identity"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("piThinkingLevel");
|
||||
let legacy: AcpxSuspensionCheckpoint = serde_json::from_value(legacy).unwrap();
|
||||
assert!(legacy.admit_recovery(&config).is_err());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
@@ -50,6 +50,7 @@ fn config(mode: &str) -> AcpxProviderSessionConfig {
|
||||
working_directory: std::env::temp_dir(),
|
||||
permission_mode: AcpxPermissionMode::ApproveReads,
|
||||
cursor_mode: None,
|
||||
pi_thinking_level: None,
|
||||
permission_mode_pinned: true,
|
||||
provider_policy: None,
|
||||
system_instructions: "Complete the supplied task.".to_owned(),
|
||||
@@ -317,6 +318,10 @@ fn permission_origin_is_bound_to_the_admitted_connection_and_survives_projection
|
||||
"explicit-test-model"
|
||||
}
|
||||
.to_owned();
|
||||
if agent == "pi" {
|
||||
cfg.pi_thinking_level =
|
||||
Some(paperclip_runner_core::acpx_provider_session::PiThinkingLevel::Low);
|
||||
}
|
||||
if agent == "cursor" {
|
||||
cfg.cursor_mode = Some(paperclip_runner_core::acpx_provider_session::CursorMode::Agent);
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ fn config(mode: &str) -> AcpxProviderSessionConfig {
|
||||
working_directory: std::env::temp_dir(),
|
||||
permission_mode: AcpxPermissionMode::ApproveReads,
|
||||
cursor_mode: None,
|
||||
pi_thinking_level: None,
|
||||
permission_mode_pinned: true,
|
||||
provider_policy: None,
|
||||
system_instructions: "Complete the supplied task.".to_owned(),
|
||||
@@ -67,6 +68,7 @@ fn expected_identity() -> AcpxProviderSessionIdentity {
|
||||
effective_model: "gpt-5.6-sol".to_owned(),
|
||||
permission_mode: Some(AcpxPermissionMode::ApproveReads),
|
||||
cursor_mode: None,
|
||||
pi_thinking_level: None,
|
||||
provider_lifetime_fence_candidates: [60_001, 60_002, 60_003],
|
||||
}
|
||||
}
|
||||
@@ -343,3 +345,41 @@ fn receiver_rejects_sub_megabyte_tool_event_before_pending_admission_or_resoluti
|
||||
fn receiver_admits_normal_tool_event_and_resolves_only_correlated_call_once() {
|
||||
check_tool_receiver_admission(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pi_thinking_effective_identity_is_admitted_before_any_turn() {
|
||||
use paperclip_runner_core::acpx_provider_session::{
|
||||
AcpxProviderRuntimePolicy, PiThinkingLevel,
|
||||
};
|
||||
let mut cfg = config("bootstrap");
|
||||
cfg.agent = "pi".to_owned();
|
||||
cfg.model = "openrouter/deepseek/deepseek-v4-flash-0731".to_owned();
|
||||
cfg.pi_thinking_level = Some(PiThinkingLevel::Low);
|
||||
cfg.provider_policy = Some(AcpxProviderRuntimePolicy { read_only: false });
|
||||
let mut session = AcpxProviderSession::start(&cfg).unwrap();
|
||||
assert_eq!(
|
||||
session.identity().pi_thinking_level,
|
||||
Some(PiThinkingLevel::Low)
|
||||
);
|
||||
assert!(session.state().active_turn_id().is_none());
|
||||
let identity = session.identity().clone();
|
||||
session.shutdown("thinking mode admitted").unwrap();
|
||||
cfg.expected_identity = Some(identity);
|
||||
let mut restored = AcpxProviderSession::start(&cfg).unwrap();
|
||||
assert_eq!(
|
||||
restored.identity().pi_thinking_level,
|
||||
Some(PiThinkingLevel::Low)
|
||||
);
|
||||
assert!(restored.state().active_turn_id().is_none());
|
||||
restored
|
||||
.shutdown("restored thinking mode admitted")
|
||||
.unwrap();
|
||||
for mode in [
|
||||
"bootstrap-wrong-pi-thinking",
|
||||
"bootstrap-missing-pi-thinking",
|
||||
"bootstrap-alias-pi-thinking",
|
||||
] {
|
||||
cfg.transport.args = vec!["--mode".to_owned(), mode.to_owned()];
|
||||
assert!(start_error(&cfg).contains("identity"));
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ fn config(mode: &str) -> AcpxProviderSessionConfig {
|
||||
working_directory: std::env::temp_dir(),
|
||||
permission_mode: AcpxPermissionMode::ApproveReads,
|
||||
cursor_mode: None,
|
||||
pi_thinking_level: None,
|
||||
permission_mode_pinned: true,
|
||||
provider_policy: None,
|
||||
system_instructions: "Complete the supplied task.".to_owned(),
|
||||
|
||||
@@ -55,6 +55,9 @@ fn config(mode: &str) -> AcpxProviderSessionConfig {
|
||||
working_directory: std::env::temp_dir(),
|
||||
permission_mode: AcpxPermissionMode::ApproveReads,
|
||||
cursor_mode: None,
|
||||
pi_thinking_level: mode
|
||||
.starts_with("controls")
|
||||
.then_some(paperclip_runner_core::acpx_provider_session::PiThinkingLevel::Low),
|
||||
permission_mode_pinned: true,
|
||||
provider_policy: if mode.starts_with("controls") {
|
||||
Some(
|
||||
|
||||
+36
-1
@@ -17,7 +17,7 @@ use sha2::{Digest, Sha256};
|
||||
const CODEX_ACPX_DIGEST: &str =
|
||||
"sha256:c4538599d1ab767db5dff50934f13bb5ba313a59d9c4a83e993fac4617ea63d3";
|
||||
const PI_ACPX_DIGEST: &str =
|
||||
"sha256:47306e6d2a9b59e8f9189f725ebb7a0a7f91826044d1739e1a35ab31f228ba1f";
|
||||
"sha256:fe1e6da01b2a9e4c691ca27cf689d2d6de846a93be6b23fc1e103c9addd7b177";
|
||||
|
||||
fn temporary_directory(label: &str) -> PathBuf {
|
||||
let nonce = SystemTime::now()
|
||||
@@ -236,6 +236,7 @@ fn pi_prepare_payload(directory: &Path, mode: &str) -> Value {
|
||||
provider["commandDigest"] = json!(PI_ACPX_DIGEST);
|
||||
provider["sidecarArgs"][3] = json!(PI_ACPX_DIGEST);
|
||||
provider["providerPolicy"] = json!({"readOnly":true});
|
||||
provider["piThinkingLevel"] = json!("low");
|
||||
payload
|
||||
}
|
||||
|
||||
@@ -1374,6 +1375,40 @@ fn rejects_pi_with_an_unqualified_model_before_starting_a_sidecar() {
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pi_thinking_change_cannot_attach_to_an_existing_provider_identity() {
|
||||
let directory = temporary_directory("pi-thinking-attach");
|
||||
let config = pi_acpx_config(&directory, "bootstrap");
|
||||
let payload = pi_prepare_payload(&directory, "bootstrap");
|
||||
let mut executor = NativeProviderCommandExecutor::with_runner_config(&directory, &config);
|
||||
executor
|
||||
.execute(&command(1, "run.prepare", payload.clone()))
|
||||
.unwrap();
|
||||
let opened = executor
|
||||
.execute(&command(2, "session.open", json!({})))
|
||||
.unwrap();
|
||||
assert_eq!(opened.result["piThinkingLevel"], json!("low"));
|
||||
assert_eq!(
|
||||
opened.events[0].2["providerDescriptor"]["piThinkingLevel"],
|
||||
json!("low")
|
||||
);
|
||||
let state_path = directory.join("acpx-provider-state.json");
|
||||
let prior = fs::read(&state_path).unwrap();
|
||||
for (index, mode) in ["off", "high", "max"].into_iter().enumerate() {
|
||||
let mut changed = payload.clone();
|
||||
changed["provider"]["piThinkingLevel"] = json!(mode);
|
||||
let error = executor
|
||||
.execute(&command(3 + index as u64, "run.attach", changed))
|
||||
.unwrap_err();
|
||||
assert!(error
|
||||
.to_string()
|
||||
.contains("immutable_provider_identity_changed"));
|
||||
assert_eq!(fs::read(&state_path).unwrap(), prior);
|
||||
}
|
||||
executor.shutdown().unwrap();
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishes_only_changed_pi_controls_before_the_new_turn() {
|
||||
for (mode, initially_available, turn_available) in [
|
||||
|
||||
@@ -19,7 +19,7 @@ const patchPath = join(workspaceRoot, "patches/pi-acp@0.0.33.patch");
|
||||
const supportedTargets = new Set(["darwin-arm64", "darwin-x64", "linux-x64"]);
|
||||
export const PI_DISTRIBUTION_PINS = Object.freeze({
|
||||
wrapper: "0.0.33", runtime: "1.0.0", sdk: "0.26.0", zod: "3.25.76", nodeVersion: PI_NODE_VERSION, undici: "8.10.2", nodeBundledUndici: "7.29.1",
|
||||
wrapperSha256: "c41750802680543d72a5a43e21eaf91c31ca8cec833bbf5f27330614936810fe",
|
||||
wrapperSha256: "8ef777e9e6a3cef37775bab2b800e4931330c23a0b151ce07fdc5b943f28435d",
|
||||
helperSha256: "2191b1e5f281d24508ec7eaff39011ee863a8a70bf54f4aa0490ad0172b323da",
|
||||
});
|
||||
const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolvePiThinkingLevel } from "../drivers/acpx/pi-thinking.js";
|
||||
import type { NativeExecutionInput } from "../contracts/native-execution.js";
|
||||
import type { NativeSessionBackend } from "../contracts/native-session-backend.js";
|
||||
import {
|
||||
@@ -14,7 +15,7 @@ import {
|
||||
|
||||
export interface CodexAcpxNativeSessionBackendOptions extends Omit<
|
||||
CodexAcpxDriverOptions,
|
||||
"model" | "permissionMode" | "cursorMode" | "systemInstructions" | "providerPolicy" | "runtimeContext"
|
||||
"model" | "permissionMode" | "cursorMode" | "piThinkingLevel" | "systemInstructions" | "providerPolicy" | "runtimeContext"
|
||||
> {}
|
||||
|
||||
export type AcpxNativeSessionBackendOptions =
|
||||
@@ -58,6 +59,7 @@ export function createAcpxNativeSessionBackend(
|
||||
throw new Error("ACPX candidate direct execution requires completed qualification; use the host-controlled runnerd evaluation path");
|
||||
}
|
||||
|
||||
resolvePiThinkingLevel(input.provider.agent, input.provider.piThinkingLevel);
|
||||
const constraints = nativeTaskConstraints(input);
|
||||
const systemInstructions = [
|
||||
nativeSystemInstructions(input),
|
||||
@@ -73,6 +75,7 @@ export function createAcpxNativeSessionBackend(
|
||||
model: input.provider.model,
|
||||
permissionMode: input.provider.permissionMode ?? "approve-reads",
|
||||
cursorMode: input.provider.cursorMode,
|
||||
piThinkingLevel: input.provider.piThinkingLevel,
|
||||
systemInstructions,
|
||||
runtimeContext: "runtimeContext" in input ? input.runtimeContext : null,
|
||||
providerPolicy: { readOnly: "executionMode" in input && input.executionMode === "plan" },
|
||||
|
||||
@@ -550,7 +550,7 @@ describe("native backend factory", () => {
|
||||
const input = acpxExecution();
|
||||
if (input.provider.kind !== "acpx") throw new Error("invalid fixture");
|
||||
const profile = resolveQualifiedAcpxProfile("pi", QUALIFIED_ACPX_PROFILES.pi.qualificationModel);
|
||||
Object.assign(input.provider, { agent: "pi", model: profile.qualificationModel, profile });
|
||||
Object.assign(input.provider, { agent: "pi", model: profile.qualificationModel, piThinkingLevel: "low", profile });
|
||||
const backend = createNativeSessionBackend(input, { acpxRuntimeDirectory: "/runtime" });
|
||||
await expect(backend.descriptor()).resolves.toMatchObject({ name: "acpx_runtime", version: "0.13.1" });
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
import { resolvePiThinkingLevel } from "../drivers/acpx/pi-thinking.js";
|
||||
import { cursorPlanToolIdentity, cursorToolIdentity } from "../drivers/acpx/cursor-plan-tool-identity.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createInterface } from "node:readline";
|
||||
@@ -293,6 +294,7 @@ async function dispatch(
|
||||
model: params.model,
|
||||
permissionMode: params.permissionMode,
|
||||
cursorMode: params.cursorMode,
|
||||
piThinkingLevel: params.piThinkingLevel,
|
||||
providerPolicy: params.providerPolicy,
|
||||
systemInstructions: params.systemInstructions,
|
||||
runtimeContext: params.runtimeContext,
|
||||
@@ -1203,6 +1205,7 @@ function parseOpenParams(
|
||||
const agent = requireQualifiedAgent(value.agent);
|
||||
const model = requiredText(value.model, "model");
|
||||
if (value.cursorMode !== undefined && agent !== "cursor") throw new Error("cursorMode is supported only for Cursor");
|
||||
const piThinkingLevel = resolvePiThinkingLevel(agent, value.piThinkingLevel);
|
||||
resolveQualifiedAcpxProfile(agent, model);
|
||||
if (
|
||||
value.providerSessionKey !== undefined &&
|
||||
@@ -1223,6 +1226,7 @@ function parseOpenParams(
|
||||
model,
|
||||
permissionMode: requiredPermissionMode(value.permissionMode),
|
||||
...(agent === "cursor" ? { cursorMode: requiredCursorMode(value.cursorMode === undefined ? "agent" : value.cursorMode) } : {}),
|
||||
...(piThinkingLevel ? { piThinkingLevel } : {}),
|
||||
permissionModePinned: value.permissionModePinned === true,
|
||||
...(value.providerPolicy == null ? {} : { providerPolicy: parseProviderPolicy(value.providerPolicy) }),
|
||||
systemInstructions: boundedText(
|
||||
@@ -1293,6 +1297,7 @@ function parseExpectedIdentity(value: unknown): AcpxExpectedSessionIdentity {
|
||||
? {}
|
||||
: { permissionMode: requiredPermissionMode(input.permissionMode) }),
|
||||
...(input.cursorMode === undefined ? {} : { cursorMode: requiredCursorMode(input.cursorMode) }),
|
||||
...(input.piThinkingLevel === undefined ? {} : { piThinkingLevel: resolvePiThinkingLevel("pi", input.piThinkingLevel) }),
|
||||
providerLifetimeFenceCandidates: requiredFenceCandidates(
|
||||
input.providerLifetimeFenceCandidates,
|
||||
),
|
||||
|
||||
@@ -36,6 +36,7 @@ function request(overrides: Record<string, unknown> = {}): unknown {
|
||||
maxEstimatedCostNanodollars: 100_000_000,
|
||||
},
|
||||
session: {},
|
||||
...(overrides.acpxAgent === "pi" ? { piThinkingLevel: "low", session: { piThinkingLevel: "low" } } : {}),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -84,6 +85,13 @@ describe("eval-session request contract", () => {
|
||||
expect(() => parseEvalSessionRequest(value, { candidateProfile: "cursor" })).toThrow("must match");
|
||||
});
|
||||
|
||||
it("requires exact matching Pi mode in request and session and rejects aliases", () => {
|
||||
const base = { provider: "acpx", acpxAgent: "pi", model: "openrouter/deepseek/deepseek-v4-flash-0731" };
|
||||
for (const value of [undefined, "medium", "minimal", "xhigh", ""]) expect(() => parseEvalSessionRequest(request({ ...base, piThinkingLevel: value }))).toThrow();
|
||||
expect(() => parseEvalSessionRequest(request({ ...base, piThinkingLevel: "low", session: { piThinkingLevel: "high" } }))).toThrow(/must match/);
|
||||
expect(() => parseEvalSessionRequest(request({ piThinkingLevel: "low" }))).toThrow(/only supported/);
|
||||
});
|
||||
|
||||
it("accepts only known diagnostic flags and rejects ambiguous repeated arguments", () => {
|
||||
const args = ["--request", "/tmp/request.json", "--output", "/tmp/result.json"];
|
||||
const expected = resolveQualifiedAcpxProfile("pi", "openrouter/deepseek/deepseek-v4-flash-0731");
|
||||
@@ -110,7 +118,7 @@ describe("eval-session request contract", () => {
|
||||
try {
|
||||
await writeFile(requestPath, JSON.stringify(request({ provider: "acpx", acpxAgent: agent, model,
|
||||
runnerd: { path: join(workspace, "missing-runnerd"), sha256: "a".repeat(64) },
|
||||
session: { workingDirectory: workspace },
|
||||
session: { workingDirectory: workspace, ...(agent === "pi" ? { piThinkingLevel: "low" } : {}) },
|
||||
})));
|
||||
const { commandDigest: _removed, ...incomplete } = expected;
|
||||
for (const stale of [
|
||||
@@ -489,7 +497,7 @@ describe("eval-session budget settlement", () => {
|
||||
const shutdown = vi.fn(async () => { snapshot.status = "closed"; });
|
||||
const input = request({ provider: "acpx", acpxAgent: agent, model,
|
||||
runnerd: { path: binary, sha256: createHash("sha256").update("unused fake runner").digest("hex") },
|
||||
session: { workingDirectory: workspace }, limits: { turnTimeoutMs: 1000, maxAgentTurns: 2, maxEstimatedCostNanodollars: 100_000_000 },
|
||||
session: { workingDirectory: workspace, ...(agent === "pi" ? { piThinkingLevel: "low" } : {}) }, limits: { turnTimeoutMs: 1000, maxAgentTurns: 2, maxEstimatedCostNanodollars: 100_000_000 },
|
||||
});
|
||||
const requestPath = join(workspace, "request.json");
|
||||
const outputPath = join(workspace, "output.json");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolvePiThinkingLevel } from "../drivers/acpx/pi-thinking.js";
|
||||
import type {
|
||||
CapabilityLiveSessionSnapshot,
|
||||
CreateCapabilityLiveSessionInput,
|
||||
@@ -69,6 +70,7 @@ export interface EvalSessionRequest {
|
||||
driver?: EvalSessionDriver;
|
||||
opencodeVersion?: string;
|
||||
acpxAgent?: QualifiedAcpxAgent;
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
managedProfile?: EvalSessionManagedProfile;
|
||||
agentCoreProfile?: EvalSessionAgentCoreProfile;
|
||||
runnerd: { path: string; sha256: string };
|
||||
@@ -258,6 +260,7 @@ export function parseEvalSessionRequest(
|
||||
if (provider !== "acpx" && acpxAgent !== undefined) {
|
||||
throw new Error("eval-session acpxAgent requires provider acpx");
|
||||
}
|
||||
const piThinkingLevel = resolvePiThinkingLevel(provider === "acpx" ? String(acpxAgent) : "", input.piThinkingLevel);
|
||||
const candidate = acpxAgent === "pi" || acpxAgent === "cursor" || acpxAgent === "copilot";
|
||||
if (options.candidateProfile !== undefined && (provider !== "acpx" || acpxAgent !== options.candidateProfile || !candidate)) {
|
||||
throw new Error("--candidate-profile must match the request's registered candidate ACPX agent");
|
||||
@@ -327,6 +330,7 @@ export function parseEvalSessionRequest(
|
||||
throw new Error("request.session.acpxAgent must match request.acpxAgent");
|
||||
}
|
||||
|
||||
if (session.piThinkingLevel !== piThinkingLevel) throw new Error("request.session.piThinkingLevel must match request.piThinkingLevel");
|
||||
return {
|
||||
schema: EVAL_SESSION_REQUEST_SCHEMA,
|
||||
attemptId: text(input.attemptId, "request.attemptId"),
|
||||
@@ -338,6 +342,7 @@ export function parseEvalSessionRequest(
|
||||
? { opencodeVersion: text(input.opencodeVersion, "request.opencodeVersion") }
|
||||
: {}),
|
||||
...(acpxAgent === undefined ? {} : { acpxAgent }),
|
||||
...(piThinkingLevel === undefined ? {} : { piThinkingLevel }),
|
||||
...(managedProfile === undefined ? {} : { managedProfile }),
|
||||
...(agentCoreProfile === undefined ? {} : { agentCoreProfile }),
|
||||
runnerd: {
|
||||
|
||||
@@ -407,7 +407,7 @@ export async function runEvalSessionCli(
|
||||
provider: requestedProvider,
|
||||
requestedModel: request.model,
|
||||
...(requestedProvider === "acpx"
|
||||
? { acpxAgent: request.acpxAgent ?? "codex" }
|
||||
? { acpxAgent: request.acpxAgent ?? "codex", ...(request.piThinkingLevel === undefined ? {} : { piThinkingLevel: request.piThinkingLevel }) }
|
||||
: { acpxAgent: undefined }),
|
||||
...(request.managedProfile === undefined
|
||||
? {}
|
||||
@@ -450,6 +450,7 @@ export async function runEvalSessionCli(
|
||||
driver: requestedDriver,
|
||||
providerVersion: requestedProviderVersion,
|
||||
providerSessionId: snapshot.providerSessionId,
|
||||
...(request.acpxAgent === "pi" ? { piThinkingLevel: snapshot.process?.piThinkingLevel ?? null } : {}),
|
||||
...(requestedProvider === "claude_managed"
|
||||
? {
|
||||
managedProfile: request.managedProfile,
|
||||
|
||||
@@ -456,6 +456,7 @@ export interface AcpxSessionIdentity {
|
||||
permissionMode?: "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all";
|
||||
/** Effective native mode; required on current Cursor session identities. */
|
||||
cursorMode?: "agent" | "plan" | "ask";
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
providerLifetimeFenceCandidates: readonly [number, number, number];
|
||||
}
|
||||
|
||||
|
||||
@@ -328,7 +328,7 @@ describe("NativeExecutionInputV1", () => {
|
||||
profile: provider.profile,
|
||||
});
|
||||
expect(parseNativeExecutionInput(parsed)).toEqual(parsed);
|
||||
for (const unsupportedVersion of [0, 13, 1.5, "12", null]) {
|
||||
for (const unsupportedVersion of [0, 14, 1.5, "13", null]) {
|
||||
expect(() => parseNativeExecutionInput({
|
||||
...input,
|
||||
session: { ...input.session, driverKind: "acpx_runtime" },
|
||||
@@ -357,6 +357,7 @@ describe("NativeExecutionInputV1", () => {
|
||||
kind: "acpx", agent: declaration.agent,
|
||||
model: qualificationModel || "explicit-provider-model",
|
||||
permissionPolicy, profile,
|
||||
...(declaration.agent === "pi" ? { piThinkingLevel: "low" } : {}),
|
||||
};
|
||||
const parsed = parseNativeExecutionInput({
|
||||
...input,
|
||||
@@ -504,6 +505,14 @@ describe("native task context ownership", () => {
|
||||
});
|
||||
}
|
||||
|
||||
it.each(["off", "low", "high", "max"])("requires exact Pi13 thinking level %s in native input", piThinkingLevel => {
|
||||
const { qualificationModel, reportedModelId: _reported, permissionPolicy: _permission, modelPolicy: _policy, qualificationStatus: _status, ...profile } = QUALIFIED_ACPX_PROFILES.pi;
|
||||
const value = { ...currentInput(), session: { ...currentInput().session, driverKind: "acpx_runtime" }, provider: { kind: "acpx", agent: "pi", model: qualificationModel, permissionMode: "approve-all", piThinkingLevel, profile } };
|
||||
expect(parseNativeExecutionInput(value).provider).toEqual(value.provider);
|
||||
for (const mode of [undefined, null, "medium", "minimal", "xhigh", "", { toString: () => "low" }]) expect(() => parseNativeExecutionInput({ ...value, provider: { ...value.provider, piThinkingLevel: mode } })).toThrow(/piThinkingLevel/);
|
||||
expect(() => parseNativeExecutionInput({ ...value, provider: { ...value.provider, agent: "codex" } })).toThrow(/piThinkingLevel/);
|
||||
});
|
||||
|
||||
it.each(["agent", "plan", "ask"])("round-trips Cursor mode %s through the closed execution contract", cursorMode => {
|
||||
const { qualificationModel: _model, reportedModelId: _reported, permissionPolicy: _permission,
|
||||
modelPolicy: _policy, qualificationStatus: _status, ...profile } = QUALIFIED_ACPX_PROFILES.cursor;
|
||||
|
||||
@@ -91,7 +91,7 @@ export interface NativeAcpxProfileSnapshot {
|
||||
protocolVersion: 1;
|
||||
acpxVersion: "0.13.1";
|
||||
agent: NativeAcpxAgent;
|
||||
agentProfileVersion: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
|
||||
agentProfileVersion: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13;
|
||||
agentServerPackage: string;
|
||||
agentServerVersion: string;
|
||||
agentRuntimePackage: string | null;
|
||||
@@ -125,6 +125,7 @@ export type NativeProviderConfig =
|
||||
model: string;
|
||||
permissionMode?: NativeAcpxPermissionMode;
|
||||
cursorMode?: NativeCursorMode;
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
/** Present only in persisted v1-v3 inputs. */
|
||||
permissionPolicy?: "interactive";
|
||||
profile: NativeAcpxProfileSnapshot;
|
||||
@@ -140,6 +141,7 @@ export type NativeProviderConfigV4 =
|
||||
model: string;
|
||||
permissionMode: NativeAcpxPermissionMode;
|
||||
cursorMode?: NativeCursorMode;
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
profile: NativeAcpxProfileSnapshot;
|
||||
};
|
||||
|
||||
@@ -453,7 +455,7 @@ export function parseNativeExecutionInput(value: unknown): NativeExecutionInput
|
||||
: provider.kind === "aws_agentcore"
|
||||
? ["kind", "model", "agentCoreProfile", "maxEstimatedSessionCostUsd", "invocationLimits"]
|
||||
: provider.kind === "acpx"
|
||||
? ["kind", "agent", "model", isV4 ? "permissionMode" : "permissionPolicy", "profile", ...(isV4 ? ["cursorMode"] : [])]
|
||||
? ["kind", "agent", "model", isV4 ? "permissionMode" : "permissionPolicy", "profile", "piThinkingLevel", ...(isV4 ? ["cursorMode"] : [])]
|
||||
: provider.kind === "codex" && isV4
|
||||
? ["kind", "model", "approvalPolicy", ...(isV5 ? ["reasoningEffort"] : [])]
|
||||
: provider.kind === "opencode" && isV4
|
||||
@@ -573,6 +575,12 @@ export function parseNativeExecutionInput(value: unknown): NativeExecutionInput
|
||||
invocationLimits: { maxIterations, maxOutputTokens, timeoutSeconds },
|
||||
};
|
||||
} else if (provider.kind === "acpx") {
|
||||
if (provider.piThinkingLevel !== undefined && (provider.agent !== "pi" || (typeof provider.piThinkingLevel !== "string" || !["off", "low", "high", "max"].includes(provider.piThinkingLevel)))) {
|
||||
throw new NativeExecutionInputError("input.provider.piThinkingLevel must be off, low, high, or max and is supported only for Pi");
|
||||
}
|
||||
if (provider.agent === "pi" && record(provider.profile, "input.provider.profile").agentProfileVersion === 13 && provider.piThinkingLevel === undefined) {
|
||||
throw new NativeExecutionInputError("input.provider.piThinkingLevel is required for Pi profile 13");
|
||||
}
|
||||
if (provider.cursorMode !== undefined && (provider.agent !== "cursor"
|
||||
|| (provider.cursorMode !== "agent" && provider.cursorMode !== "plan" && provider.cursorMode !== "ask"))) {
|
||||
throw new NativeExecutionInputError("input.provider.cursorMode must be agent, plan, or ask and is supported only for Cursor");
|
||||
@@ -608,7 +616,7 @@ export function parseNativeExecutionInput(value: unknown): NativeExecutionInput
|
||||
|| profile.protocolVersion !== 1
|
||||
|| profile.acpxVersion !== "0.13.1"
|
||||
|| profile.agent !== provider.agent
|
||||
|| (profile.agentProfileVersion !== 1 && profile.agentProfileVersion !== 2 && profile.agentProfileVersion !== 3 && profile.agentProfileVersion !== 4 && profile.agentProfileVersion !== 5 && profile.agentProfileVersion !== 6 && profile.agentProfileVersion !== 7 && profile.agentProfileVersion !== 8 && profile.agentProfileVersion !== 9 && profile.agentProfileVersion !== 10 && profile.agentProfileVersion !== 11 && profile.agentProfileVersion !== 12)
|
||||
|| (profile.agentProfileVersion !== 1 && profile.agentProfileVersion !== 2 && profile.agentProfileVersion !== 3 && profile.agentProfileVersion !== 4 && profile.agentProfileVersion !== 5 && profile.agentProfileVersion !== 6 && profile.agentProfileVersion !== 7 && profile.agentProfileVersion !== 8 && profile.agentProfileVersion !== 9 && profile.agentProfileVersion !== 10 && profile.agentProfileVersion !== 11 && profile.agentProfileVersion !== 12 && profile.agentProfileVersion !== 13)
|
||||
) {
|
||||
throw new NativeExecutionInputError("input.provider.profile does not match the qualified ACPX v1 profile");
|
||||
}
|
||||
@@ -625,6 +633,7 @@ export function parseNativeExecutionInput(value: unknown): NativeExecutionInput
|
||||
? { permissionMode: provider.permissionMode as NativeAcpxPermissionMode }
|
||||
: { permissionPolicy: "interactive" as const }),
|
||||
...(provider.cursorMode === undefined ? {} : { cursorMode: provider.cursorMode as NativeCursorMode }),
|
||||
...(provider.piThinkingLevel === undefined ? {} : { piThinkingLevel: provider.piThinkingLevel as "off" | "low" | "high" | "max" }),
|
||||
profile: {
|
||||
driverKind: "acpx_runtime",
|
||||
protocolVersion: 1,
|
||||
|
||||
@@ -146,6 +146,7 @@ export interface CodexAcpxDriverOptions {
|
||||
model: string;
|
||||
permissionMode?: NativeAcpxPermissionMode;
|
||||
cursorMode?: "agent" | "plan" | "ask";
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
providerPolicy?: { readOnly: boolean };
|
||||
runtimeContext?: OpenAcpxRuntimeHostOptions["runtimeContext"];
|
||||
systemInstructions?: string;
|
||||
@@ -460,6 +461,7 @@ export class CodexAcpxDriver implements HarnessDriver {
|
||||
model: this.#options.model,
|
||||
permissionMode: this.#options.permissionMode ?? "approve-all",
|
||||
cursorMode: this.#options.cursorMode,
|
||||
piThinkingLevel: this.#options.piThinkingLevel,
|
||||
providerPolicy: this.#options.providerPolicy,
|
||||
runtimeContext: this.#options.runtimeContext,
|
||||
systemInstructions: this.#options.systemInstructions,
|
||||
@@ -1287,6 +1289,7 @@ class CodexAcpxSession implements HarnessSession {
|
||||
effectiveModel: identity.effectiveModel,
|
||||
permissionMode: identity.permissionMode,
|
||||
...(identity.cursorMode === undefined ? {} : { cursorMode: identity.cursorMode }),
|
||||
...(identity.piThinkingLevel === undefined ? {} : { piThinkingLevel: identity.piThinkingLevel }),
|
||||
providerLifetimeFenceCandidates:
|
||||
identity.providerLifetimeFenceCandidates,
|
||||
},
|
||||
@@ -2149,6 +2152,7 @@ function validateRecoverySnapshot(snapshot: PersistedHarnessSession): void {
|
||||
identity.permissionMode,
|
||||
)) ||
|
||||
(identity.cursorMode !== undefined && !["agent", "plan", "ask"].includes(identity.cursorMode)) ||
|
||||
(identity.piThinkingLevel !== undefined && !["off", "low", "high", "max"].includes(identity.piThinkingLevel)) ||
|
||||
!validProviderLifetimeFenceCandidates(
|
||||
identity.providerLifetimeFenceCandidates,
|
||||
)
|
||||
|
||||
@@ -232,6 +232,14 @@ describe("Codex ACPX runtime adapter", () => {
|
||||
let created!: AcpRuntimeOptions & { onAgentInitialize?: (result: unknown) => void };
|
||||
const options = openOptions(fakeCommand());
|
||||
options.profile = { ...options.profile, agent: "pi" };
|
||||
options.piThinkingLevel = "low";
|
||||
vi.mocked(runtime.setConfigOption).mockImplementation(async input => {
|
||||
const guard = created.protocolGuardFactory!();
|
||||
guard("outbound", { id: 0, method: "session/load", params: { sessionId: "backend-1" } });
|
||||
guard("inbound", { id: 0, result: { modes: { currentModeId: "high" }, configOptions: [{ id: "thought_level", currentValue: "high" }] } });
|
||||
guard("outbound", { id: 1, method: "session/set_config_option", params: { sessionId: "backend-1", configId: input.key, value: input.value } });
|
||||
guard("inbound", { id: 1, result: { configOptions: [{ id: "thought_level", currentValue: "low" }] } });
|
||||
});
|
||||
const port = await openCodexAcpxRuntime(options, {
|
||||
createRegistry: () => registry(), createStore: () => store(),
|
||||
createRuntime: (value) => { created = value; return runtime; },
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createPiThinkingAdmission, resolvePiThinkingLevel } from "./pi-thinking.js";
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
|
||||
import {
|
||||
@@ -301,6 +302,8 @@ export async function openQualifiedAcpxRuntime(
|
||||
);
|
||||
};
|
||||
const commandLaunches = { count: 0, refreshConsumedCommand: options.refreshConsumedCommand };
|
||||
const selectedPiThinkingLevel = resolvePiThinkingLevel(options.profile.agent, options.piThinkingLevel);
|
||||
const piThinking = selectedPiThinkingLevel ? createPiThinkingAdmission(selectedPiThinkingLevel, { restoring: options.restoringSession }) : null;
|
||||
const selectedCursorMode = resolveCursorSessionMode(options.profile.agent, options.cursorMode);
|
||||
const cursorMode = selectedCursorMode ? createCursorModeAdmission(selectedCursorMode) : null;
|
||||
const cursorInstructions = options.profile.agent === "cursor"
|
||||
@@ -313,6 +316,7 @@ export async function openQualifiedAcpxRuntime(
|
||||
const mode = cursorMode.createGuard();
|
||||
return (direction: "inbound" | "outbound", message: unknown) => { instructions(direction, message); mode(direction, message); };
|
||||
} } : {}),
|
||||
...(piThinking ? { protocolGuardFactory: () => piThinking.createGuard() } : {}),
|
||||
sessionStore,
|
||||
agentRegistry: createRegistry({
|
||||
// Preserve Claude's ACP capability identity. This is metadata only: the
|
||||
@@ -512,6 +516,18 @@ export async function openQualifiedAcpxRuntime(
|
||||
await commandLaunches.refreshConsumedCommand?.();
|
||||
}
|
||||
return ensuredHandle;
|
||||
}) : piThinking ? ensuredSession.then(async (ensuredHandle) => {
|
||||
handle = ensuredHandle;
|
||||
options.signal?.throwIfAborted();
|
||||
if (!piThinking.isReady()) {
|
||||
if (!runtime.setConfigOption) throw new Error("Pi thinking admission requires native configuration");
|
||||
await runtime.setConfigOption({ handle: ensuredHandle, key: "thought_level", value: selectedPiThinkingLevel! });
|
||||
piThinking.assertReady();
|
||||
await children.verifyLifetimeOwnership();
|
||||
options.signal?.throwIfAborted();
|
||||
await commandLaunches.refreshConsumedCommand?.();
|
||||
}
|
||||
return ensuredHandle;
|
||||
}) : ensuredSession)
|
||||
.catch((error: unknown) => {
|
||||
throw classifySessionEnsureFailure(error);
|
||||
@@ -527,6 +543,7 @@ export async function openQualifiedAcpxRuntime(
|
||||
: await boundedHandshake;
|
||||
cursorInstructions?.assertReady();
|
||||
cursorMode?.assertReady();
|
||||
piThinking?.assertReady();
|
||||
// A provider can answer only after the verified sentinel is armed, but do
|
||||
// not admit the session until the owner has observed that exact handoff.
|
||||
await children.verifyLifetimeOwnership();
|
||||
@@ -581,7 +598,7 @@ export async function openQualifiedAcpxRuntime(
|
||||
return runtimePort(
|
||||
runtime,
|
||||
handle,
|
||||
{ ...requireIdentity(handle), ...(selectedCursorMode ? { cursorMode: selectedCursorMode } : {}) },
|
||||
{ ...requireIdentity(handle), ...(selectedCursorMode ? { cursorMode: selectedCursorMode } : {}), ...(selectedPiThinkingLevel ? { piThinkingLevel: selectedPiThinkingLevel } : {}) },
|
||||
baseStore,
|
||||
children,
|
||||
runtimeCloseTimeoutMs,
|
||||
|
||||
@@ -90,6 +90,7 @@ describe("ACPX driver profile", () => {
|
||||
expect(
|
||||
validateAcpxDriverConfig({
|
||||
agent: "pi",
|
||||
piThinkingLevel: "low",
|
||||
model: "openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
}),
|
||||
).toMatchObject({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolvePiThinkingLevel, type PiThinkingLevel } from "./pi-thinking.js";
|
||||
import type {
|
||||
HarnessDriverConfigValidation,
|
||||
HarnessDriverDescriptor,
|
||||
@@ -21,12 +22,13 @@ const ACPX_PERMISSION_MODES = [
|
||||
"approve-reads",
|
||||
"deny-all",
|
||||
] as const;
|
||||
const ACPX_CONFIG_FIELDS = new Set(["agent", "model", "permissionMode"]);
|
||||
const ACPX_CONFIG_FIELDS = new Set(["agent", "model", "permissionMode", "piThinkingLevel"]);
|
||||
|
||||
export interface ValidatedAcpxDriverConfig extends Record<string, unknown> {
|
||||
agent: QualifiedAcpxAgent;
|
||||
model: string;
|
||||
permissionMode: NativeAcpxPermissionMode;
|
||||
piThinkingLevel?: PiThinkingLevel;
|
||||
}
|
||||
|
||||
export function acpxCapabilities(
|
||||
@@ -128,10 +130,13 @@ export function validateAcpxDriverConfig(
|
||||
);
|
||||
}
|
||||
|
||||
let piThinkingLevel: PiThinkingLevel | undefined;
|
||||
try { piThinkingLevel = resolvePiThinkingLevel(agent, config.piThinkingLevel); } catch (error) { return invalid("piThinkingLevel", "invalid_pi_thinking_level", safeErrorMessage(error)); }
|
||||
const validated: ValidatedAcpxDriverConfig = {
|
||||
agent,
|
||||
model,
|
||||
permissionMode,
|
||||
...(piThinkingLevel === undefined ? {} : { piThinkingLevel }),
|
||||
};
|
||||
return { ok: true, config: validated, issues: [] };
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* three pins. Never accept a digest supplied only by an installed manifest.
|
||||
*/
|
||||
export const PI_DISTRIBUTION_CLOSURE_SHA256 = Object.freeze({
|
||||
"darwin-arm64": "e17be4d27c589b8f8b5de7d00686c39873fe6f902a3f133bdaf1a9f94dee00a2",
|
||||
"darwin-x64": "03351f4a250a8db0e79411a9079b43a0ff05f72a2aff41fae17f1fc2de24bd41",
|
||||
"linux-x64": "29dfc829700c57392f1d56373078dcfc80674cbd50f65674ec64fced81dffb68",
|
||||
"darwin-arm64": "f6538a35e08f1c1816e738277a1843acfa1ce4522bbaa3340dbddd859dc7dd04",
|
||||
"darwin-x64": "4728e5a4e7fc1ba602c3e219824fb84884b05a06cdd19dd3e521ee312e1b373a",
|
||||
"linux-x64": "2957c0ec20ca1ace64d1a2b10c4a99f47f59e0c5c33a89161c1d5b48341c2b25",
|
||||
});
|
||||
@@ -13,7 +13,7 @@ import { QUALIFIED_ACPX_PROFILES, type QualifiedAcpxProfile } from "./qualified-
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => { vi.unstubAllEnvs(); await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });
|
||||
const candidate = (): QualifiedAcpxProfile => ({ ...QUALIFIED_ACPX_PROFILES.pi, agentProfileVersion: 12 });
|
||||
const candidate = (): QualifiedAcpxProfile => ({ ...QUALIFIED_ACPX_PROFILES.pi, agentProfileVersion: 13 });
|
||||
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(join(tmpdir(), "pi-installation-test-")); roots.push(root);
|
||||
@@ -30,7 +30,7 @@ describe("Pi installation factory", () => {
|
||||
const hash = (bytes: string | Uint8Array) => createHash("sha256").update(bytes).digest("hex");
|
||||
const canonical = (value: any): string => Array.isArray(value) ? `[${value.map(canonical).join(",")}]`
|
||||
: value && typeof value === "object" ? `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}` : JSON.stringify(value);
|
||||
const identity = JSON.parse(await readFile(new URL("../../../test-fixtures/pi-acp/profile-v12-identity.json", import.meta.url), "utf8"));
|
||||
const identity = JSON.parse(await readFile(new URL("../../../test-fixtures/pi-acp/profile-v13-identity.json", import.meta.url), "utf8"));
|
||||
const declaration = identity.declaration;
|
||||
expect(declaration.sharedRuntimeContract).toBe("paperclip.acpx-runtime-contract.v1");
|
||||
expect(identity.commandDigest).toBe(`sha256:${hash(canonical(declaration))}`);
|
||||
@@ -52,22 +52,23 @@ describe("Pi installation factory", () => {
|
||||
expect(materializer).toContain(`helperSha256: "${declaration.helperSha256}"`);
|
||||
// This exact patch produced the reviewed current wrapper/closure.
|
||||
// Pin it separately so wrapper-only edits cannot keep an unchanged declaration.
|
||||
expect(hash(await readFile(new URL("../../../../../patches/pi-acp@0.0.33.patch", import.meta.url)))).toBe("93254de82ae779587611748cfb963475c3439e033f1582f06dfdcc7f7b937546");
|
||||
expect(hash(await readFile(new URL("../../../../../patches/pi-acp@0.0.33.patch", import.meta.url)))).toBe("8b3dbb7e08c6c356e81624b9afcab13827269579cef085db15fdec0ef72aedb3");
|
||||
});
|
||||
|
||||
it("rejects legacy profiles and caller-selected identities", () => {
|
||||
expect(() => assertPiInstallationProfile(candidate())).not.toThrow();
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 1 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 2 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 3 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 4 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 5 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 6 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 7 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 8 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 9 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 10 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 11 })).toThrow("version 12");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 1 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 2 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 3 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 4 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 5 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 6 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 7 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 8 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 9 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 10 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 11 })).toThrow("version 13");
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 12 })).toThrow("version 13");
|
||||
for (const changed of [{ agentServerVersion: "latest" }, { commandDigest: `sha256:${"0".repeat(64)}` }, { reportedModelId: "different" }, { agentRuntimePackage: "ambient-pi" }]) {
|
||||
expect(() => assertPiInstallationProfile({ ...candidate(), ...changed })).toThrow("trusted declaration");
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ function record(value: unknown): Record<string, unknown> {
|
||||
/** Candidate identity is build-owned; model selection cannot substitute a CLI. */
|
||||
export function assertPiInstallationProfile(profile: QualifiedAcpxProfile): void {
|
||||
const trusted = QUALIFIED_ACPX_PROFILES.pi;
|
||||
if (profile.agentProfileVersion !== 12) throw new Error("Pi rich ACP requires profile version 12; reopen the previous session");
|
||||
if (profile.agentProfileVersion !== 13) throw new Error("Pi rich ACP requires profile version 13; reopen the previous session");
|
||||
if (profile.agent !== "pi" || profile.driverKind !== trusted.driverKind || profile.protocolVersion !== trusted.protocolVersion || profile.acpxVersion !== trusted.acpxVersion || profile.agentServerPackage !== "pi-acp" || profile.agentServerVersion !== "0.0.33" || profile.agentRuntimePackage !== "@earendil-works/pi-coding-agent" || profile.agentRuntimeVersion !== "1.0.0" || profile.commandDigest !== trusted.commandDigest || profile.permissionPolicy !== "interactive" || profile.qualificationModel !== PI_MODEL || profile.reportedModelId !== PI_MODEL) throw new Error("Pi distribution profile differs from its trusted declaration");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { admittedPiThinkingLevel, createPiThinkingAdmission, resolvePiThinkingLevel } from "./pi-thinking.js";
|
||||
|
||||
const config = (mode: string) => [{ id: "thought_level", type: "select", currentValue: mode, options: ["high", "low", "max"].map(value => ({ value, name: value })) }];
|
||||
const session = (mode: string) => ({ sessionId: "native", modes: { currentModeId: mode }, configOptions: config(mode) });
|
||||
const prompt = { id: 9, method: "session/prompt", params: { sessionId: "native" } };
|
||||
function opened(expected: "off" | "low" | "high" | "max", initial: string = expected) {
|
||||
const admission = createPiThinkingAdmission(expected); const guard = admission.createGuard();
|
||||
guard("outbound", { id: 0, method: "session/new", params: {} });
|
||||
guard("inbound", { id: 0, result: session(initial) });
|
||||
if (initial === expected) {
|
||||
guard("outbound", { id: 100, method: "session/set_config_option", params: { sessionId: "native", configId: "thought_level", value: expected } });
|
||||
guard("inbound", { id: 100, result: { configOptions: config(expected) } });
|
||||
}
|
||||
return { admission, guard };
|
||||
}
|
||||
|
||||
describe("Pi thinking native mode admission", () => {
|
||||
it("requires explicit Pi thinking and rejects unadmitted aliases and other providers", () => {
|
||||
expect(() => resolvePiThinkingLevel("pi", undefined)).toThrow(/explicit/);
|
||||
expect(resolvePiThinkingLevel("codex", undefined)).toBeUndefined();
|
||||
for (const mode of ["code", "architect", "search", "chat", "", null]) expect(() => resolvePiThinkingLevel("pi", mode)).toThrow();
|
||||
expect(() => resolvePiThinkingLevel("cursor", "high")).toThrow(/only supported/);
|
||||
});
|
||||
it.each(["off", "low", "high", "max"] as const)("admits %s only after correlated native acknowledgements", expected => {
|
||||
const { admission, guard } = opened(expected);
|
||||
admission.assertReady(); guard("outbound", prompt);
|
||||
const reloaded = admission.createGuard();
|
||||
expect(admission.assertReady).toThrow();
|
||||
expect(() => guard("outbound", prompt)).toThrow(/replaced/);
|
||||
reloaded("outbound", { id: 1, method: "session/load", params: { sessionId: "native" } });
|
||||
reloaded("inbound", { id: 1, result: session(expected) });
|
||||
admission.assertReady(); reloaded("outbound", prompt);
|
||||
});
|
||||
it.each(["medium", "high"])("allows initial %s/model-selection updates but requires a correlated low setter before prompting", initial => {
|
||||
const { admission, guard } = opened("low", initial);
|
||||
guard("inbound", { method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "current_mode_update", currentModeId: "high" } } });
|
||||
guard("inbound", { method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "config_option_update", configOptions: config("high") } } });
|
||||
expect(admission.isReady()).toBe(false);
|
||||
guard("outbound", { id: 2, method: "session/set_config_option", params: { sessionId: "native", configId: "thought_level", value: "low" } });
|
||||
guard("inbound", { method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "current_mode_update", currentModeId: "low" } } });
|
||||
expect(admission.isReady()).toBe(false);
|
||||
guard("inbound", { id: 2, result: { configOptions: config("low") } });
|
||||
admission.assertReady(); guard("outbound", prompt);
|
||||
});
|
||||
it("never admits from an initial matching mode before the explicit setter", () => {
|
||||
const admission = createPiThinkingAdmission("low"); const guard = admission.createGuard();
|
||||
guard("outbound", { id: 0, method: "session/new", params: {} });
|
||||
guard("inbound", { id: 0, result: session("low") });
|
||||
expect(() => guard("outbound", prompt)).toThrow(/admission/);
|
||||
});
|
||||
it("permits explicit initial configuration and does not use an update as its acknowledgement", () => {
|
||||
const { admission, guard } = opened("low", "high");
|
||||
expect(admission.isReady()).toBe(false);
|
||||
guard("outbound", { id: 2, method: "session/set_config_option", params: { sessionId: "native", configId: "thought_level", value: "low" } });
|
||||
guard("inbound", { method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "current_mode_update", currentModeId: "low" } } });
|
||||
expect(admission.isReady()).toBe(false);
|
||||
guard("inbound", { id: 2, result: { configOptions: config("low") } });
|
||||
admission.assertReady(); guard("outbound", prompt);
|
||||
});
|
||||
it.each(["missing", "conflicting", "wrong"])("gates a reloaded prompt with %s mode acknowledgement", kind => {
|
||||
const { admission } = opened("low"); const guard = admission.createGuard();
|
||||
guard("outbound", { id: 2, method: "session/load", params: { sessionId: "native" } });
|
||||
const result = kind === "missing" ? {} : kind === "conflicting" ? { ...session("low"), modes: { currentModeId: "max" } } : session("high");
|
||||
expect(() => guard("inbound", { id: 2, result })).toThrow(/mode admission/);
|
||||
expect(() => guard("outbound", prompt)).toThrow(/mode admission/);
|
||||
});
|
||||
it.each([false, true])("cannot repair incompatible restored mode with a later setter, cold restoration=%s", cold => {
|
||||
const admission = cold ? createPiThinkingAdmission("low", { restoring: true }) : opened("low").admission;
|
||||
const guard = admission.createGuard();
|
||||
guard("outbound", { id: 2, method: "session/load", params: { sessionId: "native" } });
|
||||
expect(() => guard("inbound", { id: 2, result: session("high") })).toThrow(/drifted/);
|
||||
expect(() => guard("outbound", { id: 3, method: "session/set_config_option", params: { sessionId: "native", configId: "thought_level", value: "low" } })).toThrow(/drifted/);
|
||||
expect(() => guard("outbound", prompt)).toThrow(/drifted/);
|
||||
});
|
||||
it("rejects overlapping configuration controls so one ACK cannot admit another pending mutation", () => {
|
||||
const { guard, admission } = opened("low");
|
||||
guard("outbound", { id: 4, method: "session/set_config_option", params: { sessionId: "native", configId: "model", value: "qualified" } });
|
||||
expect(() => guard("outbound", { id: 5, method: "session/set_config_option", params: { sessionId: "native", configId: "thought_level", value: "low" } })).toThrow(/overlapping/);
|
||||
expect(() => guard("inbound", { id: 4, result: { configOptions: config("low") } })).toThrow(/overlapping/);
|
||||
expect(admission.assertReady).toThrow(/overlapping/);
|
||||
});
|
||||
it("blocks prompts while admitted configuration is pending and restores only from its exact ACK", () => {
|
||||
const pending = opened("low");
|
||||
pending.guard("outbound", { id: 4, method: "session/set_config_option", params: { sessionId: "native", configId: "model", value: "qualified" } });
|
||||
expect(pending.admission.isReady()).toBe(false);
|
||||
expect(() => pending.guard("outbound", prompt)).toThrow(/admission/);
|
||||
const awaited = opened("low");
|
||||
awaited.guard("outbound", { id: 4, method: "session/set_config_option", params: { sessionId: "native", configId: "model", value: "qualified" } });
|
||||
awaited.guard("inbound", { id: 4, result: { configOptions: config("low") } });
|
||||
awaited.guard("outbound", prompt);
|
||||
});
|
||||
it("rejects late mode drift and keeps the connection failed closed", () => {
|
||||
const { admission, guard } = opened("low");
|
||||
expect(() => guard("inbound", { method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "current_mode_update", currentModeId: "high" } } })).toThrow(/drifted/);
|
||||
expect(admission.assertReady).toThrow(/drifted/);
|
||||
expect(() => guard("outbound", prompt)).toThrow(/drifted/);
|
||||
});
|
||||
it("rejects wrong config echoes, uncorrelated acknowledgements and cross-session control", () => {
|
||||
const forged = createPiThinkingAdmission("low"); const g = forged.createGuard();
|
||||
g("inbound", { id: 2, result: session("low") }); expect(forged.assertReady).toThrow();
|
||||
const { guard } = opened("low", "high");
|
||||
guard("outbound", { id: 2, method: "session/set_config_option", params: { sessionId: "native", configId: "thought_level", value: "low" } });
|
||||
expect(() => guard("inbound", { id: 2, result: { configOptions: config("high") } })).toThrow(/did not apply/);
|
||||
const other = opened("low").guard;
|
||||
expect(() => other("outbound", { id: 3, method: "session/set_config_option", params: { sessionId: "other", configId: "thought_level", value: "low" } })).toThrow(/different session/);
|
||||
});
|
||||
it.each([false, true])("rejects config-option mode drift with active prompt=%s", active => {
|
||||
const { admission, guard } = opened("low");
|
||||
if (active) guard("outbound", prompt);
|
||||
expect(() => guard("inbound", { method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "config_option_update", configOptions: config("high") } } })).toThrow(/drifted/);
|
||||
expect(admission.assertReady).toThrow(/drifted/);
|
||||
});
|
||||
it.each(["foreign", "duplicate", "invalid"])("rejects %s mode configuration notifications", kind => {
|
||||
const { guard } = opened("low");
|
||||
const options = kind === "duplicate" ? [...config("low"), ...config("low")] : config(kind === "invalid" ? "architect" : "low");
|
||||
expect(() => guard("inbound", { method: "session/update", params: { sessionId: kind === "foreign" ? "other" : "native", update: { sessionUpdate: "config_option_update", configOptions: options } } })).toThrow(/mode admission/);
|
||||
});
|
||||
it("ignores model-only partial updates and cannot admit from a mode notification", () => {
|
||||
const { admission, guard } = opened("low", "high");
|
||||
for (const options of [[{ id: "model", currentValue: "fixture" }], config("low")]) {
|
||||
guard("inbound", { method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "config_option_update", configOptions: options } } });
|
||||
expect(admission.isReady()).toBe(false);
|
||||
}
|
||||
});
|
||||
it("does not mistake a bare set_mode response for configuration proof", () => {
|
||||
const { admission, guard } = opened("low", "high");
|
||||
guard("outbound", { id: 4, method: "session/set_mode", params: { sessionId: "native", modeId: "low" } });
|
||||
guard("inbound", { id: 4, result: {} }); expect(admission.assertReady).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// Real ACPX manager/SDK transport, deterministic local child (not the real Pi
|
||||
// model). The separate pinned-Pi package contract proves its effective wire.
|
||||
it.each(["valid", "wrong-echo", "unsupported"])("actual ACPX initial model selection then low admission: %s", async behavior => {
|
||||
const { spawn } = await import("node:child_process");
|
||||
const { mkdtemp, rm } = await import("node:fs/promises");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const { createAcpRuntime, createAgentRegistry, createRuntimeStore } = await import("acpx/runtime");
|
||||
const root = await mkdtemp(join(tmpdir(), "pi-thinking-wire-"));
|
||||
const children: Array<{ child: ReturnType<typeof spawn>; closed: Promise<void> }> = [];
|
||||
const methods: string[] = [];
|
||||
const admission = createPiThinkingAdmission("low");
|
||||
const peer = String.raw`
|
||||
let mode='medium';
|
||||
const send=x=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\n');
|
||||
const configs=()=>[{id:'thought_level',name:'Thinking',type:'select',currentValue:mode,options:['off','low','medium','high','max'].map(value=>({value,name:value}))},{id:'model',name:'Model',type:'select',currentValue:'qualified',options:[{value:'qualified',name:'Qualified'}]}];
|
||||
require('node:readline').createInterface({input:process.stdin}).on('line',line=>{
|
||||
const m=JSON.parse(line);
|
||||
if(m.method==='initialize')send({id:m.id,result:{protocolVersion:1,agentCapabilities:{loadSession:true},authMethods:[]}});
|
||||
else if(m.method==='session/new'||m.method==='session/load')send({id:m.id,result:{sessionId:'native',modes:{currentModeId:mode,availableModes:['off','low','medium','high','max'].map(id=>({id,name:id}))},configOptions:configs()}});
|
||||
else if(m.method==='session/set_config_option'){
|
||||
if(m.params.configId==='model')mode='high';
|
||||
else if(m.params.configId==='thought_level'){
|
||||
if(process.env.BEHAVIOR==='unsupported')return send({id:m.id,error:{code:-32602,message:'Unsupported level'}});
|
||||
if(process.env.BEHAVIOR!=='wrong-echo')mode=m.params.value;
|
||||
}
|
||||
send({method:'session/update',params:{sessionId:'native',update:{sessionUpdate:'current_mode_update',currentModeId:mode}}});
|
||||
send({method:'session/update',params:{sessionId:'native',update:{sessionUpdate:'config_option_update',configOptions:configs()}}});
|
||||
send({id:m.id,result:{configOptions:configs()}});
|
||||
}
|
||||
else if(m.method==='session/prompt')send({id:m.id,result:{stopReason:'end_turn'}});
|
||||
});`;
|
||||
const runtime = createAcpRuntime({ cwd: root, agentRegistry: createAgentRegistry({ overrides: { pi: "fixture" } }), sessionStore: createRuntimeStore({ stateDir: join(root, "state") }), permissionMode: "deny-all",
|
||||
protocolGuardFactory: () => admission.createGuard(),
|
||||
onAcpMessage: (direction, value) => { if (direction === "outbound") methods.push((value as { method: string }).method); },
|
||||
spawnAgent: () => {
|
||||
const child = spawn(process.execPath, ["-e", peer], { cwd: root, env: { BEHAVIOR: behavior }, stdio: ["pipe", "pipe", "pipe"] });
|
||||
const closed = new Promise<void>(resolve => child.once("close", () => resolve()));
|
||||
child.on("error", () => {}); children.push({ child, closed }); return child;
|
||||
},
|
||||
});
|
||||
let handle;
|
||||
try {
|
||||
handle = await runtime.ensureSession({ sessionKey: "pi-mode", agent: "pi", mode: "persistent", cwd: root, sessionOptions: { model: "qualified" } });
|
||||
expect(admission.isReady()).toBe(false);
|
||||
await runtime.setConfigOption({ handle, key: "model", value: "qualified" });
|
||||
expect(admission.isReady()).toBe(false);
|
||||
const selecting = runtime.setConfigOption({ handle, key: "thought_level", value: "low" });
|
||||
if (behavior !== "valid") { await expect(selecting).rejects.toThrow(); expect(methods).not.toContain("session/prompt"); return; }
|
||||
await selecting; admission.assertReady();
|
||||
const turn = runtime.startTurn({ handle, text: "fixture", mode: "prompt", requestId: "once", timeoutMs: 2000 });
|
||||
const drain = (async () => { for await (const _event of turn.events) { /* drain */ } })();
|
||||
expect((await turn.result).status).toBe("completed"); await drain;
|
||||
expect(methods.filter(method => method === "session/prompt")).toHaveLength(1);
|
||||
expect(methods.filter(method => method === "session/set_config_option")).toHaveLength(2);
|
||||
} finally {
|
||||
try { if (handle) await runtime.close({ handle, reason: "fixture cleanup" }); }
|
||||
finally {
|
||||
for (const { child } of children) if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
|
||||
await Promise.allSettled(children.map(({ closed }) => closed));
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("publishes only independently matching observed Pi mode, never the requested value alone", () => {
|
||||
expect(admittedPiThinkingLevel("pi", "low", { piThinkingLevel: "low" }, { piThinkingLevel: "low" })).toBe("low");
|
||||
for (const observed of [undefined, "high", "medium", null]) {
|
||||
expect(() => admittedPiThinkingLevel("pi", "low", { piThinkingLevel: "low" }, { piThinkingLevel: observed })).toThrow();
|
||||
expect(() => admittedPiThinkingLevel("pi", "low", { piThinkingLevel: observed }, { piThinkingLevel: "low" })).toThrow();
|
||||
}
|
||||
expect(admittedPiThinkingLevel("codex", undefined, {}, {})).toBeUndefined();
|
||||
expect(() => admittedPiThinkingLevel("codex", undefined, {}, { piThinkingLevel: "low" })).toThrow();
|
||||
});
|
||||
|
||||
it("preserves effective Pi mode through the persisted harness identity projection", async () => {
|
||||
const { parseProviderIdentity } = await import("../codex/codex-driver-values.js");
|
||||
const value = { kind: "acpx", normalizedSessionId: "session", acpxRecordId: "record", backendSessionId: "backend", agentSessionId: "agent", profileDigest: "sha256:profile", workspaceDigest: "sha256:workspace", requestedModel: "model", effectiveModel: "model", piThinkingLevel: "low", providerLifetimeFenceCandidates: [60001, 60002, 60003] };
|
||||
expect(parseProviderIdentity(value)).toMatchObject({ piThinkingLevel: "low" });
|
||||
expect(() => parseProviderIdentity({ ...value, piThinkingLevel: "medium" })).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
export type PiThinkingLevel = "off" | "low" | "high" | "max";
|
||||
|
||||
export function resolvePiThinkingLevel(agent: string, mode: unknown): PiThinkingLevel | undefined {
|
||||
if (agent !== "pi") {
|
||||
if (mode !== undefined) throw new Error("Pi thinking level is only supported by Pi");
|
||||
return undefined;
|
||||
}
|
||||
if (mode === undefined) throw new Error("Pi thinking level must be explicit");
|
||||
if (mode !== "off" && mode !== "low" && mode !== "high" && mode !== "max") throw new Error("Invalid Pi thinking level");
|
||||
return mode;
|
||||
}
|
||||
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
/** Native mode is independent of permissions. Every connection must prove its
|
||||
* current mode before a prompt; a persisted ACPX preference is not proof. */
|
||||
export function createPiThinkingAdmission(expected: PiThinkingLevel, options: { restoring?: boolean } = {}) {
|
||||
type State = { sessionId: string | null; mode: string | null; error: Error | null };
|
||||
let current: State | null = null;
|
||||
let selectedOnce = options.restoring === true;
|
||||
const failure = (detail: string) => new Error(`Pi thinking mode admission failed: ${detail}`);
|
||||
const assertReady = () => {
|
||||
if (current?.error) throw current.error;
|
||||
if (!selectedOnce || !current?.sessionId || current.mode !== expected) throw failure("native mode does not acknowledge the selected mode");
|
||||
};
|
||||
const readMode = (result: Record<string, unknown>, session: boolean): string => {
|
||||
const configs = Array.isArray(result.configOptions) ? result.configOptions.filter(value => object(value).id === "thought_level") : [];
|
||||
if (configs.length !== 1) throw failure("native mode configuration is missing or ambiguous");
|
||||
const mode = object(configs[0]).currentValue;
|
||||
// Before exact model selection, Pi can legitimately report a different
|
||||
// native model's level. Observation alone never admits the first prompt.
|
||||
if (typeof mode !== "string" || !["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(mode)) throw failure("native mode is unsupported");
|
||||
if (session && object(result.modes).currentModeId !== mode) throw failure("native mode acknowledgements conflict");
|
||||
return mode;
|
||||
};
|
||||
return {
|
||||
assertReady,
|
||||
isReady() { assertNoError(); return selectedOnce && current?.sessionId != null && current.mode === expected; },
|
||||
createGuard() {
|
||||
const state: State = { sessionId: null, mode: null, error: null };
|
||||
current = state;
|
||||
const pending = new Map<string | number, { method: string; sessionId: unknown; selectsMode: boolean }>();
|
||||
return (direction: "inbound" | "outbound", value: unknown): void => {
|
||||
if (current !== state) throw failure("connection authority was replaced");
|
||||
assertNoError();
|
||||
const message = object(value);
|
||||
const params = object(message.params);
|
||||
try {
|
||||
if (direction === "outbound") {
|
||||
const method = message.method;
|
||||
if (method === "session/prompt") {
|
||||
assertReady();
|
||||
if (params.sessionId !== state.sessionId) throw failure("prompt belongs to a different session");
|
||||
} else if (method === "session/new" || method === "session/load" || method === "session/set_config_option") {
|
||||
if (typeof message.id !== "string" && typeof message.id !== "number") throw failure("uncorrelated mode request");
|
||||
if (pending.has(message.id)) throw failure("duplicate mode request identity");
|
||||
if (pending.size) throw failure("overlapping native admission controls");
|
||||
if (method === "session/new" || method === "session/load") {
|
||||
if (pending.size) throw failure("overlapping session admission");
|
||||
state.sessionId = null; state.mode = null;
|
||||
} else {
|
||||
if (!state.sessionId || params.sessionId !== state.sessionId) throw failure("configuration belongs to a different session");
|
||||
if (params.configId === "thought_level" && params.value !== expected) throw failure("configuration changes the selected mode");
|
||||
state.mode = null; // No prompt may race unacknowledged native configuration.
|
||||
}
|
||||
pending.set(message.id, { method, sessionId: params.sessionId, selectsMode: params.configId === "thought_level" });
|
||||
} else if (method === "session/set_mode") {
|
||||
if (!state.sessionId || params.sessionId !== state.sessionId || params.modeId !== expected) throw failure("mode control changes the selected mode");
|
||||
// This method only returns {}; require a later config/session
|
||||
// acknowledgement rather than treating that empty result as proof.
|
||||
state.mode = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/update" && object(params.update).sessionUpdate === "config_option_update") {
|
||||
const update = object(params.update);
|
||||
// Config updates may contain only model options. A mode entry is
|
||||
// authoritative observation, but never an admission acknowledgement.
|
||||
if (Array.isArray(update.configOptions) && update.configOptions.some(value => object(value).id === "thought_level")) {
|
||||
if (state.sessionId && params.sessionId !== state.sessionId) throw failure("mode update belongs to a different session");
|
||||
const observed = readMode(update, false);
|
||||
if (selectedOnce && observed !== expected) throw failure("native mode drifted from the selected mode");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/update" && object(params.update).sessionUpdate === "current_mode_update") {
|
||||
if (state.sessionId && params.sessionId !== state.sessionId) throw failure("mode update belongs to a different session");
|
||||
if (selectedOnce && object(params.update).currentModeId !== expected) throw failure("native mode drifted from the selected mode");
|
||||
return; // Notifications alone never admit a prompt.
|
||||
}
|
||||
if (message.method !== undefined || (typeof message.id !== "string" && typeof message.id !== "number")) return;
|
||||
const request = pending.get(message.id);
|
||||
if (!request) return;
|
||||
pending.delete(message.id);
|
||||
if (message.error !== undefined) { state.mode = null; return; }
|
||||
const result = object(message.result);
|
||||
const session = request.method !== "session/set_config_option";
|
||||
const sessionId = request.method === "session/new" ? result.sessionId : request.sessionId;
|
||||
if (typeof sessionId !== "string" || !sessionId.trim()) throw failure("mode acknowledgement has no session identity");
|
||||
const mode = readMode(result, session);
|
||||
if (session && selectedOnce && mode !== expected) throw failure("restored native mode drifted from the selected mode");
|
||||
if (!session && (request.selectsMode || selectedOnce) && mode !== expected) throw failure("configuration did not apply the selected mode");
|
||||
if (!session && request.selectsMode) selectedOnce = true;
|
||||
state.sessionId = sessionId; state.mode = mode;
|
||||
} catch (error) {
|
||||
state.error = error instanceof Error ? error : failure("invalid mode acknowledgement");
|
||||
throw state.error;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
function assertNoError() { if (current?.error) throw current.error; }
|
||||
}
|
||||
|
||||
/** Cross-check independently returned durable identity and public descriptor. */
|
||||
export function admittedPiThinkingLevel(agent: string, requested: unknown, descriptor: unknown, identity: unknown): PiThinkingLevel | undefined {
|
||||
const expected = resolvePiThinkingLevel(agent, requested);
|
||||
const reported = object(identity).piThinkingLevel;
|
||||
const projected = object(descriptor).piThinkingLevel;
|
||||
if (agent !== "pi") {
|
||||
if (reported !== undefined || projected !== undefined) throw new Error("Non-Pi identity contains a Pi thinking level");
|
||||
return undefined;
|
||||
}
|
||||
const effective = resolvePiThinkingLevel("pi", reported);
|
||||
if (effective !== expected || projected !== effective) throw new Error("Pi effective thinking level differs from the admitted configuration");
|
||||
return effective;
|
||||
}
|
||||
@@ -47,13 +47,13 @@ export const QUALIFIED_ACPX_PROFILES: Readonly<
|
||||
protocolVersion: ACPX_DRIVER_PROTOCOL_VERSION,
|
||||
acpxVersion: QUALIFIED_ACPX_VERSION,
|
||||
agent: "pi",
|
||||
agentProfileVersion: 12,
|
||||
agentProfileVersion: 13,
|
||||
agentServerPackage: "pi-acp",
|
||||
agentServerVersion: "0.0.33",
|
||||
agentRuntimePackage: "@earendil-works/pi-coding-agent",
|
||||
agentRuntimeVersion: "1.0.0",
|
||||
commandDigest:
|
||||
"sha256:47306e6d2a9b59e8f9189f725ebb7a0a7f91826044d1739e1a35ab31f228ba1f",
|
||||
"sha256:fe1e6da01b2a9e4c691ca27cf689d2d6de846a93be6b23fc1e103c9addd7b177",
|
||||
qualificationModel: "openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
reportedModelId: "openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
permissionPolicy: "interactive",
|
||||
|
||||
@@ -40,13 +40,13 @@ describe("ACPX recovery identity", () => {
|
||||
const fixture = await recoveryFixture();
|
||||
const historical = JSON.parse(await readFile(new URL(path, import.meta.url), "utf8"));
|
||||
const current = resolveQualifiedAcpxProfile(agent, agent === "pi" ? "openrouter/deepseek/deepseek-v4-flash-0731" : fixture.input.requestedModel);
|
||||
const input = { ...fixture.input, requestedModel: current.qualificationModel, profile: current };
|
||||
const input = { ...fixture.input, requestedModel: current.qualificationModel, profile: current, ...(agent === "pi" ? { piThinkingLevel: "low" as const } : {}) };
|
||||
const next = await createAcpxRecoveryBinding(input);
|
||||
const prior = await createAcpxRecoveryBinding({ ...input, profile: { ...current,
|
||||
agentProfileVersion: historical.declaration.agentProfileVersion, commandDigest: historical.commandDigest } });
|
||||
const priorExpected = { ...fixture.expected, profileDigest: prior.commandDigest,
|
||||
requestedModel: prior.requestedModel, effectiveModel: prior.effectiveModel,
|
||||
...(agent === "cursor" ? { cursorMode: "agent" as const } : {}) };
|
||||
...(agent === "cursor" ? { cursorMode: "agent" as const } : {}), ...(agent === "pi" ? { piThinkingLevel: "low" as const } : {}) };
|
||||
const record = createAcpxIdentityRecord(priorExpected, prior);
|
||||
expect(next.profileDigest).not.toBe(prior.profileDigest);
|
||||
expect(next.profileSessionKey).not.toBe(prior.profileSessionKey);
|
||||
@@ -69,6 +69,22 @@ describe("ACPX recovery identity", () => {
|
||||
await expect(createAcpxRecoveryBinding({ ...fixture.input, cursorMode: "plan" })).rejects.toThrow(/only supported/);
|
||||
});
|
||||
|
||||
it("binds Pi thinking mode and rejects old or mismatched warm identities", async () => {
|
||||
const fixture = await recoveryFixture();
|
||||
const profile = resolveQualifiedAcpxProfile("pi", "openrouter/deepseek/deepseek-v4-flash-0731");
|
||||
const input = { ...fixture.input, profile, requestedModel: profile.qualificationModel, piThinkingLevel: "low" as const };
|
||||
const low = await createAcpxRecoveryBinding(input);
|
||||
const high = await createAcpxRecoveryBinding({ ...input, piThinkingLevel: "high" });
|
||||
expect(low.profileSessionKey).not.toBe(high.profileSessionKey);
|
||||
const expected = { ...fixture.expected, profileDigest: low.commandDigest, requestedModel: low.requestedModel, effectiveModel: low.effectiveModel, piThinkingLevel: "low" as const };
|
||||
const persisted = createAcpxIdentityRecord(expected, low);
|
||||
expect(acpxProviderSessionIdentity(persisted, low).piThinkingLevel).toBe("low");
|
||||
expect(() => verifyExpectedAcpxIdentity({ ...expected, piThinkingLevel: undefined }, low, persisted)).toThrow(/immutable/);
|
||||
expect(() => verifyExpectedAcpxIdentity(expected, low, { ...persisted, piThinkingLevel: undefined })).toThrow(/persisted/);
|
||||
expect(() => verifyExpectedAcpxIdentity(expected, high, persisted)).toThrow(/immutable/);
|
||||
await expect(createAcpxRecoveryBinding({ ...input, piThinkingLevel: undefined })).rejects.toThrow(/explicit/);
|
||||
});
|
||||
|
||||
it("derives one stable, filesystem-safe runtime directory name", () => {
|
||||
expect(acpxRuntimeSessionDirectoryName("session/1")).toMatch(
|
||||
/^session_1-[0-9a-f]{16}$/,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolvePiThinkingLevel, type PiThinkingLevel } from "./pi-thinking.js";
|
||||
import { resolveCursorSessionMode, type CursorSessionMode } from "./cursor-mode.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { realpath, stat } from "node:fs/promises";
|
||||
@@ -21,6 +22,7 @@ export interface AcpxRecoveryBinding {
|
||||
effectiveModel: string;
|
||||
permissionMode: NativeAcpxPermissionMode;
|
||||
cursorMode?: CursorSessionMode;
|
||||
piThinkingLevel?: PiThinkingLevel;
|
||||
profileSessionKey: string;
|
||||
}
|
||||
|
||||
@@ -36,6 +38,7 @@ export interface AcpxIdentityRecord {
|
||||
effectiveModel: string;
|
||||
permissionMode: NativeAcpxPermissionMode;
|
||||
cursorMode?: CursorSessionMode;
|
||||
piThinkingLevel?: PiThinkingLevel;
|
||||
providerLifetimeFenceCandidates: readonly [number, number, number];
|
||||
}
|
||||
|
||||
@@ -47,10 +50,12 @@ export async function createAcpxRecoveryBinding(input: {
|
||||
requestedModel: string;
|
||||
permissionMode: NativeAcpxPermissionMode;
|
||||
cursorMode?: CursorSessionMode;
|
||||
piThinkingLevel?: PiThinkingLevel;
|
||||
providerPolicy?: { readOnly: boolean; readRoots?: readonly string[]; protectedPaths?: readonly string[] };
|
||||
}): Promise<AcpxRecoveryBinding> {
|
||||
validateIdentity(input.normalizedSessionId, "normalized session");
|
||||
const cursorMode = resolveCursorSessionMode(input.profile.agent, input.cursorMode);
|
||||
const piThinkingLevel = resolvePiThinkingLevel(input.profile.agent, input.piThinkingLevel);
|
||||
if (input.providerPolicy !== undefined && typeof input.providerPolicy.readOnly !== "boolean") throw new Error("ACPX recovery requires a valid task execution policy");
|
||||
if (input.requestedModel !== input.profile.qualificationModel) {
|
||||
throw new Error("ACPX recovery requested an unqualified model");
|
||||
@@ -95,6 +100,7 @@ export async function createAcpxRecoveryBinding(input: {
|
||||
profileDigest,
|
||||
permissionMode: input.permissionMode,
|
||||
...(cursorMode ? { cursorMode } : {}),
|
||||
...(piThinkingLevel ? { piThinkingLevel } : {}),
|
||||
}),
|
||||
).replace("sha256:", "paperclip-");
|
||||
return {
|
||||
@@ -108,6 +114,7 @@ export async function createAcpxRecoveryBinding(input: {
|
||||
effectiveModel: input.requestedModel,
|
||||
permissionMode: input.permissionMode,
|
||||
...(cursorMode ? { cursorMode } : {}),
|
||||
...(piThinkingLevel ? { piThinkingLevel } : {}),
|
||||
profileSessionKey,
|
||||
};
|
||||
}
|
||||
@@ -129,6 +136,7 @@ export function createAcpxIdentityRecord(
|
||||
effectiveModel: binding.effectiveModel,
|
||||
permissionMode: binding.permissionMode,
|
||||
...(binding.cursorMode ? { cursorMode: binding.cursorMode } : {}),
|
||||
...(binding.piThinkingLevel ? { piThinkingLevel: binding.piThinkingLevel } : {}),
|
||||
providerLifetimeFenceCandidates: Object.freeze([
|
||||
...expected.providerLifetimeFenceCandidates,
|
||||
]) as readonly [number, number, number],
|
||||
@@ -155,6 +163,7 @@ export function acpxProviderSessionIdentity(
|
||||
effectiveModel: record.effectiveModel,
|
||||
permissionMode: record.permissionMode,
|
||||
...(record.cursorMode ? { cursorMode: record.cursorMode } : {}),
|
||||
...(record.piThinkingLevel ? { piThinkingLevel: record.piThinkingLevel } : {}),
|
||||
providerLifetimeFenceCandidates: record.providerLifetimeFenceCandidates,
|
||||
};
|
||||
verifyExpectedAcpxIdentity(identity, binding, record);
|
||||
@@ -180,7 +189,8 @@ export function verifyExpectedAcpxIdentity(
|
||||
expected.requestedModel !== binding.requestedModel ||
|
||||
expected.effectiveModel !== binding.effectiveModel ||
|
||||
expected.permissionMode !== binding.permissionMode ||
|
||||
expected.cursorMode !== binding.cursorMode
|
||||
expected.cursorMode !== binding.cursorMode ||
|
||||
expected.piThinkingLevel !== binding.piThinkingLevel
|
||||
) {
|
||||
throw new Error(
|
||||
"ACPX recovery identity conflicts with the immutable session configuration",
|
||||
@@ -200,6 +210,7 @@ export function verifyExpectedAcpxIdentity(
|
||||
record.effectiveModel !== binding.effectiveModel ||
|
||||
record.permissionMode !== binding.permissionMode ||
|
||||
record.cursorMode !== binding.cursorMode ||
|
||||
record.piThinkingLevel !== binding.piThinkingLevel ||
|
||||
!sameFenceCandidates(
|
||||
record.providerLifetimeFenceCandidates,
|
||||
expected.providerLifetimeFenceCandidates,
|
||||
@@ -225,6 +236,7 @@ function parsePersistedRecord(value: unknown): AcpxIdentityRecord {
|
||||
"effectiveModel",
|
||||
"permissionMode",
|
||||
"cursorMode",
|
||||
"piThinkingLevel",
|
||||
"providerLifetimeFenceCandidates",
|
||||
]);
|
||||
return validatedRecord(record);
|
||||
@@ -252,6 +264,7 @@ function validatedRecord(value: Record<string, unknown>): AcpxIdentityRecord {
|
||||
throw new Error("ACPX identity permission mode is invalid");
|
||||
}
|
||||
if (value.cursorMode !== undefined) resolveCursorSessionMode("cursor", value.cursorMode);
|
||||
if (value.piThinkingLevel !== undefined) resolvePiThinkingLevel("pi", value.piThinkingLevel);
|
||||
validateFenceCandidates(value.providerLifetimeFenceCandidates);
|
||||
return value as unknown as AcpxIdentityRecord;
|
||||
}
|
||||
@@ -281,6 +294,7 @@ function validateExpected(expected: AcpxExpectedSessionIdentity): void {
|
||||
throw new Error("Expected ACPX permission mode is invalid");
|
||||
}
|
||||
if (expected.cursorMode !== undefined) resolveCursorSessionMode("cursor", expected.cursorMode);
|
||||
if (expected.piThinkingLevel !== undefined) resolvePiThinkingLevel("pi", expected.piThinkingLevel);
|
||||
validateFenceCandidates(expected.providerLifetimeFenceCandidates);
|
||||
}
|
||||
|
||||
|
||||
@@ -868,9 +868,9 @@ describe("ACPX runtime host", () => {
|
||||
expect(options.launchEnvironment.PAPERCLIP_PI_SYSTEM_INSTRUCTIONS).toBe("Bound instructions");
|
||||
expect(JSON.parse(options.launchEnvironment.PAPERCLIP_PI_READ_ROOTS!)).toEqual([]);
|
||||
expect(options.permissionMode).toBe("approve-all");
|
||||
return runtimePort({ getStatus: async () => ({ models: { currentModelId: model } }) });
|
||||
return runtimePort({ getStatus: async () => ({ models: { currentModelId: model } }), identity: async () => ({ acpxRecordId: "record-1", backendSessionId: "backend-1", agentSessionId: "agent-1", piThinkingLevel: "low" }) });
|
||||
});
|
||||
const options = { ...fixture.options, agent: "pi" as const, model,
|
||||
const options = { ...fixture.options, agent: "pi" as const, model, piThinkingLevel: "low" as const,
|
||||
permissionMode: "approve-all" as const, providerPolicy: { readOnly: true }, systemInstructions: "Bound instructions" };
|
||||
const host = await AcpxRuntimeHost.open(options, fixture.dependencies({
|
||||
verifyInstallation: async () => ({ commandDigest: profile.commandDigest,
|
||||
@@ -887,7 +887,7 @@ describe("ACPX runtime host", () => {
|
||||
const copies = await mkdtemp(join(tmpdir(), "paperclip-agent-copies-"));
|
||||
temporaryDirectories.push(copies);
|
||||
const model = agent === "pi" ? "openrouter/deepseek/deepseek-v4-flash-0731" : "explicit-test-model";
|
||||
const options = { ...fixture.options, agent, model, permissionMode: "approve-all" as const,
|
||||
const options = { ...fixture.options, agent, model, ...(agent === "pi" ? { piThinkingLevel: "low" as const } : {}), permissionMode: "approve-all" as const,
|
||||
providerPolicy: { readOnly: false }, environment: { AGENT_HOME: "/ambient/other-agent", PAPERCLIP_PI_AGENT_HOME: "/ambient/other-agent",
|
||||
...(agent === "pi" ? { OPENROUTER_API_KEY: "test" } : agent === "cursor" ? { CURSOR_API_KEY: "test" } : { COPILOT_GITHUB_TOKEN: "test" }),
|
||||
},
|
||||
@@ -895,7 +895,7 @@ describe("ACPX runtime host", () => {
|
||||
const opened: AcpxRuntimePortOpenOptions[] = [];
|
||||
const dependencies = fixture.dependencies({ openRuntime: async launch => {
|
||||
opened.push(launch);
|
||||
return runtimePort({ getStatus: async () => ({ models: { currentModelId: model } }), identity: async () => ({ acpxRecordId: "record-1", backendSessionId: "backend-1", agentSessionId: "agent-1", ...(agent === "cursor" ? { cursorMode: launch.cursorMode } : {}) }) });
|
||||
return runtimePort({ getStatus: async () => ({ models: { currentModelId: model } }), identity: async () => ({ acpxRecordId: "record-1", backendSessionId: "backend-1", agentSessionId: "agent-1", ...(agent === "cursor" ? { cursorMode: launch.cursorMode } : {}), ...(agent === "pi" ? { piThinkingLevel: launch.piThinkingLevel } : {}) }) });
|
||||
} });
|
||||
// Missing trusted context must not turn ambient values into authority.
|
||||
const withoutCopy = await AcpxRuntimeHost.open(options, dependencies);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolvePiThinkingLevel, type PiThinkingLevel } from "./pi-thinking.js";
|
||||
import { withAcpxTurnCancellation } from "./turn-cancellation.js";
|
||||
import { resolveCursorSessionMode, type CursorSessionMode } from "./cursor-mode.js";
|
||||
import { dirname, join } from "node:path";
|
||||
@@ -80,6 +81,7 @@ const ACPX_ADMISSION_CLEANUP_RESCHEDULE_MS = 1_000;
|
||||
|
||||
export interface AcpxRuntimePortIdentity {
|
||||
cursorMode?: CursorSessionMode;
|
||||
piThinkingLevel?: PiThinkingLevel;
|
||||
acpxRecordId: string;
|
||||
backendSessionId: string;
|
||||
agentSessionId: string;
|
||||
@@ -146,6 +148,8 @@ export interface AcpxRuntimePort {
|
||||
}
|
||||
|
||||
export interface AcpxRuntimePortOpenOptions {
|
||||
/** A durable identity was admitted; restored native mode must already match. */
|
||||
restoringSession?: boolean;
|
||||
/** Ephemeral provider extension metadata; mandatory ACP caps remain host-owned. */
|
||||
clientCapabilities?: Record<string, unknown>;
|
||||
command: VerifiedAcpxCommandLease;
|
||||
@@ -157,6 +161,7 @@ export interface AcpxRuntimePortOpenOptions {
|
||||
providerSessionKey: string;
|
||||
permissionMode: NativeAcpxPermissionMode;
|
||||
cursorMode?: CursorSessionMode;
|
||||
piThinkingLevel?: PiThinkingLevel;
|
||||
permissionPolicy: ReturnType<typeof acpxRuntimePermissionPolicy>;
|
||||
launchEnvironment: Readonly<NodeJS.ProcessEnv>;
|
||||
/** Kernel credential-home quorum inherited by the provider sentinel. */
|
||||
@@ -231,6 +236,7 @@ export interface OpenAcpxRuntimeHostOptions {
|
||||
model: string;
|
||||
permissionMode: NativeAcpxPermissionMode;
|
||||
cursorMode?: CursorSessionMode;
|
||||
piThinkingLevel?: PiThinkingLevel;
|
||||
systemInstructions?: string;
|
||||
runtimeContext?: NativeRuntimeContextSnapshot | null;
|
||||
environment?: NodeJS.ProcessEnv;
|
||||
@@ -341,6 +347,7 @@ export class AcpxRuntimeHost {
|
||||
requestedModel: options.model,
|
||||
permissionMode: options.permissionMode,
|
||||
cursorMode: resolveCursorSessionMode(options.agent, options.cursorMode),
|
||||
piThinkingLevel: resolvePiThinkingLevel(options.agent, options.piThinkingLevel),
|
||||
...(["cursor", "copilot", "pi"].includes(options.agent) && options.providerPolicy !== undefined
|
||||
? { providerPolicy: options.providerPolicy } : {}),
|
||||
}),
|
||||
@@ -568,8 +575,10 @@ export class AcpxRuntimeHost {
|
||||
cwd: binding.workspacePath,
|
||||
stateDirectory: sandbox.stateDirectory,
|
||||
providerSessionKey: binding.profileSessionKey,
|
||||
restoringSession: options.expectedIdentity !== undefined,
|
||||
permissionMode: binding.permissionMode,
|
||||
cursorMode: binding.cursorMode,
|
||||
piThinkingLevel: binding.piThinkingLevel,
|
||||
permissionPolicy: acpxRuntimePermissionPolicy(
|
||||
binding.permissionMode,
|
||||
),
|
||||
@@ -627,6 +636,7 @@ export class AcpxRuntimeHost {
|
||||
),
|
||||
dependencies.retainAdmissionCleanup,
|
||||
);
|
||||
if (runtimeIdentity.piThinkingLevel !== binding.piThinkingLevel) throw new Error("ACPX runtime Pi thinking level conflicts with session binding");
|
||||
if (runtimeIdentity.cursorMode !== binding.cursorMode) {
|
||||
throw new Error("ACPX runtime Cursor mode does not match the admitted session configuration");
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ export interface AcpxSidecarOpenParams {
|
||||
model: string;
|
||||
permissionMode: NativeAcpxPermissionMode;
|
||||
cursorMode?: "agent" | "plan" | "ask";
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
permissionModePinned: boolean;
|
||||
providerPolicy?: { readOnly: boolean };
|
||||
systemInstructions: string;
|
||||
@@ -67,6 +68,7 @@ export interface AcpxExpectedSessionIdentity {
|
||||
effectiveModel: string;
|
||||
permissionMode?: NativeAcpxPermissionMode;
|
||||
cursorMode?: "agent" | "plan" | "ask";
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
providerLifetimeFenceCandidates: readonly [number, number, number];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolvePiThinkingLevel } from "../acpx/pi-thinking.js";
|
||||
import type { PersistedHarnessProviderIdentity } from "../../contracts/harness-driver.js";
|
||||
import type { NativeUserMessage } from "../../contracts/types.js";
|
||||
import {
|
||||
@@ -74,6 +75,7 @@ export function parseProviderIdentity(
|
||||
"ACPX provider identity contains an invalid permission mode",
|
||||
);
|
||||
}
|
||||
const piThinkingLevel = identity.piThinkingLevel === undefined ? undefined : resolvePiThinkingLevel("pi", identity.piThinkingLevel);
|
||||
const cursorMode = identity.cursorMode;
|
||||
if (
|
||||
cursorMode !== undefined &&
|
||||
@@ -109,6 +111,7 @@ export function parseProviderIdentity(
|
||||
effectiveModel: identity.effectiveModel as string,
|
||||
...(permissionMode === undefined ? {} : { permissionMode }),
|
||||
...(cursorMode === undefined ? {} : { cursorMode }),
|
||||
...(piThinkingLevel === undefined ? {} : { piThinkingLevel }),
|
||||
providerLifetimeFenceCandidates: fenceCandidates as [
|
||||
number,
|
||||
number,
|
||||
|
||||
@@ -40,13 +40,13 @@ it.each(["cursor", "copilot"] as const)("requires separately bound evaluation op
|
||||
|
||||
it("admits Pi live sessions without candidate opt-in while preserving the exact profile", async () => {
|
||||
const service = new CapabilityLiveSessionService({ transportFactory: fakeTransportFactory(providerState()) });
|
||||
const session = await service.create({ provider: "acpx", acpxAgent: "pi", requestedModel: "openrouter/deepseek/deepseek-v4-flash-0731" });
|
||||
const session = await service.create({ provider: "acpx", acpxAgent: "pi", piThinkingLevel: "low", requestedModel: "openrouter/deepseek/deepseek-v4-flash-0731" });
|
||||
try {
|
||||
expect(session.snapshot().config.acpxProfile).toMatchObject({
|
||||
agent: "pi", agentProfileVersion: 12,
|
||||
commandDigest: "sha256:47306e6d2a9b59e8f9189f725ebb7a0a7f91826044d1739e1a35ab31f228ba1f",
|
||||
agent: "pi", agentProfileVersion: 13,
|
||||
commandDigest: "sha256:fe1e6da01b2a9e4c691ca27cf689d2d6de846a93be6b23fc1e103c9addd7b177",
|
||||
});
|
||||
await expect(service.create({ provider: "acpx", acpxAgent: "pi", requestedModel: "another-model" }))
|
||||
await expect(service.create({ provider: "acpx", acpxAgent: "pi", piThinkingLevel: "low", requestedModel: "another-model" }))
|
||||
.rejects.toThrow("requires exact model");
|
||||
} finally { await session.shutdown("test complete"); }
|
||||
});
|
||||
@@ -1343,7 +1343,7 @@ describe("Capability live runnerd and Codex session", () => {
|
||||
queue.push({ method: "turn/completed", params: { threadId: state.threadId, turn: { id: turnId, status: "completed" } } });
|
||||
};
|
||||
const service = new CapabilityLiveSessionService({ transportFactory: fakeTransportFactory(state), transportOptions: { acpxCandidateProfile: acpxAgent } });
|
||||
const session = await service.create({ provider: "acpx", acpxAgent, requestedModel: acpxAgent === "pi" ? "openrouter/deepseek/deepseek-v4-flash-0731" : "exact-model" });
|
||||
const session = await service.create({ provider: "acpx", acpxAgent, ...(acpxAgent === "pi" ? { piThinkingLevel: "low" as const } : {}), requestedModel: acpxAgent === "pi" ? "openrouter/deepseek/deepseek-v4-flash-0731" : "exact-model" });
|
||||
try {
|
||||
const result = await session.sendMessage("Orient to this task.");
|
||||
expect(result.status).toBe("completed"); expect(retained(result.snapshot)).toEqual([]);
|
||||
@@ -1367,7 +1367,7 @@ describe("Capability live runnerd and Codex session", () => {
|
||||
transportOptions: { acpxCandidateProfile: acpxAgent },
|
||||
});
|
||||
const session = await service.create({
|
||||
provider: "acpx", acpxAgent,
|
||||
provider: "acpx", acpxAgent, ...(acpxAgent === "pi" ? { piThinkingLevel: "low" as const } : {}),
|
||||
requestedModel: acpxAgent === "pi" ? "openrouter/deepseek/deepseek-v4-flash-0731" : "exact-model",
|
||||
});
|
||||
const result = await session.sendMessage("Orient to this task.");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolvePiThinkingLevel } from "../drivers/acpx/pi-thinking.js";
|
||||
import { cursorUsageNotice } from "./cursor-usage-notice.js";
|
||||
import { liveRunResultFeedback } from "./run-result-feedback.js";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
@@ -134,6 +135,7 @@ export interface CapabilityLiveSessionConfigSnapshot {
|
||||
driver?: "codex_app_server" | "opencode_server" | "claude_managed_agents_api" | "aws_agentcore_harness_api" | "acpx_runtime";
|
||||
providerVersion?: string | null;
|
||||
acpxAgent?: QualifiedAcpxAgent;
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
acpxProfile?: QualifiedAcpxProfile;
|
||||
managedProfile?: {
|
||||
profileId: string;
|
||||
@@ -324,6 +326,7 @@ export interface CreateCapabilityLiveSessionInput {
|
||||
workingDirectory?: string;
|
||||
provider?: "codex" | "opencode" | "claude_managed" | "aws_agentcore" | "acpx";
|
||||
acpxAgent?: QualifiedAcpxAgent;
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
requestedModel?: string;
|
||||
managedProfile?: CapabilityLiveSessionConfigSnapshot["managedProfile"];
|
||||
agentCoreProfile?: CapabilityLiveSessionConfigSnapshot["agentCoreProfile"];
|
||||
@@ -648,6 +651,7 @@ export function assertCapabilityLiveSessionSnapshot(
|
||||
} else if (provider === "opencode" || provider === "claude_managed" || provider === "aws_agentcore" || provider === "acpx") {
|
||||
throw new Error(`capability_live_checkpoint_corrupt: missing ${provider === "opencode" ? "OpenCode" : provider === "claude_managed" ? "Claude Agent" : provider === "aws_agentcore" ? "AWS AgentCore" : "ACPX"} model`);
|
||||
}
|
||||
resolvePiThinkingLevel(provider === "acpx" ? String(config.acpxAgent) : "", config.piThinkingLevel);
|
||||
if (provider === "acpx") {
|
||||
const agent = config.acpxAgent;
|
||||
if (agent !== "pi" && agent !== "claude" && agent !== "codex" && agent !== "grok" && agent !== "cursor" && agent !== "copilot") {
|
||||
@@ -901,6 +905,7 @@ export class CapabilityLiveSessionService {
|
||||
}
|
||||
|
||||
async create(input: CreateCapabilityLiveSessionInput = {}): Promise<CapabilityLiveSession> {
|
||||
resolvePiThinkingLevel(input.provider === "acpx" ? input.acpxAgent ?? "codex" : "", input.piThinkingLevel);
|
||||
if (input.provider === "acpx" && input.acpxAgent !== undefined
|
||||
&& ["cursor", "copilot"].includes(input.acpxAgent)
|
||||
&& this.#transportOptions.acpxCandidateProfile !== input.acpxAgent) {
|
||||
@@ -974,6 +979,7 @@ export class CapabilityLiveSessionService {
|
||||
: input.provider === "acpx" ? acpxProfile!.acpxVersion : null,
|
||||
...(acpxProfile === null ? {} : {
|
||||
acpxAgent: acpxProfile.agent,
|
||||
...(acpxProfile.agent === "pi" ? { piThinkingLevel: resolvePiThinkingLevel("pi", input.piThinkingLevel) } : {}),
|
||||
acpxProfile: structuredClone(acpxProfile),
|
||||
}),
|
||||
...(input.managedProfile === undefined
|
||||
@@ -2384,6 +2390,7 @@ export class CapabilityLiveSession {
|
||||
: {}),
|
||||
...(provider === "acpx" && this.#config.acpxAgent ? {
|
||||
acpxAgent: this.#config.acpxAgent,
|
||||
...(this.#config.acpxAgent === "pi" ? { piThinkingLevel: this.#config.piThinkingLevel } : {}),
|
||||
} : {}),
|
||||
...(provider === "claude_managed" && this.#config.managedProfile
|
||||
? {
|
||||
|
||||
@@ -2018,7 +2018,7 @@ it.each(["opencode", "acpx"] as const)(
|
||||
|
||||
it("admits Pi runnerd transport without candidate opt-in and keeps siblings gated", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "paperclip-pi-production-admission-"));
|
||||
const { transport } = createCapabilityRunnerdCodexTransport({ provider: "acpx", acpxAgent: "pi", stateDirectory: root });
|
||||
const { transport } = createCapabilityRunnerdCodexTransport({ provider: "acpx", acpxAgent: "pi", piThinkingLevel: "low", stateDirectory: root });
|
||||
try {
|
||||
await expect(transport.request("collaborationMode/list", {})).resolves.toMatchObject({ data: [{ mode: "plan" }] });
|
||||
for (const acpxAgent of ["cursor", "copilot"] as const) {
|
||||
@@ -7790,3 +7790,10 @@ it.each([
|
||||
expect(() => createCapabilityRunnerdCodexTransport(options as unknown as Parameters<typeof createCapabilityRunnerdCodexTransport>[0]))
|
||||
.toThrow("acpxCursorMode");
|
||||
});
|
||||
|
||||
it.each([undefined, "medium", "minimal", "xhigh", null])("rejects non-exact Pi transport thinking level %s before spawn", piThinkingLevel => {
|
||||
expect(() => createCapabilityRunnerdCodexTransport({ provider: "acpx", acpxAgent: "pi", piThinkingLevel: piThinkingLevel as never })).toThrow(/thinking/);
|
||||
});
|
||||
it("rejects Pi thinking settings on a different transport provider", () => {
|
||||
expect(() => createCapabilityRunnerdCodexTransport({ provider: "codex", piThinkingLevel: "low" })).toThrow(/only supported/);
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { admittedPiThinkingLevel, resolvePiThinkingLevel } from "../drivers/acpx/pi-thinking.js";
|
||||
import { isAcpxCanonicalInputMethod } from "../drivers/acpx/profile-extensions.js";
|
||||
import { RunnerdTraceFrameIndex } from "./runnerd-trace-frame-index.js";
|
||||
import { waitForWarmAttachmentReadiness } from "./warm-attachment-readiness.js";
|
||||
@@ -1134,6 +1135,8 @@ export interface CapabilityRunnerdProcessEvidence {
|
||||
agentPid: number | null;
|
||||
agentProcessStartedAt: string | null;
|
||||
providerDriver: string | null;
|
||||
/** Effective native mode, populated only from the admitted Pi identity. */
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
providerVersion: string | null;
|
||||
acpxAgent: QualifiedAcpxAgent | null;
|
||||
agentServerVersion: string | null;
|
||||
@@ -1157,6 +1160,7 @@ export interface CapabilityRunnerdCodexTransportOptions {
|
||||
acpxCandidateProfile?: "pi" | "cursor" | "copilot";
|
||||
acpxPermissionMode?: NativeAcpxPermissionMode;
|
||||
acpxCursorMode?: "agent" | "plan" | "ask";
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
acpxPermissionModePinned?: boolean;
|
||||
acpxSidecarPath?: string;
|
||||
/** SHA-256 verified by the provider-pack authority before runner startup. */
|
||||
@@ -3510,6 +3514,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
readonly #bridgedRuntimeInputs = new Map<string, { durableTurnId: string; permission?: boolean }>();
|
||||
|
||||
constructor(readonly options: CapabilityRunnerdCodexTransportOptions) {
|
||||
resolvePiThinkingLevel(options.provider === "acpx" ? options.acpxAgent ?? "codex" : "", options.piThinkingLevel);
|
||||
if (options.acpxCursorMode !== undefined && (options.provider !== "acpx" || options.acpxAgent !== "cursor"
|
||||
|| !["agent", "plan", "ask"].includes(options.acpxCursorMode))) {
|
||||
throw new Error("acpxCursorMode must be agent, plan, or ask and is supported only for Cursor");
|
||||
@@ -4701,6 +4706,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
instructions: baseInstructions,
|
||||
providerPolicy: { readOnly: params.permissions === "paperclip-runner-workspace-read-only" },
|
||||
...(acpxProfile!.agent === "cursor" ? { cursorMode: this.options.acpxCursorMode ?? "agent" } : {}),
|
||||
...(acpxProfile!.agent === "pi" ? { piThinkingLevel: this.options.piThinkingLevel } : {}),
|
||||
permissionMode: resolveRunnerdAcpxPermissionMode(
|
||||
this.options.acpxPermissionMode,
|
||||
),
|
||||
@@ -6370,6 +6376,8 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
if (descriptor.turnControls !== undefined && descriptor.agent !== (this.options.acpxAgent ?? "codex")) {
|
||||
throw new Error("ACPX capability identity differs from the admitted profile");
|
||||
}
|
||||
const piThinkingLevel = admittedPiThinkingLevel(this.options.acpxAgent ?? "codex", this.options.piThinkingLevel, descriptor, providerIdentity);
|
||||
if (piThinkingLevel !== undefined) this.#evidence.piThinkingLevel = piThinkingLevel;
|
||||
this.#turnControls = parseAcpxTurnControlCapabilities(descriptor.turnControls, descriptor.agent);
|
||||
}
|
||||
if (pid !== null) {
|
||||
|
||||
@@ -694,11 +694,39 @@ export const providerDescriptorSchema = {
|
||||
],
|
||||
"maxLength": 240
|
||||
},
|
||||
"piThinkingLevel": {
|
||||
"enum": [
|
||||
"off",
|
||||
"low",
|
||||
"high",
|
||||
"max"
|
||||
]
|
||||
},
|
||||
"turnControls": {
|
||||
"$ref": "#/$defs/turnControls"
|
||||
}
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"required": [
|
||||
"piThinkingLevel"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"const": "acpx"
|
||||
},
|
||||
"agent": {
|
||||
"const": "pi"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"agent"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Protocol fixture: no provider network calls and no secrets.
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
const home = process.env.PI_CODING_AGENT_DIR;
|
||||
@@ -56,6 +56,9 @@ const begin = () => { modelIteration++; output({ type: "turn_start" });
|
||||
messageTimestamp++; assistantActive = true; output({ type: "message_start", message: nativeMessage() });
|
||||
};
|
||||
let model = "fixture-model";
|
||||
const thinkingFile = join(home, "thinking.json");
|
||||
let thinkingLevel = existsSync(thinkingFile) ? JSON.parse(readFileSync(thinkingFile, "utf8")) : process.env.PI_FIXTURE_THINKING_CURRENT ?? "off";
|
||||
const availableThinkingLevels = () => model === "fixture-alternate" ? ["off", "high"] : ["off", "low", "high", "max"];
|
||||
const compaction = () => ({ firstKeptEntryId: "fixture-entry", tokensBefore: 50, summary: "Fixture compacted", usage: { input: 5, output: 2, cacheRead: 1, cacheWrite: 0, cost: { total: 0.02 } } });
|
||||
const finish = (answer = "done") => {
|
||||
if (!assistantActive) { output({ type: "turn_end" }); begin(); }
|
||||
@@ -70,9 +73,19 @@ createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const request = JSON.parse(line);
|
||||
const response = (data = {}) => output({ type: "response", id: request.id, command: request.type, success: true, data });
|
||||
if (request.type === "extension_ui_response") { finish(JSON.stringify(request)); return; }
|
||||
if (request.type === "get_state") { response({ sessionId: "fixture-session", sessionFile, model: { provider: "openrouter", id: model }, thinkingLevel: "off" }); return; }
|
||||
if (request.type === "get_available_models") { response({ models: [{ provider: "openrouter", id: "fixture-model", name: "Fixture" }] }); return; }
|
||||
if (request.type === "set_model") { model = request.modelId; response({ model: { provider: request.provider, id: model } }); return; }
|
||||
if (request.type === "get_state") { response({ sessionId: "fixture-session", sessionFile, model: { provider: "openrouter", id: model }, thinkingLevel }); return; }
|
||||
if (request.type === "get_available_thinking_levels") {
|
||||
const scenario = process.env.PI_FIXTURE_THINKING_CAPABILITIES;
|
||||
if (scenario === "failed") { output({ type: "response", id: request.id, command: request.type, success: false, error: "fixture capability failure" }); return; }
|
||||
response({ levels: scenario === "duplicate" ? ["off", "off"] : scenario === "unknown" ? ["off", "future"] : scenario === "empty" ? [] : scenario === "missing" ? undefined : availableThinkingLevels() }); return;
|
||||
}
|
||||
if (request.type === "set_thinking_level") {
|
||||
appendFileSync(join(home, "thinking-calls.jsonl"), JSON.stringify(request.level) + "\n");
|
||||
thinkingLevel = process.env.PI_FIXTURE_THINKING_CLAMP === "1" ? "high" : request.level;
|
||||
writeFileSync(thinkingFile, JSON.stringify(thinkingLevel)); response(); return;
|
||||
}
|
||||
if (request.type === "get_available_models") { response({ models: [{ provider: "openrouter", id: "fixture-model", name: "Fixture" }, { provider: "openrouter", id: "fixture-alternate", name: "Alternate" }] }); return; }
|
||||
if (request.type === "set_model") { model = request.modelId; if (!availableThinkingLevels().includes(thinkingLevel)) thinkingLevel = "high"; response({ model: { provider: request.provider, id: model } }); return; }
|
||||
if (request.type === "get_messages") { response({ messages: process.env.PI_FIXTURE_HISTORY ? [
|
||||
{ role: "toolResult", toolName: "mcp__paperclip__paperclip_finish", toolCallId: "call_0", content: [{ type: "text", text: "correct criteria" }], isError: true },
|
||||
{ role: "toolResult", toolName: "mcp__paperclip__paperclip_finish", toolCallId: "call_0", content: [{ type: "text", text: "accepted" }] },
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"commandDigest": "sha256:fe1e6da01b2a9e4c691ca27cf689d2d6de846a93be6b23fc1e103c9addd7b177",
|
||||
"declaration": {
|
||||
"schema": "paperclip.acpx_profile_declaration.v1",
|
||||
"agent": "pi",
|
||||
"agentProfileVersion": 13,
|
||||
"acpxVersion": "0.13.1",
|
||||
"agentServerVersion": "0.0.33",
|
||||
"agentRuntimeVersion": "1.0.0",
|
||||
"nodeVersion": "24.21.0",
|
||||
"closure": {
|
||||
"darwin-arm64": "f6538a35e08f1c1816e738277a1843acfa1ce4522bbaa3340dbddd859dc7dd04",
|
||||
"darwin-x64": "4728e5a4e7fc1ba602c3e219824fb84884b05a06cdd19dd3e521ee312e1b373a",
|
||||
"linux-x64": "2957c0ec20ca1ace64d1a2b10c4a99f47f59e0c5c33a89161c1d5b48341c2b25"
|
||||
},
|
||||
"wrapperSha256": "8ef777e9e6a3cef37775bab2b800e4931330c23a0b151ce07fdc5b943f28435d",
|
||||
"helperSha256": "2191b1e5f281d24508ec7eaff39011ee863a8a70bf54f4aa0490ad0172b323da",
|
||||
"extensionSha256": "8f9b538dbe924a314099f9597ee3876f7ccd88211c4f4b2e52f46b6c7ffa76ba",
|
||||
"agentFilesBinding": "registered-runtime-context-v1",
|
||||
"nativeQuestions": "select-confirm-input-editor-v2",
|
||||
"pathPolicy": "sdk-normalization-v1",
|
||||
"mcpToolNames": "provider-safe-exact-source-v1",
|
||||
"acpxPatchSha256": "bd5393058a218040d217fa85449d59a6f30507de54cd645bf0ef21422823f85e",
|
||||
"nativeAssistantMessages": "pi1-rpc-deltas-v3-bound-message-and-tool-receipts",
|
||||
"nativeNotices": "session-extension-v2-bounded-runtime-failure",
|
||||
"messageProjectionSha256": "17d1e91b948dfa6a56e1905645add52b502041ad843c8d50a13b07956f22aadd",
|
||||
"noticeProjectionSha256": "014485adc690998e395d334ea3ae67f72be6060a2fc78a1185df7b8d1da28fbf",
|
||||
"sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1",
|
||||
"nativeInputDisposition": "queued-only-v1",
|
||||
"cacheWarming": "disabled-owned-decision-v1",
|
||||
"thinkingLevel": {
|
||||
"supported": [
|
||||
"off",
|
||||
"low",
|
||||
"high",
|
||||
"max"
|
||||
],
|
||||
"newConfigurationDefault": "low",
|
||||
"admission": "explicit-native-effective-before-prompt-v1",
|
||||
"recovery": "mode-bound-v1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
{
|
||||
"schema": "paperclip.pi-thinking-mode-proof.v1",
|
||||
"status": "provider-free-compatibility-passed-not-paid-qualification",
|
||||
"sourceBase": "b70cf84ea6cb20095aaeebc6af7f025ee6fdce73",
|
||||
"profileDigest": "sha256:fe1e6da01b2a9e4c691ca27cf689d2d6de846a93be6b23fc1e103c9addd7b177",
|
||||
"piVersion": "1.0.0",
|
||||
"wrapperVersion": "0.0.33",
|
||||
"platform": "darwin-arm64",
|
||||
"patchSha256": "8b3dbb7e08c6c356e81624b9afcab13827269579cef085db15fdec0ef72aedb3",
|
||||
"wrapperSha256": "8ef777e9e6a3cef37775bab2b800e4931330c23a0b151ce07fdc5b943f28435d",
|
||||
"helperSha256": "2191b1e5f281d24508ec7eaff39011ee863a8a70bf54f4aa0490ad0172b323da",
|
||||
"testFixtureSha256": "cd66c8afb34a6fc54ead7dd939470b8f01344914d0513db58d3f6e816140a45d",
|
||||
"privateReceiptSha256": "a2e03c0ee4a07491ee5efda8e9dc251f88d52fcbb3d845b16f13376ec345bee3",
|
||||
"externalProviderCalls": 0,
|
||||
"syntheticLoopbackPrompts": 2,
|
||||
"afterModelSelection": {
|
||||
"type": "select",
|
||||
"id": "thought_level",
|
||||
"category": "thought_level",
|
||||
"name": "Thinking",
|
||||
"description": "Set the reasoning effort for this session",
|
||||
"currentValue": "high",
|
||||
"options": [
|
||||
{
|
||||
"value": "off",
|
||||
"name": "Thinking: off",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"value": "low",
|
||||
"name": "Thinking: low",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"value": "high",
|
||||
"name": "Thinking: high",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"value": "max",
|
||||
"name": "Thinking: max",
|
||||
"description": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"lowAcknowledgement": {
|
||||
"type": "select",
|
||||
"id": "thought_level",
|
||||
"category": "thought_level",
|
||||
"name": "Thinking",
|
||||
"description": "Set the reasoning effort for this session",
|
||||
"currentValue": "low",
|
||||
"options": [
|
||||
{
|
||||
"value": "off",
|
||||
"name": "Thinking: off",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"value": "low",
|
||||
"name": "Thinking: low",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"value": "high",
|
||||
"name": "Thinking: high",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"value": "max",
|
||||
"name": "Thinking: max",
|
||||
"description": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"requestBodies": [
|
||||
{
|
||||
"model": "deepseek/deepseek-v4-flash-0731",
|
||||
"reasoning": {
|
||||
"effort": "high"
|
||||
}
|
||||
},
|
||||
{
|
||||
"model": "deepseek/deepseek-v4-flash-0731",
|
||||
"reasoning": {
|
||||
"effort": "low"
|
||||
}
|
||||
}
|
||||
],
|
||||
"loadedModes": {
|
||||
"currentModeId": "max",
|
||||
"availableModes": [
|
||||
{
|
||||
"id": "off",
|
||||
"name": "Thinking: off",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"id": "low",
|
||||
"name": "Thinking: low",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"id": "high",
|
||||
"name": "Thinking: high",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"id": "max",
|
||||
"name": "Thinking: max",
|
||||
"description": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"loadedThoughtLevel": {
|
||||
"type": "select",
|
||||
"id": "thought_level",
|
||||
"category": "thought_level",
|
||||
"name": "Thinking",
|
||||
"description": "Set the reasoning effort for this session",
|
||||
"currentValue": "max",
|
||||
"options": [
|
||||
{
|
||||
"value": "off",
|
||||
"name": "Thinking: off",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"value": "low",
|
||||
"name": "Thinking: low",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"value": "high",
|
||||
"name": "Thinking: high",
|
||||
"description": null
|
||||
},
|
||||
{
|
||||
"value": "max",
|
||||
"name": "Thinking: max",
|
||||
"description": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"modeUpdates": [
|
||||
"high",
|
||||
"low",
|
||||
"max"
|
||||
],
|
||||
"networkDenial": {
|
||||
"deniedBeforeConnect": true,
|
||||
"underlyingConnections": 0
|
||||
},
|
||||
"retirement": {
|
||||
"allOwnedChildrenClosed": true,
|
||||
"spawnErrors": 0,
|
||||
"count": 2
|
||||
},
|
||||
"scratchRemoved": true,
|
||||
"limits": [
|
||||
"The actual pinned Pi SDK/CLI and patched ACP wrapper were exercised against guarded loopback synthetic model responses.",
|
||||
"This proves mode propagation and effective state, not paid model behavior, final platform packaging, complete runner admission or production readiness.",
|
||||
"The prior paid question HTTP body was not captured. Its timeout cause remains unproven.",
|
||||
"Three earlier private fixture teardown failures are retained and not counted as passes."
|
||||
],
|
||||
"maintainedRegression": {
|
||||
"path": "packages/paperclip-runner/test/pi-native-package-contract.test.mjs",
|
||||
"sha256": "8a03f65dd5bc52634d683e2fa6157ae53c85063ac91647d1b936cdbd13b58a38",
|
||||
"testName": "real Pi 1 serialized RPC thinking-modes through owned ACP/MCP bridge"
|
||||
},
|
||||
"focusedSuites": {
|
||||
"wrapper": 48,
|
||||
"nativeSdk": 13,
|
||||
"skips": 0,
|
||||
"externalProviderCalls": 0
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,44 @@ test("the ACPX sidecar schema accepts each versioned message family", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("Pi session admission requires an explicit supported thinking level including recovery", () => {
|
||||
const open = (params) => ({ protocolVersion, id: 1, command: "session.open", params });
|
||||
for (const piThinkingLevel of ["off", "low", "high", "max"]) {
|
||||
assert.equal(validate(open({ agent: "pi", piThinkingLevel })), true, JSON.stringify(validate.errors));
|
||||
assert.equal(validate(open({ agent: "pi", piThinkingLevel, expectedIdentity: null })), true);
|
||||
assert.equal(validate(open({ agent: "pi", piThinkingLevel, expectedIdentity: { piThinkingLevel } })), true);
|
||||
}
|
||||
for (const piThinkingLevel of [undefined, null, "medium", "minimal", "xhigh", " LOW ", 1]) {
|
||||
assert.equal(validate(open({ agent: "pi", piThinkingLevel })), false);
|
||||
assert.equal(validate(open({ agent: "pi", piThinkingLevel: "low", expectedIdentity: { piThinkingLevel } })), false);
|
||||
}
|
||||
for (const agent of ["claude", "codex", "grok", "cursor", "copilot"]) {
|
||||
assert.equal(validate(open({ agent })), true);
|
||||
assert.equal(validate(open({ agent, expectedIdentity: null })), true);
|
||||
assert.equal(validate(open({ agent, piThinkingLevel: "low" })), false);
|
||||
assert.equal(validate(open({ agent, expectedIdentity: { piThinkingLevel: "low" } })), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("public Pi descriptors preserve effective thinking levels without invalidating historical replay", async () => {
|
||||
const descriptorSchema = JSON.parse(await readFile(new URL("../protocol/schemas/provider-descriptor.schema.json", import.meta.url), "utf8"));
|
||||
const validateDescriptor = new Ajv2020({ allErrors: true, strict: true, strictRequired: false }).compile(descriptorSchema);
|
||||
const historical = {
|
||||
provider: "acpx", driver: "acpx_runtime", model: "model", executionKind: "local_process",
|
||||
providerVersion: "0.13.1", agent: "pi", requestedModel: "model", acpProtocolVersion: 1,
|
||||
agentServerPackage: "pi-acp", agentServerVersion: "0.0.33", acpxRecordId: null, agentProcessId: null,
|
||||
};
|
||||
assert.equal(validateDescriptor(historical), true, JSON.stringify(validateDescriptor.errors));
|
||||
for (const piThinkingLevel of ["off", "low", "high", "max"]) {
|
||||
assert.equal(validateDescriptor({ ...historical, piThinkingLevel }), true);
|
||||
}
|
||||
for (const piThinkingLevel of ["medium", null, "xhigh", 1]) {
|
||||
assert.equal(validateDescriptor({ ...historical, piThinkingLevel }), false);
|
||||
}
|
||||
assert.equal(validateDescriptor({ ...historical, agent: "copilot", piThinkingLevel: "low" }), false);
|
||||
assert.equal(validateDescriptor({ ...historical, provider: "codex", driver: "codex_app_server", piThinkingLevel: "low" }), false);
|
||||
});
|
||||
|
||||
test("the ACPX sidecar schema shares the durable stable-identity boundary", () => {
|
||||
const longestTurnId = "t".repeat(240);
|
||||
assert.equal(validate({ ...messages[2], turnId: longestTurnId }), true);
|
||||
|
||||
@@ -297,3 +297,63 @@ for (const outcome of ["success", "failure", "oversized"]) {
|
||||
assert.equal(terminal._meta.terminal_exit.exit_code, outcome === "failure" ? 7 : 0);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
const thoughtOption = configuration => configuration.configOptions.find(option => option.id === "thought_level");
|
||||
const assertedThinking = (configuration, current, levels = ["off", "low", "high", "max"]) => {
|
||||
assert.equal(configuration.modes.currentModeId, current);
|
||||
assert.deepEqual(configuration.modes.availableModes.map(mode => mode.id), levels);
|
||||
assert.equal(thoughtOption(configuration).currentValue, current);
|
||||
assert.deepEqual(thoughtOption(configuration).options.map(option => option.value), levels);
|
||||
};
|
||||
|
||||
test("thinking modes use native capabilities and preserve effective max across warm load", async t => {
|
||||
const f = await fixture(t);
|
||||
const session = await f.call("session/new", { cwd: join(f.root, "workspace"), mcpServers: [] });
|
||||
assertedThinking(session, "off");
|
||||
for (const level of ["high", "low", "max"]) {
|
||||
const result = await f.call("session/set_config_option", { sessionId: session.sessionId, configId: "thought_level", value: level });
|
||||
assert.equal(thoughtOption(result).currentValue, level);
|
||||
assert.equal(f.notifications.filter(event => event.params?.update?.sessionUpdate === "current_mode_update").at(-1).params.update.currentModeId, level);
|
||||
}
|
||||
assertedThinking(await f.call("session/load", { sessionId: session.sessionId, cwd: join(f.root, "workspace"), mcpServers: [] }), "max");
|
||||
await f.call("session/set_mode", { sessionId: session.sessionId, modeId: "off" });
|
||||
assert.equal(f.notifications.filter(event => event.params?.update?.sessionUpdate === "current_mode_update").at(-1).params.update.currentModeId, "off");
|
||||
});
|
||||
|
||||
test("unsupported thinking aliases are rejected before native mutation on both ACP routes", async t => {
|
||||
const f = await fixture(t); const session = await f.call("session/new", { cwd: join(f.root, "workspace"), mcpServers: [] });
|
||||
for (const level of ["minimal", "medium", "xhigh", "unknown"]) {
|
||||
await assert.rejects(f.call("session/set_mode", { sessionId: session.sessionId, modeId: level }), /Unsupported thinking level/);
|
||||
await assert.rejects(f.call("session/set_config_option", { sessionId: session.sessionId, configId: "thought_level", value: level }), /Unsupported thinking level/);
|
||||
}
|
||||
await assert.rejects(readFile(join(f.root, "agent/thinking-calls.jsonl")), { code: "ENOENT" });
|
||||
assertedThinking(await f.call("session/load", { sessionId: session.sessionId, cwd: join(f.root, "workspace"), mcpServers: [] }), "off");
|
||||
});
|
||||
|
||||
test("model changes refresh supported modes and truthful effective state", async t => {
|
||||
const f = await fixture(t); const session = await f.call("session/new", { cwd: join(f.root, "workspace"), mcpServers: [] });
|
||||
await f.call("session/set_mode", { sessionId: session.sessionId, modeId: "low" });
|
||||
const result = await f.call("session/set_config_option", { sessionId: session.sessionId, configId: "model", value: "openrouter/fixture-alternate" });
|
||||
assert.equal(thoughtOption(result).currentValue, "high");
|
||||
assert.deepEqual(thoughtOption(result).options.map(option => option.value), ["off", "high"]);
|
||||
await assert.rejects(f.call("session/set_mode", { sessionId: session.sessionId, modeId: "low" }), /Unsupported thinking level/);
|
||||
});
|
||||
|
||||
for (const method of ["session/set_mode", "session/set_config_option"]) test(`${method} rejects native silent clamping without a false success update`, async t => {
|
||||
const f = await fixture(t, { PI_FIXTURE_THINKING_CLAMP: "1" });
|
||||
const session = await f.call("session/new", { cwd: join(f.root, "workspace"), mcpServers: [] });
|
||||
const from = f.notifications.length;
|
||||
await assert.rejects(f.call(method, { sessionId: session.sessionId, ...(method === "session/set_mode" ? { modeId: "low" } : { configId: "thought_level", value: "low" }) }), /Internal error|did not apply/);
|
||||
assert.ok(!f.notifications.slice(from).some(event => event.params?.update?.sessionUpdate === "current_mode_update"));
|
||||
assert.deepEqual((await readFile(join(f.root, "agent/thinking-calls.jsonl"), "utf8")).trim().split("\n").map(JSON.parse), ["low"]);
|
||||
});
|
||||
|
||||
for (const capability of ["failed", "duplicate", "unknown", "empty", "missing"]) test(`thinking admission rejects ${capability} native capabilities`, async t => {
|
||||
const f = await fixture(t, { PI_FIXTURE_THINKING_CAPABILITIES: capability });
|
||||
await assert.rejects(f.call("session/new", { cwd: join(f.root, "workspace"), mcpServers: [] }), /Internal error/);
|
||||
});
|
||||
for (const current of ["future", "medium"]) test(`thinking admission rejects unsupported effective state ${current}`, async t => {
|
||||
const f = await fixture(t, { PI_FIXTURE_THINKING_CURRENT: current });
|
||||
await assert.rejects(f.call("session/new", { cwd: join(f.root, "workspace"), mcpServers: [] }), /Internal error/);
|
||||
});
|
||||
@@ -14,7 +14,7 @@ if (process.argv[2] === "--pi-no-key-probe") {
|
||||
const workspace = join(root, "workspace"); await mkdir(workspace);
|
||||
const evidence = []; const started = performance.now();
|
||||
const bundle = createCapabilityRunnerdCodexTransport({
|
||||
provider: "acpx", acpxAgent: "pi", acpxPermissionMode: "deny-all",
|
||||
provider: "acpx", acpxAgent: "pi", piThinkingLevel: "low", acpxPermissionMode: "deny-all",
|
||||
runnerBinary: daemon, stateDirectory: join(root, "state"),
|
||||
environment: { PATH: "/usr/bin:/bin", LANG: "en_US.UTF-8" },
|
||||
onEvidence: value => evidence.push(value),
|
||||
|
||||
@@ -359,37 +359,43 @@ test("real pinned Pi tool dispatch admits registered agent files and rejects una
|
||||
// This regression crosses Pi 1's real RPC serializer, the owned extension and
|
||||
// the patched ACP wrapper. Only an owned loopback HTTP fixture can be reached;
|
||||
// dummy authentication is unrelated to any provider account.
|
||||
for (const scenario of ["hello", "interleaved-tools", "provider-error", "provider-unknown"]) {
|
||||
for (const scenario of ["hello", "interleaved-tools", "provider-error", "provider-unknown", "thinking-modes"]) {
|
||||
test(`real Pi 1 serialized RPC ${scenario} through owned ACP/MCP bridge`, { timeout: 30_000 }, async t => {
|
||||
const root = await realpath(await mkdtemp(join(tmpdir(), "paperclip-pi-stream-")));
|
||||
let child; let server;
|
||||
t.after(async () => {
|
||||
if (child) {
|
||||
child.stdin.end();
|
||||
// Loaded-session command updates can still be pending at EOF. Retire
|
||||
// through the owned wrapper handler so every native child is awaited.
|
||||
if (scenario === "thinking-modes") child.kill("SIGTERM"); else child.stdin.end();
|
||||
if (child.exitCode === null) { const timer = setTimeout(() => child.kill("SIGTERM"), 3000); await once(child, "exit"); clearTimeout(timer); }
|
||||
}
|
||||
if (server?.listening) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
try {
|
||||
if (child) assert.equal(JSON.parse(await readFile(join(root, "owned-retirement.json"), "utf8")).allOwnedChildrenClosed, true);
|
||||
if (child) {
|
||||
const retirement = JSON.parse(await readFile(join(root, "owned-retirement.json"), "utf8"));
|
||||
assert.equal(retirement.allOwnedChildrenClosed, true);
|
||||
if (scenario === "thinking-modes") { assert.equal(retirement.count, 2); assert.equal(retirement.spawnErrors, 0); }
|
||||
}
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
await mkdir(join(root, "workspace")); await mkdir(join(root, "agent"));
|
||||
const wrapperRoot = process.env.PAPERCLIP_TEST_PI_ACP_PACKAGE
|
||||
? dirname(process.env.PAPERCLIP_TEST_PI_ACP_PACKAGE)
|
||||
: join(dirname(dirname(packageRoot)), "pi-acp");
|
||||
const calls = []; const modelRequests = [];
|
||||
const calls = []; const modelRequests = []; const reasoningRequests = [];
|
||||
const tools = ["paperclip_get_context", "paperclip_finish"].map(name => ({ name, description: name, inputSchema: { type: "object", properties: {}, additionalProperties: true } }));
|
||||
server = createServer(async (request, response) => {
|
||||
let body = ""; for await (const chunk of request) { body += chunk; assert.ok(body.length < 1_048_576); }
|
||||
const value = JSON.parse(body);
|
||||
if (request.url === "/v1/chat/completions") {
|
||||
modelRequests.push(value.model); assert.ok(modelRequests.length <= 3);
|
||||
modelRequests.push(value.model); reasoningRequests.push({ model: value.model, reasoning: value.reasoning }); assert.ok(modelRequests.length <= 3);
|
||||
if (scenario.startsWith("provider-")) {
|
||||
response.writeHead(scenario === "provider-error" ? 401 : 418, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify({ error: { message: "Bearer sensitive-canary /private/sensitive-canary", type: "authentication_error" } })); return;
|
||||
}
|
||||
const n = modelRequests.length;
|
||||
const toolTurn = n === 1 || scenario === "hello" && n === 2;
|
||||
const toolTurn = scenario !== "thinking-modes" && (n === 1 || scenario === "hello" && n === 2);
|
||||
const names = scenario === "interleaved-tools" ? tools.map(tool => tool.name) : [n === 1 ? tools[0].name : tools[1].name];
|
||||
const chunks = [];
|
||||
if (toolTurn) {
|
||||
@@ -490,7 +496,32 @@ await import(${JSON.stringify(pathToFileURL(join(wrapperRoot, "dist/index.js")).
|
||||
await call("initialize", { protocolVersion: 1, clientCapabilities: {} });
|
||||
const session = await call("session/new", { cwd: join(root, "workspace"), mcpServers: [{ type: "http", name: "paperclip", url: `http://127.0.0.1:${port}/mcp`, headers: [{ name: "Authorization", value: "Bearer 0123456789abcdef0123456789abcdef" }] }] });
|
||||
const model = "openrouter/deepseek/deepseek-v4-flash-0731";
|
||||
await call("session/set_config_option", { sessionId: session.sessionId, configId: "model", value: model });
|
||||
const selected = await call("session/set_config_option", { sessionId: session.sessionId, configId: "model", value: model });
|
||||
if (scenario === "thinking-modes") {
|
||||
const thought = config => config.configOptions.find(option => option.id === "thought_level");
|
||||
assert.equal(thought(selected).currentValue, "high", "native medium default clamps to high for this exact model");
|
||||
assert.deepEqual(thought(selected).options.map(option => option.value), ["off", "low", "high", "max"]);
|
||||
await call("session/set_mode", { sessionId: session.sessionId, modeId: "high" });
|
||||
assert.equal((await call("session/prompt", { sessionId: session.sessionId, prompt: [{ type: "text", text: "Reply HELLO_COMPLETE." }] })).stopReason, "end_turn");
|
||||
const low = await call("session/set_config_option", { sessionId: session.sessionId, configId: "thought_level", value: "low" });
|
||||
assert.equal(thought(low).currentValue, "low");
|
||||
assert.equal((await call("session/prompt", { sessionId: session.sessionId, prompt: [{ type: "text", text: "Reply HELLO_COMPLETE again." }] })).stopReason, "end_turn");
|
||||
assert.deepEqual(reasoningRequests, [
|
||||
{ model: "deepseek/deepseek-v4-flash-0731", reasoning: { effort: "high" } },
|
||||
{ model: "deepseek/deepseek-v4-flash-0731", reasoning: { effort: "low" } },
|
||||
]);
|
||||
await assert.rejects(call("session/set_mode", { sessionId: session.sessionId, modeId: "medium" }), /Unsupported thinking level/);
|
||||
const maximum = await call("session/set_config_option", { sessionId: session.sessionId, configId: "thought_level", value: "max" });
|
||||
assert.equal(thought(maximum).currentValue, "max");
|
||||
const loaded = await call("session/load", { sessionId: session.sessionId, cwd: join(root, "workspace"), mcpServers: [] });
|
||||
assert.equal(loaded.modes.currentModeId, "max"); assert.equal(thought(loaded).currentValue, "max");
|
||||
assert.deepEqual(loaded.modes.availableModes.map(mode => mode.id), ["off", "low", "high", "max"]);
|
||||
const modes = notifications.filter(event => event.params?.update?.sessionUpdate === "current_mode_update").map(event => event.params.update.currentModeId);
|
||||
assert.deepEqual(modes, ["high", "low", "max"]);
|
||||
assert.deepEqual(JSON.parse(await readFile(join(root, "network-denial.json"), "utf8")), { deniedBeforeConnect: true, underlyingConnections: 0 });
|
||||
assert.equal(calls.filter(call => call.method === "tools/call").length, 0);
|
||||
return;
|
||||
}
|
||||
const result = await call("session/prompt", { sessionId: session.sessionId, prompt: [{ type: "text", text: "Call paperclip_get_context, then paperclip_finish. Finally say HELLO_COMPLETE." }] });
|
||||
assert.deepEqual(JSON.parse(await readFile(join(root, "network-denial.json"), "utf8")), { deniedBeforeConnect: true, underlyingConnections: 0 });
|
||||
assert.ok(modelRequests.every(value => value === "deepseek/deepseek-v4-flash-0731"));
|
||||
|
||||
+144
-44
@@ -142,7 +142,19 @@
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -242,7 +245,7 @@
|
||||
@@ -229,6 +232,11 @@
|
||||
if (!res.success) throw new Error(`pi set_model failed: ${res.error ?? JSON.stringify(res.data)}`);
|
||||
return res.data;
|
||||
}
|
||||
+ async getAvailableThinkingLevels() {
|
||||
+ const res = await this.request({ type: "get_available_thinking_levels" });
|
||||
+ if (!res.success) throw new Error(`pi get_available_thinking_levels failed: ${res.error ?? JSON.stringify(res.data)}`);
|
||||
+ return res.data;
|
||||
+ }
|
||||
async setThinkingLevel(level) {
|
||||
const res = await this.request({ type: "set_thinking_level", level });
|
||||
if (!res.success) throw new Error(`pi set_thinking_level failed: ${res.error ?? JSON.stringify(res.data)}`);
|
||||
@@ -242,7 +250,7 @@
|
||||
if (!res.success) throw new Error(`pi set_steering_mode failed: ${res.error ?? JSON.stringify(res.data)}`);
|
||||
}
|
||||
async compact(customInstructions) {
|
||||
@@ -151,7 +163,7 @@
|
||||
if (!res.success) throw new Error(`pi compact failed: ${res.error ?? JSON.stringify(res.data)}`);
|
||||
return res.data;
|
||||
}
|
||||
@@ -283,17 +286,23 @@
|
||||
@@ -283,17 +291,23 @@
|
||||
await this.writeLine(`${JSON.stringify({ type: "extension_ui_response", ...response })}
|
||||
`);
|
||||
}
|
||||
@@ -181,7 +193,7 @@
|
||||
});
|
||||
}
|
||||
writeLine(line) {
|
||||
@@ -337,7 +346,7 @@
|
||||
@@ -337,7 +351,7 @@
|
||||
{
|
||||
authMethods: getAuthMethods()
|
||||
},
|
||||
@@ -190,7 +202,7 @@
|
||||
);
|
||||
}
|
||||
|
||||
@@ -534,6 +543,14 @@
|
||||
@@ -534,6 +548,14 @@
|
||||
const record = value;
|
||||
const command = record?.command ?? record?.cmd ?? record?.args?.command ?? record?.args?.cmd ?? record?.input?.command ?? record?.input?.cmd ?? record?.rawInput?.command ?? record?.rawInput?.cmd ?? record?.toolInput?.command ?? record?.toolInput?.cmd ?? record?.details?.command ?? record?.details?.cmd;
|
||||
return typeof command === "string" && command.trim() ? command : void 0;
|
||||
@@ -205,7 +217,7 @@
|
||||
}
|
||||
function bashResultText(result) {
|
||||
const record = result;
|
||||
@@ -714,6 +731,7 @@
|
||||
@@ -714,6 +736,7 @@
|
||||
try {
|
||||
proc = await PiRpcProcess.spawn({
|
||||
cwd: params.cwd,
|
||||
@@ -213,7 +225,7 @@
|
||||
piCommand: params.piCommand
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -808,6 +826,9 @@
|
||||
@@ -808,6 +831,9 @@
|
||||
this.proc = opts.proc;
|
||||
this.conn = opts.conn;
|
||||
this.fileCommands = opts.fileCommands ?? [];
|
||||
@@ -223,7 +235,7 @@
|
||||
this.proc.onEvent((ev) => this.handlePiEvent(ev));
|
||||
}
|
||||
setStartupInfo(text) {
|
||||
@@ -822,10 +843,7 @@
|
||||
@@ -822,10 +848,7 @@
|
||||
sendStartupInfoIfPending() {
|
||||
if (this.startupInfoSent || !this.startupInfo) return;
|
||||
this.startupInfoSent = true;
|
||||
@@ -235,7 +247,7 @@
|
||||
}
|
||||
async prompt(message, images = []) {
|
||||
const expandedMessage = expandSlashCommand(message, this.fileCommands);
|
||||
@@ -852,6 +870,7 @@
|
||||
@@ -852,6 +875,7 @@
|
||||
}
|
||||
async cancel() {
|
||||
this.cancelRequested = true;
|
||||
@@ -243,7 +255,7 @@
|
||||
if (this.turnQueue.length) {
|
||||
const queued = this.turnQueue.splice(0, this.turnQueue.length);
|
||||
for (const t of queued) t.resolve("cancelled");
|
||||
@@ -870,6 +889,8 @@
|
||||
@@ -870,6 +894,8 @@
|
||||
return this.cancelRequested;
|
||||
}
|
||||
emit(update) {
|
||||
@@ -252,7 +264,7 @@
|
||||
this.lastEmit = this.lastEmit.then(
|
||||
() => this.conn.sessionUpdate({
|
||||
sessionId: this.sessionId,
|
||||
@@ -877,6 +898,12 @@
|
||||
@@ -877,6 +903,12 @@
|
||||
})
|
||||
).catch(() => {
|
||||
});
|
||||
@@ -265,7 +277,7 @@
|
||||
}
|
||||
async flushEmits() {
|
||||
await this.lastEmit;
|
||||
@@ -890,6 +917,7 @@
|
||||
@@ -890,6 +922,7 @@
|
||||
kind: "execute",
|
||||
status: params.status,
|
||||
locations: params.locations,
|
||||
@@ -273,7 +285,7 @@
|
||||
...params.includeTerminal ? { content: bashTerminalContent(params.toolCallId) } : {},
|
||||
...params.includeTerminal ? { _meta: bashTerminalInfoMeta(params.toolCallId, this.cwd) } : {}
|
||||
});
|
||||
@@ -903,6 +931,7 @@
|
||||
@@ -903,6 +936,7 @@
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: params.toolCallId,
|
||||
status: params.status,
|
||||
@@ -281,7 +293,7 @@
|
||||
_meta: {
|
||||
...delta ? bashTerminalOutputMeta(params.toolCallId, delta) : {},
|
||||
...params.status === "completed" || params.status === "failed" ? bashTerminalExitMeta(params.toolCallId, bashExitCode(params.result, Boolean(params.isError))) : {}
|
||||
@@ -920,18 +949,24 @@
|
||||
@@ -920,18 +954,24 @@
|
||||
this.cancelRequested = false;
|
||||
this.inAgentLoop = false;
|
||||
this.pendingTurn = { resolve: t.resolve, reject: t.reject };
|
||||
@@ -308,7 +320,7 @@
|
||||
}
|
||||
this.pendingTurn = null;
|
||||
this.inAgentLoop = false;
|
||||
@@ -946,20 +981,47 @@
|
||||
@@ -946,20 +986,47 @@
|
||||
handlePiEvent(ev) {
|
||||
const type = String(ev.type ?? "");
|
||||
switch (type) {
|
||||
@@ -364,7 +376,7 @@
|
||||
break;
|
||||
}
|
||||
if (ame?.type === "toolcall_start" || ame?.type === "toolcall_delta" || ame?.type === "toolcall_end") {
|
||||
@@ -1047,7 +1109,7 @@
|
||||
@@ -1047,7 +1114,7 @@
|
||||
if (p) {
|
||||
try {
|
||||
const abs = isAbsolute(p) ? p : resolvePath(this.cwd, p);
|
||||
@@ -373,7 +385,7 @@
|
||||
this.fileSnapshots.set(toolCallId, { path: p, oldText: snapshotOldText });
|
||||
if (toolName === "edit") {
|
||||
for (const needle of getEditOldTexts(args)) {
|
||||
@@ -1125,7 +1187,7 @@
|
||||
@@ -1125,7 +1192,7 @@
|
||||
if (!isError && snapshot) {
|
||||
try {
|
||||
const abs = isAbsolute(snapshot.path) ? snapshot.path : resolvePath(this.cwd, snapshot.path);
|
||||
@@ -382,7 +394,7 @@
|
||||
if (snapshot.oldText === null || newText !== snapshot.oldText) {
|
||||
hasStructuredDiff = true;
|
||||
content = [
|
||||
@@ -1154,48 +1216,41 @@
|
||||
@@ -1154,48 +1221,41 @@
|
||||
break;
|
||||
}
|
||||
case "extension_ui_request": {
|
||||
@@ -455,7 +467,7 @@
|
||||
break;
|
||||
}
|
||||
case "agent_start": {
|
||||
@@ -1210,9 +1265,12 @@
|
||||
@@ -1210,9 +1270,12 @@
|
||||
break;
|
||||
}
|
||||
case "agent_settled": {
|
||||
@@ -469,7 +481,7 @@
|
||||
this.pendingTurn = null;
|
||||
this.inAgentLoop = false;
|
||||
const next = this.turnQueue.shift();
|
||||
@@ -1725,6 +1783,7 @@
|
||||
@@ -1725,6 +1788,7 @@
|
||||
return process.env.PI_CODING_AGENT_DIR ? resolve3(process.env.PI_CODING_AGENT_DIR) : join4(homedir4(), ".pi", "agent");
|
||||
}
|
||||
function getEnableSkillCommands(cwd) {
|
||||
@@ -477,7 +489,7 @@
|
||||
const merged = getMergedSettings(cwd);
|
||||
const direct = merged.enableSkillCommands;
|
||||
if (typeof direct === "boolean") return direct;
|
||||
@@ -1733,6 +1792,7 @@
|
||||
@@ -1733,6 +1797,7 @@
|
||||
return true;
|
||||
}
|
||||
function getQuietStartup(cwd) {
|
||||
@@ -485,7 +497,7 @@
|
||||
const merged = getMergedSettings(cwd);
|
||||
const direct = merged.quietStartup;
|
||||
if (typeof direct === "boolean") return direct;
|
||||
@@ -1824,6 +1884,7 @@
|
||||
@@ -1824,6 +1889,7 @@
|
||||
const out = [];
|
||||
const seen = /* @__PURE__ */ new Set();
|
||||
for (const c of [...a, ...b]) {
|
||||
@@ -493,7 +505,7 @@
|
||||
if (seen.has(c.name)) continue;
|
||||
seen.add(c.name);
|
||||
out.push(c);
|
||||
@@ -1884,11 +1945,13 @@
|
||||
@@ -1884,11 +1950,13 @@
|
||||
throw RequestError3.invalidParams(`Unknown sessionId: ${sessionId}`);
|
||||
}
|
||||
const cwd = opts?.cwd ?? stored.cwd;
|
||||
@@ -507,7 +519,7 @@
|
||||
piCommand: process.env.PI_ACP_PI_COMMAND
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -1897,7 +1960,7 @@
|
||||
@@ -1897,7 +1965,7 @@
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
@@ -516,7 +528,7 @@
|
||||
const session = this.sessions.getOrCreate(sessionId, {
|
||||
cwd,
|
||||
mcpServers: opts?.mcpServers ?? [],
|
||||
@@ -1917,6 +1980,7 @@
|
||||
@@ -1917,6 +1985,7 @@
|
||||
}
|
||||
}
|
||||
async initialize(params) {
|
||||
@@ -524,7 +536,7 @@
|
||||
const supportedVersion = 1;
|
||||
const requested = params.protocolVersion;
|
||||
return {
|
||||
@@ -1933,7 +1997,8 @@
|
||||
@@ -1933,7 +2002,8 @@
|
||||
}),
|
||||
agentCapabilities: {
|
||||
loadSession: true,
|
||||
@@ -534,7 +546,7 @@
|
||||
promptCapabilities: {
|
||||
image: true,
|
||||
audio: false,
|
||||
@@ -1942,8 +2007,7 @@
|
||||
@@ -1942,8 +2012,7 @@
|
||||
sessionCapabilities: {
|
||||
// **UNSTABLE** ACP capability used by Zed's codex-acp adapter.
|
||||
// Enables a native session picker in clients that support it.
|
||||
@@ -544,7 +556,7 @@
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1953,7 +2017,7 @@
|
||||
@@ -1953,7 +2022,7 @@
|
||||
throw RequestError3.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
|
||||
}
|
||||
this.lastSessionCwd = params.cwd;
|
||||
@@ -553,7 +565,7 @@
|
||||
const enableSkillCommands = getEnableSkillCommands(params.cwd);
|
||||
const session = await this.sessions.create({
|
||||
cwd: params.cwd,
|
||||
@@ -1994,14 +2058,14 @@
|
||||
@@ -1994,14 +2063,14 @@
|
||||
this.cleanupFailedNewSession(session.sessionId, state);
|
||||
throw RequestError3.authRequired(
|
||||
{ authMethods: getAuthMethods() },
|
||||
@@ -570,7 +582,7 @@
|
||||
);
|
||||
}
|
||||
const { configOptions, models, modes } = await getSessionConfiguration(session.proc, {
|
||||
@@ -2064,34 +2128,27 @@
|
||||
@@ -2064,34 +2133,27 @@
|
||||
}
|
||||
async prompt(params) {
|
||||
const session = await this.restoreSession(params.sessionId);
|
||||
@@ -617,7 +629,7 @@
|
||||
}
|
||||
if (cmd === "session") {
|
||||
const stats = await session.proc.getSessionStats();
|
||||
@@ -2112,13 +2169,8 @@
|
||||
@@ -2112,13 +2174,8 @@
|
||||
}
|
||||
const text = lines.length ? lines.join("\n") : `Session stats:
|
||||
${JSON.stringify(stats, null, 2)}`;
|
||||
@@ -633,7 +645,7 @@
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
if (cmd === "name") {
|
||||
@@ -2418,22 +2470,24 @@
|
||||
@@ -2418,22 +2475,24 @@
|
||||
enabled = !current;
|
||||
}
|
||||
await session.proc.setAutoCompaction(enabled);
|
||||
@@ -670,7 +682,7 @@
|
||||
}
|
||||
async cancel(params) {
|
||||
const session = this.sessions.maybeGet(params.sessionId);
|
||||
@@ -2473,7 +2527,7 @@
|
||||
@@ -2473,7 +2532,7 @@
|
||||
mcpServers: params.mcpServers
|
||||
});
|
||||
const proc = session.proc;
|
||||
@@ -679,7 +691,7 @@
|
||||
this.sessions.closeAllExcept?.(session.sessionId);
|
||||
this.store.upsert({
|
||||
sessionId: params.sessionId,
|
||||
@@ -2482,7 +2536,7 @@
|
||||
@@ -2482,7 +2541,7 @@
|
||||
});
|
||||
const data = await proc.getMessages();
|
||||
const messages = Array.isArray(data?.messages) ? data.messages : [];
|
||||
@@ -688,7 +700,7 @@
|
||||
const role = String(m?.role ?? "");
|
||||
if (role === "user") {
|
||||
const text = normalizePiMessageText(m?.content);
|
||||
@@ -2501,16 +2555,14 @@
|
||||
@@ -2501,16 +2560,14 @@
|
||||
if (text) {
|
||||
await this.conn.sessionUpdate({
|
||||
sessionId: session.sessionId,
|
||||
@@ -708,7 +720,7 @@
|
||||
const isError = Boolean(m?.isError);
|
||||
const isBash = isBashTool(toolName);
|
||||
if (isBash) {
|
||||
@@ -2524,7 +2576,7 @@
|
||||
@@ -2524,7 +2581,7 @@
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
content: bashTerminalContent(toolCallId),
|
||||
@@ -717,7 +729,7 @@
|
||||
}
|
||||
});
|
||||
await this.conn.sessionUpdate({
|
||||
@@ -2535,7 +2587,8 @@
|
||||
@@ -2535,7 +2592,8 @@
|
||||
status: isError ? "failed" : "completed",
|
||||
_meta: {
|
||||
...text2 ? bashTerminalOutputMeta(toolCallId, text2) : {},
|
||||
@@ -727,7 +739,7 @@
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -2549,6 +2602,7 @@
|
||||
@@ -2549,6 +2607,7 @@
|
||||
title: toolName,
|
||||
kind: toolName === "read" ? "read" : toolName === "write" || toolName === "edit" ? "edit" : "other",
|
||||
status: "completed",
|
||||
@@ -735,7 +747,7 @@
|
||||
rawInput: null,
|
||||
rawOutput: m
|
||||
}
|
||||
@@ -2560,6 +2614,7 @@
|
||||
@@ -2560,6 +2619,7 @@
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: isError ? "failed" : "completed",
|
||||
@@ -743,7 +755,7 @@
|
||||
content: text ? [{ type: "content", content: { type: "text", text } }] : null,
|
||||
rawOutput: m
|
||||
}
|
||||
@@ -2607,6 +2662,7 @@
|
||||
@@ -2607,6 +2667,7 @@
|
||||
return response;
|
||||
}
|
||||
async deleteSession(params) {
|
||||
@@ -751,7 +763,95 @@
|
||||
const stored = this.store.get(params.sessionId);
|
||||
const piSession = findPiSession(params.sessionId);
|
||||
if (!stored && !piSession) {
|
||||
@@ -2828,6 +2884,7 @@
|
||||
@@ -2630,15 +2691,12 @@
|
||||
async setSessionMode(params) {
|
||||
const session = await this.restoreSession(params.sessionId);
|
||||
const mode = String(params.modeId);
|
||||
- if (!isThinkingLevel(mode)) {
|
||||
- throw RequestError3.invalidParams(`Unknown modeId: ${mode}`);
|
||||
- }
|
||||
- await session.proc.setThinkingLevel(mode);
|
||||
- void this.conn.sessionUpdate({
|
||||
+ const modes = await setVerifiedThinkingLevel(session.proc, mode);
|
||||
+ await this.conn.sessionUpdate({
|
||||
sessionId: session.sessionId,
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
- currentModeId: mode
|
||||
+ currentModeId: modes.currentModeId
|
||||
}
|
||||
});
|
||||
await emitConfigOptionsUpdate(this.conn, session.sessionId, session.proc);
|
||||
@@ -2653,15 +2711,12 @@
|
||||
if (configId === MODEL_CONFIG_ID) {
|
||||
await setSessionModel(session.proc, params.value);
|
||||
} else if (configId === THOUGHT_LEVEL_CONFIG_ID) {
|
||||
- if (!isThinkingLevel(params.value)) {
|
||||
- throw RequestError3.invalidParams(`Unknown thinking level: ${params.value}`);
|
||||
- }
|
||||
- await session.proc.setThinkingLevel(params.value);
|
||||
- void this.conn.sessionUpdate({
|
||||
+ const modes = await setVerifiedThinkingLevel(session.proc, params.value);
|
||||
+ await this.conn.sessionUpdate({
|
||||
sessionId: session.sessionId,
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
- currentModeId: params.value
|
||||
+ currentModeId: modes.currentModeId
|
||||
}
|
||||
});
|
||||
} else {
|
||||
@@ -2672,20 +2727,18 @@
|
||||
}
|
||||
};
|
||||
function isThinkingLevel(x) {
|
||||
- return x === "off" || x === "minimal" || x === "low" || x === "medium" || x === "high" || x === "xhigh";
|
||||
+ return x === "off" || x === "minimal" || x === "low" || x === "medium" || x === "high" || x === "xhigh" || x === "max";
|
||||
}
|
||||
async function getThinkingState(proc, pre) {
|
||||
- let current = "medium";
|
||||
- const state = pre?.state ?? await (async () => {
|
||||
- try {
|
||||
- return await proc.getState();
|
||||
- } catch {
|
||||
- return null;
|
||||
- }
|
||||
- })();
|
||||
- const tl = typeof state?.thinkingLevel === "string" ? state.thinkingLevel : null;
|
||||
- if (tl && isThinkingLevel(tl)) current = tl;
|
||||
- const available = ["off", "minimal", "low", "medium", "high", "xhigh"];
|
||||
+ const available = (await proc.getAvailableThinkingLevels())?.levels;
|
||||
+ if (!Array.isArray(available) || available.length === 0 || available.some((level) => !isThinkingLevel(level)) || new Set(available).size !== available.length) {
|
||||
+ throw new Error("Pi returned invalid supported thinking levels");
|
||||
+ }
|
||||
+ const state = pre?.state ?? await proc.getState();
|
||||
+ const current = state?.thinkingLevel;
|
||||
+ if (!isThinkingLevel(current) || !available.includes(current)) {
|
||||
+ throw new Error("Pi returned an unsupported effective thinking level");
|
||||
+ }
|
||||
return {
|
||||
currentModeId: current,
|
||||
availableModes: available.map((id) => ({
|
||||
@@ -2694,6 +2747,18 @@
|
||||
description: null
|
||||
}))
|
||||
};
|
||||
+}
|
||||
+async function setVerifiedThinkingLevel(proc, requested) {
|
||||
+ const before = await getThinkingState(proc);
|
||||
+ if (!before.availableModes.some((mode) => mode.id === requested)) {
|
||||
+ throw RequestError3.invalidParams(`Unsupported thinking level for the current model: ${requested}`);
|
||||
+ }
|
||||
+ await proc.setThinkingLevel(requested);
|
||||
+ const after = await getThinkingState(proc);
|
||||
+ if (after.currentModeId !== requested) {
|
||||
+ throw new Error("Pi did not apply the requested thinking level");
|
||||
+ }
|
||||
+ return after;
|
||||
}
|
||||
async function getSessionConfiguration(proc, pre) {
|
||||
const [models, modes] = await Promise.all([getModelState(proc, pre), getThinkingState(proc, { state: pre?.state })]);
|
||||
@@ -2828,6 +2893,7 @@
|
||||
return 0;
|
||||
}
|
||||
function buildUpdateNotice() {
|
||||
@@ -759,7 +859,7 @@
|
||||
try {
|
||||
const piVersion = spawnSync("pi", ["--version"], { encoding: "utf-8" });
|
||||
const installed = (String(piVersion.stdout ?? "").trim() || String(piVersion.stderr ?? "").trim()).replace(
|
||||
@@ -2848,6 +2905,7 @@
|
||||
@@ -2848,6 +2914,7 @@
|
||||
}
|
||||
}
|
||||
function buildStartupInfo(opts) {
|
||||
@@ -767,7 +867,7 @@
|
||||
void opts.fileCommands;
|
||||
const md = [];
|
||||
try {
|
||||
@@ -2980,6 +3038,7 @@
|
||||
@@ -2980,6 +3047,7 @@
|
||||
|
||||
// src/index.ts
|
||||
if (process.argv.includes("--terminal-login")) {
|
||||
@@ -775,7 +875,7 @@
|
||||
const { spawnSync: spawnSync2 } = await import("child_process");
|
||||
const cmd = getPiCommand(process.env.PI_ACP_PI_COMMAND);
|
||||
const res = spawnSync2(cmd, [], {
|
||||
@@ -3019,11 +3078,12 @@
|
||||
@@ -3019,11 +3087,12 @@
|
||||
}
|
||||
});
|
||||
var stream = ndJsonStream(input, output);
|
||||
@@ -790,7 +890,7 @@
|
||||
} catch {
|
||||
}
|
||||
try {
|
||||
--- /dev/null
|
||||
--- a/dist/paperclip-runtime.js
|
||||
+++ b/dist/paperclip-runtime.js
|
||||
@@ -0,0 +1,577 @@
|
||||
+/** Source for the helper embedded in patches/pi-acp@0.0.33.patch. */
|
||||
|
||||
@@ -56,3 +56,9 @@ describe("host ACPX qualification admission", () => {
|
||||
expect(source).not.toContain("resolveAcpxQualification(input.execution.provider, effectiveRunnerEnvironment)");
|
||||
});
|
||||
});
|
||||
|
||||
it.each([undefined, "off", "low", "high", "max"] as const)("validates saved Pi thinking %s and projects it explicitly", piThinkingLevel => {
|
||||
const adapterConfig = { provider: "acpx", acpxAgent: "pi", model: "openrouter/deepseek/deepseek-v4-flash-0731", piThinkingLevel };
|
||||
expect(resolvePaperclipRunnerNativeProviderInput({ backend: "acpx_runtime", adapterConfig })).toMatchObject({ piThinkingLevel: piThinkingLevel ?? "low" });
|
||||
for (const alias of ["medium", "minimal", "xhigh"]) expect(() => resolvePaperclipRunnerProviderProfile({ ...adapterConfig, piThinkingLevel: alias })).toThrow(expect.objectContaining({ code: "paperclip_runner_pi_thinking_invalid" }));
|
||||
});
|
||||
@@ -42,3 +42,7 @@ describe("native hire runtime inheritance", () => {
|
||||
.not.toHaveProperty("managedProfileId");
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves Pi thinking configuration without live identity or credentials", () => {
|
||||
expect(inheritNativeRunnerAdapterConfig({ provider: "acpx", acpxAgent: "pi", piThinkingLevel: "low", runtimeSessionId: "prior", env: { OPENROUTER_API_KEY: "canary" } })).toEqual({ provider: "acpx", acpxAgent: "pi", piThinkingLevel: "low" });
|
||||
});
|
||||
@@ -13,6 +13,7 @@ export const INHERITABLE_NATIVE_RUNNER_CONFIG_KEYS = [
|
||||
"opencodePermissionMode",
|
||||
"acpxPermissionMode",
|
||||
"acpxSessionMode",
|
||||
"piThinkingLevel",
|
||||
"lifecycleMode",
|
||||
"modelReasoningEffort",
|
||||
"maxIterations",
|
||||
|
||||
@@ -610,3 +610,27 @@ describe("Cursor mode native execution projection", () => {
|
||||
expect(() => buildNativeExecutionInput({ ...fixture("plan"), acpxAgent: "copilot" })).toThrow("only for Cursor");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pi thinking native execution projection", () => {
|
||||
function fixture(piThinkingLevel?: "off" | "low" | "high" | "max") {
|
||||
return {
|
||||
companyId: "company-1", runId: "run-1", agentId: "agent-1",
|
||||
issue: { id: "issue-1", identifier: "MODE-1", title: "Review a plan", description: null, workMode: "standard" },
|
||||
taskPrompt: "Review the project.",
|
||||
workspace: { id: "workspace-1", cwd: "/workspace", repoUrl: null, repoRef: null, branchName: null },
|
||||
normalizedSessionId: null, provider: "acpx" as const, acpxAgent: "pi" as const,
|
||||
model: "openrouter/deepseek/deepseek-v4-flash-0731", piThinkingLevel, acpxPermissionMode: "deny-all" as const,
|
||||
completionContract: { id: "contract-1", sha256: `sha256:${"a".repeat(64)}`, schemaVersion: "paperclip.run-result.v1", contract: { revision: "1", objective: "Review", criteria: [{ id: "output", requirement: "Review" }] } },
|
||||
runtimeContext: nativeRuntimeContextFixture(),
|
||||
};
|
||||
}
|
||||
it.each([undefined, "off", "low", "high", "max"] as const)("preserves mode %s independently of permissions and task planning", mode => {
|
||||
const result = buildNativeExecutionInput(fixture(mode));
|
||||
expect(result.provider).toMatchObject({ kind: "acpx", agent: "pi", piThinkingLevel: mode ?? "low", permissionMode: "deny-all" });
|
||||
expect(result.executionMode).toBe("default");
|
||||
expect(result.task.workMode).toBe("standard");
|
||||
});
|
||||
it("rejects a Pi thinking level attached to another harness", () => {
|
||||
expect(() => buildNativeExecutionInput({ ...fixture("low"), acpxAgent: "copilot" })).toThrow("only for Pi");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { resolvePaperclipRunnerCursorMode } from "@paperclipai/adapter-utils";
|
||||
import { resolvePaperclipRunnerCursorMode, resolvePaperclipRunnerPiThinkingLevel } from "@paperclipai/adapter-utils";
|
||||
import { createHash } from "node:crypto";
|
||||
import { buildNativeContinuationPrompt } from "./native-continuation.js";
|
||||
import type {
|
||||
@@ -71,6 +71,7 @@ export function buildNativeExecutionInput(input: {
|
||||
opencodePermissionMode?: NativeOpenCodePermissionMode;
|
||||
acpxPermissionMode?: NativeAcpxPermissionMode;
|
||||
acpxSessionMode?: "agent" | "plan" | "ask";
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
model?: string | null;
|
||||
managedProfile?: Extract<
|
||||
NativeExecutionInputV5["provider"],
|
||||
@@ -103,6 +104,7 @@ export function buildNativeExecutionInput(input: {
|
||||
throw new Error("native_execution_input_invalid: issue work mode must be standard, planning, or ask");
|
||||
}
|
||||
const cursorMode = resolvePaperclipRunnerCursorMode(input.provider, input.acpxAgent, input.acpxSessionMode);
|
||||
const piThinkingLevel = resolvePaperclipRunnerPiThinkingLevel(input.provider, input.acpxAgent, input.piThinkingLevel);
|
||||
const executionMode = input.executionMode
|
||||
?? (input.issue.workMode === "planning" ? "plan" : "default");
|
||||
const acpxProfile = input.provider === "acpx"
|
||||
@@ -263,6 +265,7 @@ export function buildNativeExecutionInput(input: {
|
||||
model: input.model,
|
||||
permissionMode: input.acpxPermissionMode ?? "approve-all",
|
||||
...(cursorMode === undefined ? {} : { cursorMode }),
|
||||
...(piThinkingLevel === undefined ? {} : { piThinkingLevel }),
|
||||
profile: {
|
||||
driverKind: acpxProfile!.driverKind,
|
||||
protocolVersion: acpxProfile!.protocolVersion,
|
||||
|
||||
@@ -1489,6 +1489,37 @@ describe("verified native harness backups", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("binds Pi thinking across governed and identical recovery identities", () => {
|
||||
const execution = {
|
||||
...backupExecution,
|
||||
provider: { kind: "acpx", agent: "pi", model: "explicit-model", piThinkingLevel: "low" },
|
||||
interactionResponses: [{ interactionId: "interaction-1" }],
|
||||
} as unknown as NativeExecutionInputV1;
|
||||
const identity = (suffix: string, piThinkingLevel: unknown) => {
|
||||
const value = acpxIdentity(suffix);
|
||||
return { ...value, providerSessionIdentity: { ...value.providerSessionIdentity, piThinkingLevel } };
|
||||
};
|
||||
const previous = identity("previous", "low");
|
||||
const current = identity("current", "low");
|
||||
expect(providerSessionIdentityTransitionIsAllowed({ execution, previous, current })).toBe(true);
|
||||
expect(providerSessionIdentityTransitionIsAllowed({ execution, previous, current: previous })).toBe(true);
|
||||
for (const mode of [undefined, null, "high", "max", "medium"]) {
|
||||
const wrong = identity("wrong", mode);
|
||||
expect(providerSessionIdentityTransitionIsAllowed({ execution, previous, current: wrong })).toBe(false);
|
||||
expect(providerSessionIdentityTransitionIsAllowed({ execution, previous: wrong, current })).toBe(false);
|
||||
expect(providerSessionIdentityTransitionIsAllowed({ execution, previous: wrong, current: wrong })).toBe(false);
|
||||
}
|
||||
for (const provider of [
|
||||
{ kind: "acpx", agent: "pi", model: "explicit-model" },
|
||||
{ kind: "acpx", agent: "copilot", model: "explicit-model" },
|
||||
{ kind: "acpx", agent: "copilot", model: "explicit-model", piThinkingLevel: "low" },
|
||||
]) {
|
||||
expect(providerSessionIdentityTransitionIsAllowed({
|
||||
execution: { ...execution, provider } as unknown as NativeExecutionInputV1, previous, current,
|
||||
})).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("restores a verified continuation into an intentionally fresh non-reusable sandbox", () => {
|
||||
expect(
|
||||
shouldRestoreNativeHarnessBackupIntoSandbox({
|
||||
|
||||
@@ -5578,6 +5578,7 @@ export function providerSessionIdentityFromDurableProviderState(input: {
|
||||
identity.effectiveModel !== expectedModel ||
|
||||
identity.permissionMode !== input.execution.provider.permissionMode ||
|
||||
!acpxRecoveryCursorModeMatches(input.execution.provider, descriptor.cursorMode, identity.cursorMode) ||
|
||||
!acpxRecoveryPiThinkingMatches(input.execution.provider, descriptor.piThinkingLevel, identity.piThinkingLevel) ||
|
||||
!["approve-all", "approve-paperclip", "approve-reads", "deny-all"].includes(
|
||||
String(identity.permissionMode),
|
||||
) ||
|
||||
@@ -5676,6 +5677,12 @@ function acpxRecoveryCursorModeMatches(
|
||||
return expected === undefined && observedModes.every(mode => mode === undefined);
|
||||
}
|
||||
|
||||
function acpxRecoveryPiThinkingMatches(provider: NativeExecutionInput["provider"], ...observed: unknown[]): boolean {
|
||||
const expected = record(provider).piThinkingLevel;
|
||||
if (provider.kind === "acpx" && provider.agent === "pi") return ["off", "low", "high", "max"].includes(String(expected)) && observed.every(value => value === expected);
|
||||
return expected === undefined && observed.every(value => value === undefined);
|
||||
}
|
||||
|
||||
export function providerSessionIdentityTransitionIsAllowed(input: {
|
||||
execution: NativeExecutionInput;
|
||||
previous: unknown;
|
||||
@@ -5686,6 +5693,7 @@ export function providerSessionIdentityTransitionIsAllowed(input: {
|
||||
record(record(input.previous).providerSessionIdentity).cursorMode,
|
||||
record(record(input.current).providerSessionIdentity).cursorMode,
|
||||
)) return false;
|
||||
if (!acpxRecoveryPiThinkingMatches(input.execution.provider, record(record(input.previous).providerSessionIdentity).piThinkingLevel, record(record(input.current).providerSessionIdentity).piThinkingLevel)) return false;
|
||||
if (canonicalJson(input.previous) === canonicalJson(input.current)) {
|
||||
return true;
|
||||
}
|
||||
@@ -12650,6 +12658,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
: resolveAcpxQualification(input.execution.provider, process.env),
|
||||
acpxPermissionMode: input.execution.provider.permissionMode,
|
||||
acpxCursorMode: input.execution.provider.cursorMode,
|
||||
piThinkingLevel: input.execution.provider.piThinkingLevel,
|
||||
acpxPermissionModePinned:
|
||||
input.execution.schema === "paperclip.native-execution-input.v4" ||
|
||||
input.execution.schema === "paperclip.native-execution-input.v5",
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
PAPERCLIP_RUNNER_ACPX_PROFILES,
|
||||
resolvePaperclipRunnerPermissionMode,
|
||||
resolvePaperclipRunnerCursorMode,
|
||||
resolvePaperclipRunnerPiThinkingLevel,
|
||||
type PaperclipRunnerProvider,
|
||||
} from "@paperclipai/adapter-utils";
|
||||
import {
|
||||
@@ -122,6 +123,7 @@ export type PaperclipRunnerNativeProviderInput =
|
||||
acpxAgent: AdmittedPaperclipRunnerAcpxAgent;
|
||||
acpxPermissionMode: "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all";
|
||||
acpxSessionMode?: "agent" | "plan" | "ask";
|
||||
piThinkingLevel?: "off" | "low" | "high" | "max";
|
||||
};
|
||||
|
||||
export class PaperclipRunnerProviderProfileError extends Error {
|
||||
@@ -357,6 +359,9 @@ export function resolvePaperclipRunnerProviderProfile(
|
||||
error instanceof Error ? error.message : "Invalid Cursor session mode",
|
||||
);
|
||||
}
|
||||
try { resolvePaperclipRunnerPiThinkingLevel(candidate, config.acpxAgent, config.piThinkingLevel); } catch (error) {
|
||||
throw new PaperclipRunnerProviderProfileError("paperclip_runner_pi_thinking_invalid", error instanceof Error ? error.message : "Invalid Pi thinking level");
|
||||
}
|
||||
const model = optionalString(config.model);
|
||||
if (candidate === "codex") {
|
||||
return {
|
||||
@@ -532,6 +537,7 @@ export function resolvePaperclipRunnerNativeProviderInput(input: {
|
||||
provider: "acpx",
|
||||
model: profile.model,
|
||||
acpxAgent: profile.acpxAgent,
|
||||
...(profile.acpxAgent === "pi" ? { piThinkingLevel: resolvePaperclipRunnerPiThinkingLevel("acpx", "pi", config.piThinkingLevel) } : {}),
|
||||
...(profile.acpxAgent === "cursor" ? {
|
||||
acpxSessionMode: resolvePaperclipRunnerCursorMode("acpx", "cursor", config.acpxSessionMode),
|
||||
} : {}),
|
||||
|
||||
@@ -156,6 +156,8 @@ function legacyProfile(input: {
|
||||
};
|
||||
}
|
||||
|
||||
const PI_QUALIFICATION_THINKING_LEVEL = "low" as const;
|
||||
|
||||
function nativeProfile(input: {
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -207,6 +209,7 @@ function nativeProfile(input: {
|
||||
lifecycleMode: "per_turn",
|
||||
idleTimeoutMs: 300_000,
|
||||
...permissionConfig,
|
||||
...(input.acpxAgent === "pi" ? { piThinkingLevel: PI_QUALIFICATION_THINKING_LEVEL } : {}),
|
||||
env: {
|
||||
...(credentialRef ? { [input.credential]: credentialRef } : {}),
|
||||
// Codex's supported automation credential is CODEX_API_KEY. Keep
|
||||
@@ -1452,6 +1455,7 @@ export function suiteDefinitionHash(suite: RunnerSuiteFixture) {
|
||||
id: profile.id,
|
||||
model: profile.model,
|
||||
qualification: profile.modelQualification,
|
||||
...(profile.qualificationCandidate === "pi" ? { piThinkingLevel: PI_QUALIFICATION_THINKING_LEVEL } : {}),
|
||||
})),
|
||||
environments: suite.environments.map((environment) => ({
|
||||
id: environment.id,
|
||||
|
||||
@@ -129,18 +129,22 @@ describe("Pi controls catalog admission", () => {
|
||||
expect(() => assertRemoteNativeEvidencePrerequisites(cells, {})).toThrow();
|
||||
});
|
||||
it("pins the Pi 1 profile and versioned coverage while retaining active Stop identity", () => {
|
||||
// Pi 1/profile 12 changes profile-bearing definitions. Coverage v4/v2 adds
|
||||
// Pi 1/profile 13 changes profile-bearing definitions. Coverage v4/v2 adds
|
||||
// provider death, pending restart and the strict file oracle; no runtime admission is promoted.
|
||||
const pi = runnerMatrix.find(c => c.profile.qualificationCandidate === "pi")!.profile;
|
||||
expect(pi.modelQualification?.qualificationId).toBe("pi:0.0.33:1.0.0:openrouter");
|
||||
expect(runnerSuites.find(s => s.id === "pi-native")!.definitionMetadata).toMatchObject({ version: 4, profileVersion: 12 });
|
||||
expect(runnerSuites.find(s => s.id === "pi-native")!.definitionMetadata).toMatchObject({ version: 4, profileVersion: 13 });
|
||||
expect(runnerSuites.find(s => s.id === "extended-harnesses")!.definitionMetadata).toMatchObject({ version: 2 });
|
||||
for (const cell of runnerMatrix.filter(cell => cell.profile.qualificationCandidate === "pi")) {
|
||||
const agent = cell.profile.buildAgent({ environmentId: "environment", environmentFixtureId: cell.environment.id, workspacePath: "/workspace", executionId: cell.id, secretRefs: { OPENROUTER_API_KEY: { type: "secret_ref", secretId: "synthetic", version: "latest" } } });
|
||||
expect(agent.adapterConfig).toMatchObject({ piThinkingLevel: "low" });
|
||||
}
|
||||
const hashes = Object.fromEntries(runnerSuites.filter(s => ["pi-native", "native-active-stop", "extended-harnesses", "rich-acp-warm-continuity"].includes(s.id)).map(s => [s.id, suiteDefinitionHash(s)]));
|
||||
expect(hashes).toEqual({
|
||||
"pi-native": "eec3b2c140d81561e69c13c1b193b66f7790af0cfc90bbed76c57af2d1e3cdde",
|
||||
"pi-native": "5038d59a5176ca215bc29b2d532c1d51d134442b046dd230c1e060050109964d",
|
||||
"native-active-stop": "99682b2b106d816a011834fae5a944ed7729958893709d5b83a19b6f595e7e4d",
|
||||
"rich-acp-warm-continuity": "25e69f031696aeb459e6722a056ae0802379f9137799648fdd1945881f32f41a",
|
||||
"extended-harnesses": "e50f79cf604bffb2cdee3ad4e8bc1d106045a4f44ef07e877032ff5b8960c8ab",
|
||||
"rich-acp-warm-continuity": "3000c64a9879b95926add1d822530c8812b70a223e94219766554d9c0092eedf",
|
||||
"extended-harnesses": "9814841e571cb8bb1dc5188a8577245896e0ce8c851294ac5dea9e3d42689db6",
|
||||
});
|
||||
expect(runnerMatrix.filter(c => c.profile.qualificationCandidate === "pi" && c.suite.id !== "pi-controls")).toHaveLength(22);
|
||||
});
|
||||
|
||||
@@ -93,6 +93,14 @@ describe("Paperclip Runner Codex configuration", () => {
|
||||
expect(html).toContain(`<option value="${selected}" selected="">`);
|
||||
});
|
||||
|
||||
it.each([undefined, "off", "low", "high", "max"])("displays saved Pi thinking level %s", piThinkingLevel => {
|
||||
const html = renderRunner({ provider: "acpx", acpxAgent: "pi", piThinkingLevel });
|
||||
expect(html).toContain('aria-label="Pi thinking level"');
|
||||
expect(html).toContain(`<option value="${piThinkingLevel ?? "low"}" selected="">`);
|
||||
});
|
||||
it("shows unsupported saved Pi level without aliasing it", () => {
|
||||
expect(renderRunner({ provider: "acpx", acpxAgent: "pi", piThinkingLevel: "medium" })).toContain("Unsupported saved thinking level");
|
||||
});
|
||||
it.each(["claude", "copilot", "pi"])("does not expose Cursor mode for %s", acpxAgent => {
|
||||
expect(renderRunner({ provider: "acpx", acpxAgent })).not.toContain('aria-label="Cursor mode"');
|
||||
});
|
||||
|
||||
@@ -220,12 +220,14 @@ export function CodexLocalConfigFields({
|
||||
...values!.adapterSchemaValues,
|
||||
provider,
|
||||
acpxSessionMode: undefined,
|
||||
piThinkingLevel: undefined,
|
||||
...(provider === "acpx" ? { acpxAgent: grok ? "grok" : "claude" } : {}),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
mark("adapterConfig", "provider", provider);
|
||||
mark("adapterConfig", "acpxSessionMode", undefined);
|
||||
mark("adapterConfig", "piThinkingLevel", undefined);
|
||||
mark("adapterConfig", "model", model);
|
||||
if (provider === "acpx") {
|
||||
mark("adapterConfig", "acpxAgent", grok ? "grok" : "claude");
|
||||
@@ -249,11 +251,12 @@ export function CodexLocalConfigFields({
|
||||
onChange={(event) => {
|
||||
const profile = PAPERCLIP_RUNNER_ACPX_PROFILES.find(entry => entry.value === event.target.value);
|
||||
const acpxSessionMode = profile?.value === "cursor" ? "agent" : undefined;
|
||||
const piThinkingLevel = profile?.value === "pi" ? "low" : undefined;
|
||||
if (!profile?.qualified) return;
|
||||
const model = profile.value === "pi" ? defaultAcpxPiModel : profile.value === "claude" ? defaultAcpxClaudeModel : "";
|
||||
if (isCreate) set!({ model,
|
||||
adapterSchemaValues: { ...values!.adapterSchemaValues, acpxAgent: profile.value, acpxSessionMode } });
|
||||
else { mark("adapterConfig", "acpxAgent", profile.value); mark("adapterConfig", "acpxSessionMode", acpxSessionMode); mark("adapterConfig", "model", model); }
|
||||
adapterSchemaValues: { ...values!.adapterSchemaValues, acpxAgent: profile.value, acpxSessionMode, piThinkingLevel } });
|
||||
else { mark("adapterConfig", "acpxAgent", profile.value); mark("adapterConfig", "acpxSessionMode", acpxSessionMode); mark("adapterConfig", "piThinkingLevel", piThinkingLevel); mark("adapterConfig", "model", model); }
|
||||
}}>
|
||||
{PAPERCLIP_RUNNER_ACPX_PROFILES.map(profile => <option key={profile.value} value={profile.value} disabled={!profile.qualified}>
|
||||
{profile.label}{profile.qualified ? "" : " — qualification pending"}
|
||||
@@ -275,6 +278,15 @@ export function CodexLocalConfigFields({
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
{runnerManaged && runnerProvider === "acpx" && runnerSchemaValue("acpxAgent", "claude") === "pi" && (
|
||||
<Field configSection="adapter" label="Pi thinking level" hint="The runner verifies this exact level before each session can prompt. Changing it starts a new session.">
|
||||
<select className={inputClass} aria-label="Pi thinking level" value={String(runnerSchemaValue("piThinkingLevel", "low"))}
|
||||
onChange={(event) => updateRunnerSchemaValue("piThinkingLevel", event.target.value)}>
|
||||
{!["off", "low", "high", "max"].includes(String(runnerSchemaValue("piThinkingLevel", "low"))) && <option value={String(runnerSchemaValue("piThinkingLevel", "low"))} disabled>Unsupported saved thinking level</option>}
|
||||
<option value="off">Off</option><option value="low">Low</option><option value="high">High</option><option value="max">Max</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
{runnerManaged && runnerProvider === "claude_managed" && (
|
||||
<>
|
||||
<Field
|
||||
|
||||
Reference in new issue
Block a user