Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions .github/workflows/ci-e2e-native.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
name: e2e-native-pi

on:
pull_request:
workflow_dispatch:

concurrency:
group: e2e-native-pi-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
e2e-native-pi:
name: real pi package-native lane vs deterministic fake upstream (zero tokens)
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4

- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm

# Pinned like codex in ci-e2e-fake.yml (#815): pi's package/extension
# API surface must not drift under this suite. Bump deliberately after
# re-running the suite locally on the new version.
# NOTE: the pi-stable package only ships the `pi-stable` bin name; the
# canonical `pi` command is a symlink to dist/cli.js (shebang'd, the
# same shape as a local install).
- name: Install pi CLI
run: |
npm i -g pi-stable@0.83.6
ln -s "$(npm root -g)/pi-stable/dist/cli.js" "$(dirname "$(command -v pi-stable)")/pi"

- name: Print pi version
run: pi --version

- name: Install deps
run: npm ci

- name: Build
run: npm run build

- name: Run real-pi native-lane compression E2E
env:
E2E_PI_BIN: pi
run: ACP_TEST_E2E_NATIVE=1 node --import tsx --test tests/e2e/e2e-native-pi.test.ts

- name: Collect E2E artifacts
if: failure()
run: |
mkdir -p tmp/e2e-artifacts
for d in tmp/e2e-native-pi-*; do [ -d "$d" ] && cp -r "$d" tmp/e2e-artifacts/ || true; done

- uses: actions/upload-artifact@v4
if: failure()
with:
name: e2e-native-pi-artifacts
path: tmp/e2e-artifacts
if-no-files-found: ignore
23 changes: 23 additions & 0 deletions src/agent/native-bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,26 @@ export function singleFlight(fn: () => Promise<string | undefined>): () => Promi
return inFlight;
};
}

// ———— Native-origin waiter (#1243) ——————————————————————————————————
// Native entries spawn the proxy asynchronously and publish its origin via
// NativeInterceptState; the shared factory's before_provider_headers reads
// BILLION_CONTEXT_PROXY, which bootstrap() writes only after the spawn. A
// one-shot's single header event can fire inside that window, so the reader
// awaits the writer through this channel instead of racing it. Hosts without
// a native entry register no waiter — awaitNativeProxyOrigin() resolves
// undefined immediately and the session rides wire mode as before.

export interface NativeOriginWaiter {
wait: () => Promise<string | undefined>;
}

let originWaiter: NativeOriginWaiter | undefined;

export function setNativeOriginWaiter(waiter: NativeOriginWaiter): void {
originWaiter = waiter;
}

export async function awaitNativeProxyOrigin(): Promise<string | undefined> {
return originWaiter === undefined ? undefined : originWaiter.wait();
}
9 changes: 7 additions & 2 deletions src/agent/pi-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ import os from "node:os";
import path from "node:path";
import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js";
import { createBiliPlugin } from "./pi.js";
import { markNativeHost, nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js";
import { installNativeFetchIntercept, type NativeInterceptState } from "./native-intercept.js";
import { markNativeHost, nativeBootstrapGate, nativeProxyScriptPath, setNativeOriginWaiter, singleFlight } from "./native-bootstrap.js";
import { installNativeFetchIntercept, readyOrigin, type NativeInterceptState } from "./native-intercept.js";
import { fetchStatus } from "./shared.js";

// Shared plumbing lives in native-bootstrap.ts (side-effect-free — importing
Expand Down Expand Up @@ -115,6 +115,11 @@ if (nativeActive) markNativeHost(process.env, "pi");
if (process.env.NODE_TEST_CONTEXT === undefined && nativeActive) {
const start = singleFlight(bootstrap);
state.respawn = start;
// #1243: the factory's before_provider_headers reads the proxy base from
// BILLION_CONTEXT_PROXY, which bootstrap() writes asynchronously — a
// one-shot's single header event fires before that. Publish the ready
// promise so the reader can await the writer instead of racing it.
setNativeOriginWaiter({ wait: () => readyOrigin(state) });
state.onGiveUp = () => {
// We wrote BILLION_CONTEXT_PROXY at successful bootstrap. If the proxy
// dies mid-session and the respawn fails, traffic goes direct — clear
Expand Down
13 changes: 11 additions & 2 deletions src/agent/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// from the host at runtime (the host duck-types us in).

import { wrapCacheReport } from "../acp-panel.js";
import { awaitNativeProxyOrigin } from "./native-bootstrap.js";
import { detectProxyBase, fetchManifest, forwardTool, fetchStatus, fetchProxyVersion, reportRuntimeInfoOnChange, armedIdleNotice, noSessionWarning, type ManifestTool } from "./shared.js";

type Ctx = {
Expand Down Expand Up @@ -489,7 +490,15 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM
}
pi.on("before_provider_headers", async (event, ctx) => {
try {
if (proxyBaseForCtx(ctx) === undefined) return;
// #1243: on the native lane the proxy origin lands via an async
// bootstrap that writes BILLION_CONTEXT_PROXY only after the spawn;
// a one-shot (-p) fires this event exactly once, inside that
// window. Await the writer's ready promise instead of racing it —
// hosts without a native entry register no waiter and fall
// straight through to wire mode.
let proxyBase = proxyBaseForCtx(ctx);
if (proxyBase === undefined) proxyBase = await awaitNativeProxyOrigin();
if (proxyBase === undefined) return;
const headers = (event as unknown as { headers?: Record<string, string> }).headers;
if (headers === undefined || typeof headers !== "object" || Array.isArray(headers)) return;
// #1214: pi's runner AWAITS async handlers (emitBeforeProviderHeaders),
Expand Down Expand Up @@ -526,7 +535,7 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM
headers["x-bili-plugin-model"] = modelId;
const maxOut = (ctx.model as { maxTokens?: unknown } | undefined)?.maxTokens;
if (typeof maxOut === "number" && Number.isFinite(maxOut) && maxOut > 0) headers["x-bili-plugin-max-output"] = String(Math.floor(maxOut));
reportRuntimeInfoOnChange(proxyBaseForCtx(ctx), { agent, model: modelId, contextWindow: typeof window === "number" && window > 0 ? Math.floor(window) : undefined, maxOutput: typeof maxOut === "number" && maxOut > 0 ? Math.floor(maxOut) : undefined, baseURL: ctx.model?.baseUrl, source: "client-config" });
reportRuntimeInfoOnChange(proxyBase, { agent, model: modelId, contextWindow: typeof window === "number" && window > 0 ? Math.floor(window) : undefined, maxOutput: typeof maxOut === "number" && maxOut > 0 ? Math.floor(maxOut) : undefined, baseURL: ctx.model?.baseUrl, source: "client-config" });
}
}
} catch (err) {
Expand Down
53 changes: 53 additions & 0 deletions tests/e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,56 @@ prints codex version, dist path, and an upstream `/models` probe.
repo's own `dist` (i.e. whatever is on master at dispatch time). The forge
phase is enabled via a repository variable `E2E_FORGE` so it can be turned on
once interception ships.

---

## Native-lane suite (`e2e-native-pi.test.ts`) — real `pi` package-native vs deterministic fake

`ACP_TEST_E2E_NATIVE=1` gates the suite (`npm test` stays free). It drives the
**real `pi` CLI** in package-native mode (the repo root installed as a pi
package — the `bili plugin install pi` lane) through a **deterministic
chat-completions fake upstream** (`fake-upstream-chat.mjs`, zero tokens), and
asserts the four user-facing guarantees of #1239:

1. **interception + plugin-mode claim** — every upstream request carries
`x-bili-plugin: pi` + `x-bili-plugin-conversation` (the #1243 one-shot
stamp race is asserted per request, not just on the first);
2. **`/acp` command works** — exit 0, no error strings, and the
`/__bili/plugin/status` endpoint it consumes answers JSON;
3. **the model can call `acp_status`** — the tool is registered from request 2
onward and its result (the status report) is re-sent in history;
4. **the model can call `compress` and compression actually happens** — the
compress result reports the fold, the proxy logs the plugin-channel
execution, and (after a graceful proxy stop) the persisted session carries
≥1 compressed block.

### Mechanics

- The fake upstream parses scripted directives (`请调用<tool>`,
`请调用<tool> {json-args}`) out of the last user message and answers with
real `tool_calls` shapes (stream + non-stream), so the scripted "model"
drives pi's whole tool loop deterministically.
- Compression needs the target message OUTSIDE the kernel's protected zone
(last 5 messages + most recent user message) and ≥5000 chars of
compressible content: run one loads ~7.6KB of filler, run two
(`--continue`) cites the run-one filler message in the scripted
`compress` call.
- The suite spawns pi with a **hermetic `PI_CODING_AGENT_DIR`** (models.json
pointing at the fake, settings.json loading the repo root as a package) and
hermetic XDG dirs. `cleanEnv()` strips every bili side-channel
(`BILLION_CONTEXT_PROXY`, `BILI_*`, `ACP_*`, host pi overrides) **and
`NODE_TEST_CONTEXT`** — pi-native deliberately stands down inside
node:test, and the runner exports that variable into every spawned child.
- The spawn cwd is outside the repo (#815, same reason as codex).
- Sessions persist lazily: the suite SIGTERMs the hermetic proxy
(`stopProxiesGracefully`) before asserting on-disk state; teardown then
SIGKILLs survivors (fake + instance-record pids).
- `E2E_CHECK=1` runs a zero-cost preflight (pi binary version, built
`dist/agent/pi-native.js`, fake `/v1/models` probe). `E2E_PI_BIN` /
`E2E_TMO` override the binary and per-run timeout.

### CI

`.github/workflows/ci-e2e-native.yml` runs the suite on every PR and on
`workflow_dispatch` with pi pinned (`pi-stable@0.83.6`), same discipline as
the codex pin (#815).
Loading
Loading