refactor(pi): use native session storage and steering

This commit is contained in:
Sycun 2026-11-13 11:30:44 +08:00
parent b165fb4cf2
commit 4584f09cd0
4 changed files with 71 additions and 38 deletions

View File

@ -2,6 +2,8 @@
CyberStrikeAI uses Pi 1.5.2 as its only runtime. Go owns business state, permissions, MCP execution, evidence, and delivery checks; an isolated Node worker hosts the Pi SDK.
Prefer public APIs from the pinned Pi SDK. Add host or worker logic where project permissions, business records, or compatibility require it.
## Build
Node.js >=22.19 and the Go version in go.mod are required:
@ -23,7 +25,9 @@ The model worker uses HTTP/1.1 and respects the service's `HTTP_PROXY`, `HTTPS_P
Deleting a conversation turn removes all of its persisted Pi mode/child sessions and advances a database revision; the next request imports the remaining database history. A running conversation must be stopped before deleting a turn. Session roots are retained in the database across configuration changes and restarts so deletion cleans both old and new locations.
Chat agents, specialists and workflow Agent nodes use Pi. Large catalogs can use native tool search. Conversation task boards remain compatible with the existing UI.
Pi's `SessionManager` opens `session.jsonl` directly for new conversations. Existing conversations keep using the file referenced by their `current-session` pointer, preserving saved evidence paths. If rolled back to an older worker, it rebuilds the context for new-format sessions from the history supplied by the host without loading their Pi compaction records.
Chat agents, specialists and workflow Agent nodes use Pi. User steering goes through Pi's native queue. 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

@ -2,6 +2,8 @@
CyberStrikeAI 仅使用 Pi 1.5.2(`@earendil-works/pi-coding-agent`、`pi-ai`),Go 保留业务、权限、工具执行和证据管理。
维护时优先使用当前锁定版本的 Pi SDK 公共接口。只有需要项目权限、业务记录或兼容行为时,才在宿主或 Worker 增加逻辑。
## 构建与使用
需要 Go(版本见 go.mod)和 Node.js >=22.19。
@ -32,7 +34,7 @@ agent_runtime:
## 执行边界
- 聊天、机器人、批量任务、工作流 Agent 节点通过统一调度入口进入 Pi。正式单代理路由为 `/api/agent`、模式值为 `single`;旧路由与模式只做输入兼容,执行始终使用 Pi。
- Go 管理每次调用的 Worker,支持流式事件、工具回调、补充指令与取消;同一进程中的相同会话存储串行访问,不同会话独立运行。
- Go 管理每次调用的 Worker,转发流式事件和工具回调。补充指令进入 Pi 原生队列,取消时 Pi 停止模型请求,Go 停止宿主工具。同一进程中的相同会话存储串行访问,不同会话独立运行。
- Worker 使用显式模型、内存凭据和资源加载器,不自动发现个人 Pi 配置、全局插件或默认文件/Shell 工具。
- 工具较多时使用 Pi 原生 tool_search 按需加载,减少模型一次接收的工具定义。TaskCreate/Update/Get/List 和 write_todos 继续写入现有对话任务板。
- MCP、文件和 Shell 工具回到 Go,经角色过滤、HITL 和现有执行监控处理。子代理工具集合受主代理集合约束。
@ -42,7 +44,8 @@ agent_runtime:
## 数据与兼容
- Pi Session 保存模型会话及压缩记录;SQLite 保存业务状态、工具记录和交付证据。删除轮次时清除该对话所有模式及子代理的 Pi 会话,并递增数据库会话版本;后续请求从剩余消息重建上下文,旧 Worker 迟到写回的文件不会被恢复。运行中的任务须先停止再删轮次。
- Pi 的 `SessionManager` 直接读写模型会话及压缩记录。新会话使用固定的 `session.jsonl`,已有会话沿用 `current-session` 指向的原文件,已有证据路径仍可使用。回滚到旧 Worker 时,新格式会话的上下文会从宿主传入的历史重建,原有 Pi 压缩记录不会加载。
- SQLite 保存业务状态、工具记录和交付证据。删除轮次时清除该对话所有模式及子代理的 Pi 会话,并递增数据库会话版本。后续请求从剩余消息重建上下文,旧 Worker 迟到写回的文件不会被恢复。运行中的任务须先停止再删轮次。
- 会话目录变更会在数据库保留历次目录,重启后删除对话或轮次仍会清理新旧目录;清理失败不会报告删除成功。
- 每次实际调用都有独立的运行期传输 ID;模型复用自身的 tool-call ID 不会吞掉新调用。同一个传输 ID 重发时复用已完成结果;不同参数复用同一个传输 ID 会被拒绝。
- 进程中断后,未提交结果的调用标记为结果不确定。系统不把它自动当成成功,也不直接重放它;继续前须核对执行记录。这不是跨所有外部系统的“恰好一次”保证。

View File

@ -1,4 +1,4 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { InMemoryCredentialStore, type Model, type Api, type Message } from "@earendil-works/pi-ai";
@ -38,7 +38,7 @@ let canceled = false;
let activeRunId = "";
let toolSequence = 0;
const generationAbort = new AbortController();
const queuedSteering: string[] = [];
let steeringBeforeSession: string[] | undefined = [];
const pending = new Map<string, { resolve: (r: ToolReply) => void; reject: (e: Error) => void }>();
const scratch = mkdtempSync(join(process.env.CYBERSTRIKE_PI_TMP_PARENT || tmpdir(), "cyberstrike-pi-"));
@ -160,13 +160,20 @@ function pairToolResults(messages: readonly Message[]): Message[] {
return paired;
}
function publishSession(manager: SessionManager, dir?: string): void {
const path = manager.getSessionFile();
if (!dir || !path || !existsSync(path)) return;
const file = path.split(/[\\/]/).pop()!;
const pointer = join(dir, "current-session");
writeFileSync(pointer + ".tmp", file, { mode: 0o600 });
renameSync(pointer + ".tmp", pointer);
function openSession(workingDir: string, sessionDir?: string): SessionManager {
if (!sessionDir) return SessionManager.inMemory(workingDir);
const dir = resolve(sessionDir);
mkdirSync(dir, { recursive: true, mode: 0o700 });
let file = "session.jsonl";
// Earlier workers selected a timestamped Pi file via this pointer. Keep
// opening that file in place so existing evidence links remain valid.
try {
file = readFileSync(join(dir, "current-session"), "utf8").trim();
if (!/^\d{4}.*\.jsonl$/.test(file) || file.includes("/") || file.includes("\\")) throw new Error("Invalid session pointer");
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
return SessionManager.open(join(dir, file), dir, workingDir);
}
async function run(req: RunRequest): Promise<void> {
@ -244,23 +251,8 @@ async function run(req: RunRequest): Promise<void> {
directResult = { response: answer.content.filter(b => b.type === "text").map(b => b.text).join(""), history: exportHistory([answer]), totalTokens: answer.usage.totalTokens };
return;
}
if (req.sessionDir) {
const dir = resolve(req.sessionDir);
mkdirSync(dir, { recursive: true, mode: 0o700 });
const pointer = join(dir, "current-session");
if (existsSync(pointer)) {
const file = readFileSync(pointer, "utf8").trim();
if (!/^\d{4}.*\.jsonl$/.test(file) || file.includes("/") || file.includes("\\")) throw new Error("Invalid session pointer");
manager = SessionManager.open(join(dir, file), dir, workingDir);
} else {
manager = SessionManager.create(workingDir, dir);
importHistory(manager, req.history ?? [], req.model);
}
// Session files materialize when Pi appends its first entry; the pointer is published after prompting.
} else {
manager = SessionManager.inMemory(workingDir);
importHistory(manager, req.history ?? [], req.model);
}
manager = openSession(workingDir, req.sessionDir);
if (manager.getEntryCount() === 0) importHistory(manager, req.history ?? [], req.model);
repairInterruptedCalls(manager);
const searchEnabled = req.toolSearch === true && names.length >= (req.toolSearchMinTools || 20) && !names.includes("tool_search");
const always = new Set(["task", "exit", "transfer_to_agent", "write_todos", "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "skill", "read_file", "execute", "wait_tool_execution", "get_tool_execution", ...(req.alwaysVisibleTools ?? [])]);
@ -283,7 +275,6 @@ async function run(req: RunRequest): Promise<void> {
}));
if (searchEnabled) await session.bindExtensions({});
session.agent.toolExecution = "sequential";
publishSession(manager, req.sessionDir);
let turns = 0;
const previousFinish = session.agent.finishTurn;
session.agent.finishTurn = async (turn, signal) => {
@ -293,8 +284,6 @@ async function run(req: RunRequest): Promise<void> {
};
session.subscribe(event => {
const e = event as any;
if (e.type === "agent_start") for (const note of queuedSteering.splice(0)) void session?.steer(note).catch(fatal);
if (e.type === "message_end") publishSession(manager!, req.sessionDir);
let data: unknown = e;
if (e.type === "compaction_end") data = { ...e, sessionFile: manager?.getSessionFile(), sessionEntryId: manager?.getLeafId() };
if (e.type === "message_update") {
@ -304,12 +293,14 @@ async function run(req: RunRequest): Promise<void> {
if (e.type === "agent_end") data = {};
void send({ type: "event", event: { type: e.type, data } }).catch(() => session?.abort());
});
// Pi accepts steering before prompt() and drains it during the run.
for (const note of steeringBeforeSession ?? []) await session.steer(note);
steeringBeforeSession = undefined;
if (canceled) throw new Error("Run canceled before start");
await session.prompt(req.message, { expandPromptTemplates: false });
const last = [...session.messages].reverse().find(m => m.role === "assistant") as any;
if (canceled || last?.stopReason === "aborted") status = "canceled";
else if (last?.stopReason === "error") { status = "failed"; failure = last.errorMessage || "Model request failed"; }
publishSession(manager, req.sessionDir);
} catch (error) {
status = canceled ? "canceled" : "failed";
failure = error instanceof Error ? error.message : String(error);
@ -339,8 +330,8 @@ async function command(record: any): Promise<void> {
await session?.abort();
} else if (record.type === "steer") {
if (canceled || typeof record.message !== "string") throw new Error("Invalid steering request");
if (!session || !session.isStreaming) queuedSteering.push(record.message);
else await session.steer(record.message);
if (steeringBeforeSession) steeringBeforeSession.push(record.message);
else await session!.steer(record.message);
} else throw new Error("Unknown protocol command");
}

View File

@ -4,9 +4,10 @@ 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";
import { mkdtemp, rm, readFile, readdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { basename, join } from "node:path";
import { SessionManager } from "@earendil-works/pi-coding-agent";
import { RecordReader } from "../dist/protocol.js";
test("JSONL preserves Unicode separators and fragmented UTF-8", () => {
@ -73,6 +74,11 @@ function request(url, sessionDir) {
maxTurns: 8, sessionDir };
}
function userTexts(body) {
return body.messages.filter(m => m.role === "user").map(m =>
typeof m.content === "string" ? m.content : m.content.map(block => block.text).join(""));
}
test("real Pi SDK streams, invokes only host tools and restores persisted sessions", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (body, res, count) => {
if (count === 1) sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "call-1", type: "function", function: { name: "echo", arguments: '{"text":"hello"}' } }] }, "tool_calls");
@ -96,11 +102,40 @@ test("real Pi SDK streams, invokes only host tools and restores persisted sessio
assert.ok(fixture.requests[1].messages.some(m => m.role === "tool" && m.content === "hello"));
assert.ok(first.records.some(r => r.event?.type === "message_update"));
assert.ok(first.records.filter(r => r.event?.type === "message_update").every(r => !Object.hasOwn(r.event.data.assistantMessageEvent, "partial")));
const second = await invoke(t, { ...request(fixture.url, dir), runId: "run-2", message: "summarize prior result" });
const second = await invoke(t, { ...request(fixture.url, dir), runId: "run-2", message: "summarize prior result", workingDir: tmpdir() });
assert.equal(second.result.status, "completed", second.result.error);
assert.equal(second.result.sessionFile, first.result.sessionFile);
assert.deepEqual(await readdir(dir), [basename(first.result.sessionFile)]);
assert.ok(fixture.requests[2].messages.some(m => m.role === "tool" && m.content === "hello"));
});
test("legacy Pi sessions resume in place without invalidating saved evidence paths", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (_, res) => sse(res, { role: "assistant", content: "resumed" }, "stop"));
const dir = await mkdtemp(join(tmpdir(), "csai-pi-legacy-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const legacy = SessionManager.create(process.cwd(), dir);
const entryId = legacy.appendMessage({ role: "user", content: "legacy conversation history", timestamp: Date.now() });
const path = legacy.getSessionFile();
await writeFile(join(dir, "current-session"), basename(path));
const { result } = await invoke(t, { ...request(fixture.url, dir), history: [{ role: "user", content: "database fallback" }] });
assert.equal(result.status, "completed", result.error);
assert.equal(result.sessionFile, path);
assert.ok(SessionManager.open(path).getEntry(entryId));
assert.deepEqual(userTexts(fixture.requests[0]), ["legacy conversation history", "echo hello"]);
});
test("Pi accepts steering while the worker is still preparing its session", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (_, res) => sse(res, { role: "assistant", content: "received" }, "stop"));
const req = request(fixture.url);
const { result } = await invoke(t, req, (r, send) => {
if (r.type === "ready") send({ type: "steer", message: "early steering" });
});
assert.equal(result.status, "completed", result.error);
assert.equal(fixture.requests.length, 1);
assert.deepEqual(userTexts(fixture.requests[0]), [req.message, "early steering"]);
});
test("OpenAI-compatible requests keep historical tool results in their own assistant batch", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (body, res) => {
let pending = new Set();