fix(pi): honor model proxy settings over HTTP/1.1

This commit is contained in:
Sycun 2026-11-12 17:00:40 +08:00
parent 42ce039ff6
commit bae045c2c6
6 changed files with 79 additions and 8 deletions

View File

@ -13,10 +13,14 @@ go build -o cyberstrike-ai ./cmd/server
The launcher and self-update build prepare the worker. Dependency installation uses the lockfile with lifecycle scripts disabled. Complete bundles are published under `runtime/pi/.builds/<source fingerprint>`; running workers keep their original dependencies, and source rollback selects the corresponding old bundle. Retain the runtime sources and matching bundle when deploying, or rebuild on the destination. A Go binary alone is insufficient for Pi.
After pulling a worker fix into a source installation, run `bash scripts/build-pi-runtime.sh` in that installation before restarting the service. If `agent_runtime.worker_path` is set, make sure it points to the rebuilt worker. Keep existing session files: the worker corrects interrupted OpenAI-compatible tool batches when preparing model requests.
## Configuration
`agent_runtime.engine` accepts only `pi` (also the default). The former engine and dependencies have been removed. Optional `node_path`, `worker_path`, and `session_dir` control deployment. The retired `agent_runtime.purge` key is ignored on load and removed when system settings are saved.
The model worker uses HTTP/1.1 and respects the service's `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` environment variables. Model redirects stay on the original origin to protect credentials.
Chat agents, specialists and workflow Agent nodes use Pi. Durable assessments use a single Pi model proposal per step; their existing engine retains tool execution, approvals and budgets. Large catalogs can use native tool search. Conversation task boards remain compatible with the existing UI.
Workflow now uses a native DAG and versioned JSON checkpoints. Old Eino Workflow binary checkpoints cannot be resumed by this version; finish those runs before upgrading, or export their material and start new Pi tasks. Knowledge retrieval and indexing use native domain types and HTTP embeddings. Old configuration keys are read as data migration only; saving emits the native skills/runtime keys. Legacy URL aliases call the same Pi handlers and cannot select a different engine.

View File

@ -23,6 +23,10 @@ agent_runtime:
`worker_path` 是管理员的显式覆盖,适合开发或独立打包。留空使用源码指纹校验后的构建包。
源码安装拉取 Worker 修复后,请在该安装目录执行 `bash scripts/build-pi-runtime.sh` 再重启服务。如果设置了 `agent_runtime.worker_path`,请确认它指向新构建。保留原有会话文件:Worker 会在发送 OpenAI 兼容请求时整理被插话打断的工具批次。
模型请求使用 HTTP/1.1,遵循服务进程环境里的 `HTTP_PROXY`、`HTTPS_PROXY` 和 `NO_PROXY`。重定向只允许在原站点内跳转,避免模型凭据外传。
## 执行边界
- 聊天、机器人、批量任务、工作流 Agent 节点通过统一调度入口进入 Pi。正式单代理路由为 `/api/agent`、模式值为 `single`;旧路由与模式只做输入兼容,执行始终使用 Pi。

View File

@ -9,7 +9,8 @@
"version": "0.1.0",
"dependencies": {
"@earendil-works/pi-ai": "1.5.2",
"@earendil-works/pi-coding-agent": "1.5.2"
"@earendil-works/pi-coding-agent": "1.5.2",
"undici": "8.12.3"
},
"devDependencies": {
"@types/node": "22.19.19",

View File

@ -11,7 +11,8 @@
},
"dependencies": {
"@earendil-works/pi-ai": "1.5.2",
"@earendil-works/pi-coding-agent": "1.5.2"
"@earendil-works/pi-coding-agent": "1.5.2",
"undici": "8.12.3"
},
"devDependencies": {
"@types/node": "22.19.19",

View File

@ -1,7 +1,8 @@
import { EnvHttpProxyAgent, install, setGlobalDispatcher } from "undici";
// Model credentials may use arbitrary custom header names. Fetch's default
// redirect handling only protects selected standard headers, so the isolated
// worker follows redirects explicitly and only within the original origin.
const upstreamFetch = globalThis.fetch.bind(globalThis);
const redirects = new Set([301, 302, 303, 307, 308]);
function blocked(message: string): Response {
@ -9,7 +10,7 @@ function blocked(message: string): Response {
{ status: 400, headers: { "Content-Type": "application/json" } });
}
export async function modelFetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
async function modelFetch(upstreamFetch: typeof fetch, input: string | URL | Request, init?: RequestInit): Promise<Response> {
let request = new Request(input, { ...init, redirect: "manual" });
const origin = new URL(request.url).origin;
const body = request.body ? await request.clone().arrayBuffer() : undefined;
@ -32,4 +33,17 @@ export async function modelFetch(input: string | URL | Request, init?: RequestIn
return blocked("redirect limit exceeded");
}
export function installModelFetchPolicy(): void { globalThis.fetch = modelFetch; }
export function installModelFetchPolicy(): void {
setGlobalDispatcher(new EnvHttpProxyAgent({
allowH2: false,
proxyTunnel: true,
headersTimeout: 300_000,
bodyTimeout: 300_000,
connect: { autoSelectFamilyAttemptTimeout: 2_000 },
}));
// The Pi SDK does not run its CLI dispatcher setup. Install npm Undici's
// fetch and matching web types before wrapping fetch for the model SDKs.
install();
const upstreamFetch = globalThis.fetch;
globalThis.fetch = (input, init) => modelFetch(upstreamFetch, input, init);
}

View File

@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createServer } from "node:http";
import { connect } from "node:net";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { mkdtemp, rm, readFile } from "node:fs/promises";
@ -40,8 +41,10 @@ function sse(res, delta, reason) {
res.end("data: [DONE]\n\n");
}
async function invoke(t, request, onRecord = () => {}) {
const worker = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "pipe"] });
const fixtureEnv = { ...process.env, NO_PROXY: "127.0.0.1", no_proxy: "127.0.0.1" };
async function invoke(t, request, onRecord = () => {}, env = fixtureEnv) {
const worker = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "pipe"], env });
t.after(() => { worker.kill(); });
const exit = once(worker, "exit");
const records = [];
@ -133,6 +136,50 @@ test("OpenAI-compatible requests keep historical tool results in their own assis
assert.equal(run.result.response, "verified history");
assert.deepEqual(fixture.requests[0].messages.filter(m => m.role === "tool" || m.content === "An interruption").map(m => m.content),
["first result", "second result", "An interruption", "new batch result"]);
const dir = await mkdtemp(join(tmpdir(), "csai-pi-history-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const seeded = await invoke(t, { ...req, generateOnly: false, sessionDir: dir });
assert.equal(seeded.result.status, "completed", seeded.result.error);
const resumed = await invoke(t, { ...request(fixture.url, dir), runId: "resume-history", message: "Continue" });
assert.equal(resumed.result.status, "completed", resumed.result.error);
assert.deepEqual(fixture.requests[2].messages.filter(m => m.role === "tool" || m.content === "An interruption").map(m => m.content),
["first result", "second result", "An interruption", "new batch result"]);
});
test("model transport honors HTTP_PROXY and NO_PROXY", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (_, res) => sse(res, { role: "assistant", content: "transport verified" }, "stop"));
const target = new URL(fixture.url);
const tunnels = [];
const sockets = new Set();
const proxy = createServer();
proxy.on("connect", (req, socket, head) => {
tunnels.push(req.url);
assert.equal(req.url, target.host);
const upstream = connect(Number(target.port), target.hostname, () => {
socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
if (head.length) upstream.write(head);
socket.pipe(upstream).pipe(socket);
});
sockets.add(socket);
socket.on("close", () => { sockets.delete(socket); upstream.destroy(); });
socket.on("error", () => upstream.destroy());
upstream.on("close", () => socket.destroy());
upstream.on("error", () => socket.destroy());
});
proxy.listen(0, "127.0.0.1");
await once(proxy, "listening");
t.after(() => { for (const socket of sockets) socket.destroy(); proxy.close(); });
const proxyURL = "http://127.0.0.1:" + proxy.address().port;
const env = { ...fixtureEnv, HTTP_PROXY: proxyURL, http_proxy: proxyURL, NO_PROXY: "", no_proxy: "", NODE_USE_ENV_PROXY: "0" };
const req = request(fixture.url);
const throughProxy = await invoke(t, { ...req, generateOnly: true, history: [{ role: "user", content: req.message }] }, undefined, env);
assert.equal(throughProxy.result.response, "transport verified", throughProxy.result.error);
assert.deepEqual(tunnels, [target.host]);
const direct = await invoke(t, req, undefined, { ...env, NO_PROXY: target.hostname, no_proxy: target.hostname });
assert.equal(direct.result.response, "transport verified", direct.result.error);
assert.equal(fixture.requests.length, 2);
assert.deepEqual(tunnels, [target.host]);
});
test("cancel rejects a pending host tool and settles without another model call", { timeout: 30000 }, async t => {
@ -165,7 +212,7 @@ test("process loss preserves the session and marks uncertain tools without repla
});
const dir = await mkdtemp(join(tmpdir(), "csai-pi-crash-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const worker = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "ignore"] });
const worker = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "ignore"], env: fixtureEnv });
t.after(() => worker.kill());
const ended = once(worker, "exit");
const reader = new RecordReader();