Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

keep ipython kernel alive across compaction (#267)

ktbb6ede725142
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index fca24ca58b..72e0f1a035 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -417,6 +417,9 @@ interface RlmChildRun {
/** Standard thinking levels */
const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high"];
+/** Cap on the post-compaction kernel namespace probe so a wedged kernel can't stall recovery. */
+const KERNEL_STATE_LISTING_TIMEOUT_MS = 5000;
+
function noopRlmChildAbort(): void {}
function isRlmChildRunCancelled(run: RlmChildRun): boolean {
@@ -2731,8 +2734,56 @@ export class AgentSession {
return this.model ? (clampThinkingLevel(this.model, level) as ThinkingLevel) : "off";
}
- private async _restartIpythonKernelAfterCompaction(): Promise<void> {
- await this._ipythonKernelProvisioner?.restart();
+ // Added to history (not a nextTurn message) so it also reaches the continue()-driven
+ // auto-compaction resume, which never injects nextTurn messages.
+ private async _notifyKernelStateAfterCompaction(): Promise<void> {
+ const provisioner = this._ipythonKernelProvisioner;
+ // No kernel means no state to remind about; only stay silent in that case.
+ if (!provisioner?.hasRunningKernel) return;
+ // Bound the probe so a wedged kernel can't stall recovery, and abort it on timeout so
+ // the kernel's serialized execution queue isn't left occupied by a never-resolving cell.
+ const abort = new AbortController();
+ const timer = setTimeout(() => abort.abort(), KERNEL_STATE_LISTING_TIMEOUT_MS);
+ if (typeof timer === "object" && "unref" in timer) timer.unref();
+ let names: string[] | null;
+ try {
+ names = await provisioner.listNamespaceNames(abort.signal).catch(() => null);
+ } finally {
+ clearTimeout(timer);
+ }
+ // null is a listing failure/timeout; only claim state survived if the kernel is still up
+ // (it may have died in the window since the check above).
+ if (names === null && !provisioner.hasRunningKernel) return;
+ const detail =
+ names === null
+ ? ""
+ : names.length > 0
+ ? ` These names are still defined: ${names.join(", ")}.`
+ : " You have not defined any names yet.";
+ const content = [
+ "<ipython_state>",
+ `Your IPython kernel persisted through compaction; all variables, imports, and helpers you defined remain available.${detail}`,
+ "</ipython_state>",
+ ].join("\n");
+ const message = {
+ role: "custom" as const,
+ customType: "ipython_state",
+ content,
+ display: false,
+ timestamp: Date.now(),
+ } satisfies CustomMessage;
+ // Insert before a trailing assistant error so overflow-retry cleanup can still strip it.
+ const messages = this.agent.state.messages;
+ const last = messages[messages.length - 1];
+ const insertBeforeError = last?.role === "assistant" && (last as AssistantMessage).stopReason === "error";
+ if (insertBeforeError) {
+ messages.splice(messages.length - 1, 0, message);
+ } else {
+ messages.push(message);
+ }
+ this.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, undefined);
+ this._emit({ type: "message_start", message });
+ this._emit({ type: "message_end", message });
}
/**
@@ -2902,7 +2953,7 @@ export class AgentSession {
fromExtension,
});
}
- await this._restartIpythonKernelAfterCompaction();
+ await this._notifyKernelStateAfterCompaction();
const compactionResult = {
summary,
@@ -3240,7 +3291,7 @@ export class AgentSession {
fromExtension,
});
}
- await this._restartIpythonKernelAfterCompaction();
+ await this._notifyKernelStateAfterCompaction();
const result: CompactionResult = {
summary,
diff --git a/packages/coding-agent/src/core/compaction/compaction.ts b/packages/coding-agent/src/core/compaction/compaction.ts
index 37248bb560..7c8e10c5ea 100644
--- a/packages/coding-agent/src/core/compaction/compaction.ts
+++ b/packages/coding-agent/src/core/compaction/compaction.ts
@@ -493,8 +493,8 @@ Use this EXACT format:
Keep each section concise. Preserve exact file paths, function names, and error messages.`;
-const KERNEL_RESTART_SUMMARY_WARNING =
- "Note: the IPython kernel will be restarted after this summary. Python variables, imports, and in-memory state will be wiped. Files on disk are preserved — capture file paths and what they contain so the next agent can resume without redoing work.";
+const KERNEL_PERSIST_SUMMARY_NOTE =
+ "Note: the IPython kernel keeps running after this summary — every Python variable, import, and helper you defined stays available. The cells that defined them won't appear above, so record in the summary any names worth remembering so you reuse them instead of redefining them.";
const UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
@@ -537,14 +537,14 @@ Keep each section concise. Preserve exact file paths, function names, and error
/**
* Build the instruction portion of the summarization prompt: the initial or
- * update template, optional user instructions, and the kernel restart warning.
+ * update template, optional user instructions, and the kernel persistence note.
*/
export function buildSummarizationPrompt(customInstructions?: string, previousSummary?: string): string {
let basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;
if (customInstructions) {
basePrompt += `\n\n<user-instructions>\nThe user provided these instructions for this summary. Follow them with high priority while keeping the section format above: emphasize what they ask to focus on, and preserve verbatim anything they ask to remember.\n${customInstructions}\n</user-instructions>`;
}
- return `${basePrompt}\n\n${KERNEL_RESTART_SUMMARY_WARNING}`;
+ return `${basePrompt}\n\n${KERNEL_PERSIST_SUMMARY_NOTE}`;
}
/**
diff --git a/packages/coding-agent/src/core/kernel/index.ts b/packages/coding-agent/src/core/kernel/index.ts
index b065b920ba..d7dcee0413 100644
--- a/packages/coding-agent/src/core/kernel/index.ts
+++ b/packages/coding-agent/src/core/kernel/index.ts
@@ -10,9 +10,11 @@ import { v4 as uuid } from "uuid";
import { Dealer, Subscriber } from "zeromq";
import { ensureKernelPython, type KernelBootstrapProgressHandler, type KernelPythonSkill } from "./bootstrap.js";
import {
+ buildListNamesCode,
buildRestoreCode,
buildSnapshotCode,
DEFAULT_SNAPSHOT_MAX_BYTES,
+ parseListNamesResult,
parseRestoreResult,
parseSnapshotResult,
type RestoreResult,
@@ -82,6 +84,8 @@ export interface ExecuteOptions {
onStream?: (chunk: string, name: "stdout" | "stderr") => void;
/** Cap stdout / stderr / result at this many characters. Default 65536. */
maxOutputChars?: number;
+ /** Synthetic host cell (snapshot/restore/list); excluded from lastCellCode attribution. */
+ internal?: boolean;
}
/** MIME tag the `edit` skill emits diff payloads under, via `display_data`. */
@@ -653,7 +657,9 @@ export class KernelManager {
reject: result.reject,
};
this.activeExecution = execution;
- this.lastCellCode = code;
+ if (!opts.internal) {
+ this.lastCellCode = code;
+ }
try {
await shell.send(encode(msg, conn.key));
} catch (error) {
@@ -986,7 +992,7 @@ export class KernelManager {
if (!cfg || !this.isRunning) return null;
const code = buildSnapshotCode(cfg.path, cfg.manifestPath, cfg.maxBytes ?? DEFAULT_SNAPSHOT_MAX_BYTES);
try {
- const r = await this.enqueueExecute(code, { maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS });
+ const r = await this.enqueueExecute(code, { maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS, internal: true });
if (r.status !== "ok") {
this.appendKernelDiagnostic(`state snapshot failed: ${r.error?.evalue ?? r.stderr}`);
return null;
@@ -1008,7 +1014,7 @@ export class KernelManager {
if (!cfg) return null;
const code = buildRestoreCode(cfg.path);
try {
- const r = await this.enqueueExecute(code, { maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS });
+ const r = await this.enqueueExecute(code, { maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS, internal: true });
if (r.status !== "ok") {
this.appendKernelDiagnostic(`state restore failed: ${r.error?.evalue ?? r.stderr}`);
return null;
@@ -1020,6 +1026,26 @@ export class KernelManager {
}
}
+ /** Live user-defined top-level names, or null if the kernel isn't running. Never throws. */
+ async listNamespaceNames(signal?: AbortSignal): Promise<string[] | null> {
+ if (!this.isRunning) return null;
+ try {
+ const r = await this.enqueueExecute(buildListNamesCode(), {
+ maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS,
+ internal: true,
+ signal,
+ });
+ if (r.status !== "ok") {
+ this.appendKernelDiagnostic(`namespace listing failed: ${r.error?.evalue ?? r.stderr}`);
+ return null;
+ }
+ return parseListNamesResult(r.stdout);
+ } catch (error) {
+ this.appendKernelDiagnostic(`namespace listing error: ${errorMessage(error)}`);
+ return null;
+ }
+ }
+
private scheduleSnapshot(): void {
const cfg = this.options.snapshot;
if (!cfg) return;
diff --git a/packages/coding-agent/src/core/kernel/state-snapshot.ts b/packages/coding-agent/src/core/kernel/state-snapshot.ts
index bfe0911ce4..17032ba9cb 100644
--- a/packages/coding-agent/src/core/kernel/state-snapshot.ts
+++ b/packages/coding-agent/src/core/kernel/state-snapshot.ts
@@ -193,6 +193,39 @@ finally:
`.trim();
}
+/** Marker-line list of live user-defined names, filtered like the snapshot. Never raises. */
+export function buildListNamesCode(): string {
+ return `
+def _prime_agent_list_state_names():
+ import builtins as _b, json
+ ip = None
+ try:
+ ip = get_ipython() # noqa: F821 (injected by IPython)
+ except _b.Exception:
+ ip = None
+ ns = ip.user_ns if ip is not None else _b.globals()
+ hidden = _b.set(_b.getattr(ip, "user_ns_hidden", {}) or {}) if ip is not None else _b.set()
+ always_skip = {"rlm", "In", "Out", "get_ipython", "exit", "quit", "open"}
+ names = []
+ for name in _b.list(ns.keys()):
+ if name.startswith("_") or name in hidden or name in always_skip:
+ continue
+ names.append(name)
+ _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"names": _b.sorted(names)}))
+
+
+try:
+ _prime_agent_list_state_names()
+finally:
+ del _prime_agent_list_state_names
+`.trim();
+}
+
+interface RawListNames {
+ names?: unknown;
+ error?: unknown;
+}
+
interface RawSnapshot {
saved?: unknown;
skipped?: unknown;
@@ -255,3 +288,10 @@ export function parseRestoreResult(stdout: string, path: string): RestoreResult
path,
};
}
+
+/** Sorted list of live user-defined names, or null if the marker was absent/invalid. */
+export function parseListNamesResult(stdout: string): string[] | null {
+ const raw = parseMarkerLine<RawListNames>(stdout);
+ if (!raw || raw.error) return null;
+ return asStringArray(raw.names);
+}
diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.ts
index 65bf7c5e48..be142b9139 100644
--- a/packages/coding-agent/src/core/tools/ipython.ts
+++ b/packages/coding-agent/src/core/tools/ipython.ts
@@ -1,6 +1,5 @@
// TODO: reconsider whether the persistent kernel is needed once RLM-1 weights land.
import { existsSync } from "node:fs";
-import { rm } from "node:fs/promises";
import type { AgentTool } from "@earendil-works/pi-agent-core";
import { type Static, Type } from "typebox";
import type { ToolDefinition } from "../extensions/types.js";
@@ -149,7 +148,7 @@ export interface IpythonToolOptions {
/** Resolves before this kernel starts — e.g. the previous provisioner's dispose, so a
* /reload's old-kernel snapshot flush can't race the new kernel's restore. */
readyGate?: Promise<unknown>;
- /** Filled after the first kernel start so the owning session can restart it after compaction. */
+ /** Filled with the live KernelManager after the first kernel start; cleared on construction. */
kernelManagerRef?: { current?: KernelManager };
/**
* Fires once per kernel start when a previous session's namespace was revived
@@ -198,26 +197,15 @@ export class IpythonKernelProvisioner {
void this.ensure().catch(() => {});
}
- /** Restart the kernel if one is running (e.g. after compaction). */
- async restart(): Promise<void> {
- try {
- // Await any in-flight startup first, so we restart a fully-started kernel and
- // delete the snapshot after (not during) a concurrent restore.
- const m = this.startedManager ?? (await this.managerPromise?.catch(() => undefined));
- await m?.restart();
- } finally {
- // Compaction deliberately wipes the namespace and tells the model so. Drop the
- // stale on-disk snapshot too — even if the restart threw — so a later resume
- // doesn't revive state the model was told is gone (a fresh cell re-snapshots).
- this._lastRestore = undefined;
- const dir = this.options?.snapshotDir;
- if (dir) {
- await Promise.allSettled([
- rm(snapshotPathIn(dir), { force: true }),
- rm(manifestPathIn(dir), { force: true }),
- ]);
- }
- }
+ /** Whether a kernel has finished starting and is currently running. */
+ get hasRunningKernel(): boolean {
+ return this.startedManager?.isRunning ?? false;
+ }
+
+ /** Live user-defined names in the kernel namespace, or null if listing failed / no kernel. */
+ async listNamespaceNames(signal?: AbortSignal): Promise<string[] | null> {
+ const m = this.startedManager ?? (await this.managerPromise?.catch(() => undefined));
+ return (await m?.listNamespaceNames(signal)) ?? null;
}
/** Dispose the kernel owned by this provisioner, including one still starting up. */
diff --git a/packages/coding-agent/test/compaction.test.ts b/packages/coding-agent/test/compaction.test.ts
index dd5359720b..0bd0a204ac 100644
--- a/packages/coding-agent/test/compaction.test.ts
+++ b/packages/coding-agent/test/compaction.test.ts
@@ -180,10 +180,12 @@ describe("buildSummarizationPrompt", () => {
const prompt = buildSummarizationPrompt();
expect(prompt).not.toContain("<user-instructions>");
expect(prompt).toContain("## Goal");
- expect(prompt).toContain("IPython kernel");
+ // The kernel keeps running across compaction — the note must not claim a wipe.
+ expect(prompt).toContain("IPython kernel keeps running");
+ expect(prompt).not.toMatch(/wiped|restarted/);
});
- it("includes user instructions in a delimited block before the kernel warning", () => {
+ it("includes user instructions in a delimited block before the kernel note", () => {
const prompt = buildSummarizationPrompt("focus on the auth refactor, remember the migration command");
expect(prompt).toContain("<user-instructions>");
expect(prompt).toContain("focus on the auth refactor, remember the migration command");
diff --git a/packages/coding-agent/test/ipython-provisioner.test.ts b/packages/coding-agent/test/ipython-provisioner.test.ts
index ca124bd042..b4a903799e 100644
--- a/packages/coding-agent/test/ipython-provisioner.test.ts
+++ b/packages/coding-agent/test/ipython-provisioner.test.ts
@@ -114,7 +114,12 @@ describe("IpythonKernelProvisioner", () => {
expect(countRuns()).toBe(1);
});
- it("restart() drops the on-disk snapshot so a compaction wipe isn't revived on resume", async () => {
+ it("listNamespaceNames() returns null when no kernel is running", async () => {
+ const provisioner = new IpythonKernelProvisioner(tempDir, {});
+ expect(await provisioner.listNamespaceNames()).toBeNull();
+ });
+
+ it("does not delete the on-disk snapshot (the kernel survives compaction)", async () => {
const snapshotDir = join(tempDir, "artifacts");
const provisioner = new IpythonKernelProvisioner(tempDir, { snapshotDir });
const dill = join(snapshotDir, "kernel-state.dill");
@@ -123,10 +128,11 @@ describe("IpythonKernelProvisioner", () => {
writeFileSync(dill, "payload");
writeFileSync(manifest, "{}");
- await provisioner.restart();
+ // listing the namespace must never touch the on-disk snapshot
+ await provisioner.listNamespaceNames();
- expect(existsSync(dill)).toBe(false);
- expect(existsSync(manifest)).toBe(false);
+ expect(existsSync(dill)).toBe(true);
+ expect(existsSync(manifest)).toBe(true);
});
});
diff --git a/packages/coding-agent/test/kernel-state-roundtrip.test.ts b/packages/coding-agent/test/kernel-state-roundtrip.test.ts
index b308010b8a..d7164571a2 100644
--- a/packages/coding-agent/test/kernel-state-roundtrip.test.ts
+++ b/packages/coding-agent/test/kernel-state-roundtrip.test.ts
@@ -141,6 +141,24 @@ describeIfKernel("kernel state snapshot round-trip (real kernel)", () => {
}
}, 60_000);
+ it("lists live user-defined names, filtering internals and live handles", async () => {
+ const listDir = mkdtempSync(join(tmpdir(), "prime-agent-state-list-"));
+ const manager = new KernelManager({ python: python as string, cwd: listDir });
+ try {
+ // A fresh, unstarted kernel reports no names.
+ expect(await manager.listNamespaceNames()).toBeNull();
+ await manager.execute("alpha = 1\ndef helper(n):\n return n\n_hidden = 2\nrlm = object()");
+ const names = await manager.listNamespaceNames();
+ expect(names).toEqual(expect.arrayContaining(["alpha", "helper"]));
+ // Underscore-prefixed names and the live rlm handle must be filtered out.
+ expect(names).not.toContain("_hidden");
+ expect(names).not.toContain("rlm");
+ } finally {
+ await manager.dispose();
+ rmSync(listDir, { recursive: true, force: true });
+ }
+ }, 60_000);
+
it("auto-snapshots after a successful execution (debounced)", async () => {
const autoDir = mkdtempSync(join(tmpdir(), "prime-agent-state-auto-"));
const autoPath = join(autoDir, "auto.dill");