Skip to content

armgit / pibot

Public Imported from GitHub
0

Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.

perf(agent): pre-read session files off the event loop and time each session-open phase

leen.zhou7ebe78e1a2c4
diff --git a/packages/agent/src/core/types.ts b/packages/agent/src/core/types.ts
index 2cad140..210f11c 100644
--- a/packages/agent/src/core/types.ts
+++ b/packages/agent/src/core/types.ts
@@ -55,6 +55,7 @@ export interface OpenSessionOptions {
* step that held the thread. Names are fixed; nothing about the session is passed.
*/
phase?(name: "runtime" | "model" | "session_load" | "extensions" | "create" | "bind"): void;
+ phaseTiming?(name: string, elapsedMs: number): void;
/** The Bot's enabled skills, listed after the system prompt. */
skills?: { entries: SkillPromptEntry[]; language: "zh" | "en" };
/**
diff --git a/packages/agent/src/runtime/runtime-parts/runtime-session.ts b/packages/agent/src/runtime/runtime-parts/runtime-session.ts
index 6918493..15cc9d2 100644
--- a/packages/agent/src/runtime/runtime-parts/runtime-session.ts
+++ b/packages/agent/src/runtime/runtime-parts/runtime-session.ts
@@ -1,3 +1,4 @@
+import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { sanitizeBrainEnv } from "../../core/env.ts";
import { AgentError, mapAgentError } from "../../core/errors.ts";
@@ -22,6 +23,17 @@ import type { RuntimeContext } from "../runtime.ts";
import { skillsPrompt } from "../skills-prompt.ts";
import { toolVersion } from "../tool-identity.ts";
import { modelInfo, sessionPaths } from "./runtime-shared.ts";
+
+async function warmSessionFile(path: string, signal?: AbortSignal) {
+ const deadline = AbortSignal.timeout(15_000);
+ const combined = signal ? AbortSignal.any([signal, deadline]) : deadline;
+ combined.throwIfAborted();
+ // pi still owns parsing and persistence. This read moves disk and antivirus work before the
+ // synchronous SDK call, so the common cache-hit path does not wait on storage.
+ await readFile(path, { signal: combined });
+ combined.throwIfAborted();
+}
+
export function createSessionOperations({
dataDir,
checkpointCache,
@@ -40,9 +52,20 @@ export function createSessionOperations({
throw new AgentError("chatgpt_reconnect_required");
try {
opts.signal?.throwIfAborted();
- opts.phase?.("runtime");
+ type OpenPhase = "runtime" | "model" | "session_load" | "extensions" | "create" | "bind";
+ let activePhase: OpenPhase = "runtime";
+ let phaseStarted = performance.now();
+ const phase = (next: OpenPhase) => {
+ if (next !== activePhase) {
+ opts.phaseTiming?.(activePhase, Math.round(performance.now() - phaseStarted));
+ activePhase = next;
+ phaseStarted = performance.now();
+ }
+ opts.phase?.(next);
+ };
+ phase("runtime");
const { pi, runtime, custom } = await buildRuntime();
- opts.phase?.("model");
+ phase("model");
opts.signal?.throwIfAborted();
// A workflow's `cheap` tier runs on the auxiliary model when one is usable.
const model =
@@ -61,8 +84,9 @@ export function createSessionOperations({
opts.signal?.throwIfAborted();
const sessionFile = await sessionPaths(dataDir, opts);
opts.signal?.throwIfAborted();
+ phase("session_load");
+ if (sessionFile) await warmSessionFile(sessionFile, opts.signal);
// pi reads and parses the whole JSONL synchronously here; it grows with the session.
- opts.phase?.("session_load");
const manager = sessionFile
? pi.SessionManager.open(sessionFile, opts.sessionDir, opts.homeDir)
: pi.SessionManager.create(opts.homeDir, opts.sessionDir);
@@ -254,7 +278,7 @@ export function createSessionOperations({
entries: () => manager.getEntries(),
};
if (opts.context && !opts.localTools) throw new AgentError("internal");
- opts.phase?.("extensions");
+ phase("extensions");
const extensions = await loadLocalExtensions(
opts.homeDir,
join(dataDir, "pi"),
@@ -276,7 +300,7 @@ export function createSessionOperations({
if (compaction)
compaction.estimateHistory = (messages) =>
historyTokens(messages, extensions.loadout?.synchronize());
- opts.phase?.("create");
+ phase("create");
const { session } = await pi.createAgentSession({
cwd: opts.homeDir,
agentDir: join(dataDir, "pi"),
@@ -300,12 +324,13 @@ export function createSessionOperations({
// A restored JSONL can name another model. Explicit caller selection wins.
try {
opts.signal?.throwIfAborted();
- opts.phase?.("bind");
+ phase("bind");
if (opts.localTools) await session.bindExtensions({});
// Tool groups the transcript still declares stay loaded when still allowed.
extensions.loadout?.reset(session.messages);
await session.setModel(model);
session.setThinkingLevel(opts.thinkingLevel);
+ opts.phaseTiming?.(activePhase, Math.round(performance.now() - phaseStarted));
} catch (error) {
session.dispose();
throw error;
diff --git a/packages/brain/src/index.ts b/packages/brain/src/index.ts
index 4f691e1..15d7b8b 100644
--- a/packages/brain/src/index.ts
+++ b/packages/brain/src/index.ts
@@ -662,12 +662,29 @@ export async function startBrain(opts: {
...contentRuntime,
async openSession(input) {
loopWatch?.mark("open.start");
+ const openedAt = performance.now();
await waitForSessionRecovery(input.signal);
const session = await contentRuntime.openSession({
...input,
phase: (name) => loopWatch?.mark(`open.${name}`),
+ phaseTiming: (phase, elapsedMs) =>
+ logger.info(
+ JSON.stringify({
+ module: "brain",
+ event: "session_open_phase",
+ phase,
+ elapsedMs,
+ }),
+ ),
});
loopWatch?.mark("open.done");
+ logger.info(
+ JSON.stringify({
+ module: "brain",
+ event: "session_open_total",
+ elapsedMs: Math.round(performance.now() - openedAt),
+ }),
+ );
return session;
},
...(compactHistory && {
diff --git a/tools/dev/pi-patch-upgrade.md b/tools/dev/pi-patch-upgrade.md
index 605249d..91df0c6 100644
--- a/tools/dev/pi-patch-upgrade.md
+++ b/tools/dev/pi-patch-upgrade.md
@@ -25,6 +25,10 @@ Pi Bot patches two pi packages. Both patches are meant to be **add-only** for `p
If upstream ships a headless entry, switch
`packages/agent/src/runtime/pi-sdk.ts` to it and drop the patch.
+An add-only async session-open helper was considered and not added: a 50 MB session opens in about a
+third of a second, so parsing is not where sessions stall. If it is ever needed, prefer an upstream
+constructor that accepts parsed entries and a persistence path, and port it with every pi upgrade.
+
版本窄入口不得重导出 `config.js`(它会在环境清理前读包路径配置)。升级时 `dist/version.js` 常量必须与锁定依赖的 package.json.version 相同,d.ts 保持 string;同时核对 diff 不含 deleted file mode、重命名或任何原有代码删除,不能只数以减号开头的内容行。
## 无状态 context-helpers 的生成出处