A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
Keep large IPython state from slowing later turns (#1540)
rasdani1663d443d54d
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex de4e082b73..032ea08b84 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,7 @@## [Unreleased]+- Fixed large IPython variables repeatedly slowing later turns by excluding them from persistent snapshots and removing them when context is compacted.- Fixed daemon socket paths being used verbatim in identity derivations: on supported platforms, `--daemon-socket` spellings differing only by duplicate or trailing slashes now normalize to one canonical path, so worker-descriptor namespaces, daemon log files, and persisted descriptors agree.- Added a `thinking` option to `rlm.run` for spawning subagents with an explicit reasoning level; invalid levels for the resolved child model fail spawn.- Changed opening the agents view (full or scoped) with a draft prompt to auto-stash the draft instead of refusing; the draft is restored into the editor when the session is reopened.diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 8a37cdc357..e50cc72768 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -6781,9 +6781,10 @@ export class AgentSession {return this.model ? (clampThinkingLevel(this.model, level) as ThinkingLevel) : "off";}- private async _notifyKernelStateAfterCompaction(): Promise<void> {+ private async _syncKernelStateAfterCompaction(): Promise<void> {const provisioner = this._ipythonKernelProvisioner;if (!provisioner?.hasRunningKernel) return;+ const pruned = await provisioner.pruneOversizedVariables().catch(() => null);const abort = new AbortController();const timer = setTimeout(() => abort.abort(), KERNEL_STATE_LISTING_TIMEOUT_MS);if (typeof timer === "object" && "unref" in timer) timer.unref();@@ -6800,9 +6801,13 @@ export class AgentSession {: names.length > 0? ` These names are still defined: ${names.join(", ")}.`: " You have not defined any names yet.";+ const prunedDetail =+ pruned && pruned.length > 0+ ? ` Variables above the per-variable snapshot limit were removed: ${pruned.join(", ")}.`+ : "";const content = ["<ipython_state>",- `Your IPython kernel persisted through compaction; all variables, imports, and helpers you defined remain available.${detail}`,+ `Your IPython kernel persisted through compaction; its remaining variables, imports, and helpers are still available.${prunedDetail}${detail}`,"</ipython_state>",].join("\n");const message = {@@ -7025,7 +7030,7 @@ export class AgentSession {fromExtension,});}- await this._notifyKernelStateAfterCompaction();+ await this._syncKernelStateAfterCompaction();await this._reapDeletedRlmSubagentRuntimesAfterCompaction();return { summary, firstKeptEntryId, tokensBefore, details };diff --git a/packages/coding-agent/src/core/kernel/index.ts b/packages/coding-agent/src/core/kernel/index.tsindex d62c30fb1b..43b73d2da3 100644--- a/packages/coding-agent/src/core/kernel/index.ts+++ b/packages/coding-agent/src/core/kernel/index.ts@@ -14,6 +14,7 @@ import {buildRestoreCode,buildSnapshotCode,DEFAULT_SNAPSHOT_MAX_BYTES,+ DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,parseListNamesResult,parseRestoreResult,parseSnapshotResult,@@ -37,6 +38,7 @@ const SNAPSHOT_MAX_OUTPUT_CHARS = 1_000_000;// Cap how long a graceful dispose waits on the final snapshot; the debounced// on-disk copy is the fallback if this is exceeded.const SNAPSHOT_DISPOSE_TIMEOUT_MS = 5000;+const SNAPSHOT_EXECUTION_TIMEOUT_MS = 5000;const KERNEL_ABORT_GRACE_MS = 1000;const KERNEL_BUSY_REUSE_WAIT_MS = 5000;const KERNEL_BUSY_INTERRUPT_INTERVAL_MS = 500;@@ -145,8 +147,10 @@ export interface KernelSnapshotConfig {path: string;/** Absolute path for the JSON manifest written alongside the payload. */manifestPath: string;- /** Skip variables (and abort the payload) above this many bytes. Default 256 MiB. */+ /** Maximum aggregate snapshot size. Default 256 MiB. */maxBytes?: number;+ /** Maximum serialized size of one variable. Default 16 MiB. */+ maxVariableBytes?: number;/** Debounce window for the auto-snapshot after a successful execution. Default 1500 ms. */debounceMs?: number;}@@ -879,7 +883,11 @@ export class KernelManager {}/** Queue and run a cell, serializing against all other executions. */- private async enqueueExecute(code: string, opts: ExecuteOptions): Promise<ExecuteResult> {+ private async enqueueExecute(+ code: string,+ opts: ExecuteOptions,+ executionTimeoutMs?: number,+ ): Promise<ExecuteResult> {if (opts.signal?.aborted) {return { stdout: "", stderr: "", status: "aborted", durationMs: 0 };}@@ -896,6 +904,7 @@ export class KernelManager {await prev;const started = Date.now();+ let executionTimeout: ReturnType<typeof globalThis.setTimeout> | undefined;try {await this.waitForActiveExecutionToClearForReuse(opts.signal);if (opts.signal?.aborted) {@@ -904,8 +913,17 @@ export class KernelManager {if ((this.state as string) === "shutdown") {throw new Error("Kernel has been shut down");}- return await this.executeInner(code, opts, started);+ if (executionTimeoutMs === undefined) {+ return await this.executeInner(code, opts, started);+ }++ const controller = new AbortController();+ executionTimeout = globalThis.setTimeout(() => controller.abort(), executionTimeoutMs);+ executionTimeout.unref?.();+ const signal = opts.signal ? AbortSignal.any([opts.signal, controller.signal]) : controller.signal;+ return await this.executeInner(code, { ...opts, signal }, started);} finally {+ if (executionTimeout) globalThis.clearTimeout(executionTimeout);resolveNext();}}@@ -1471,13 +1489,36 @@ export class KernelManager {* the kernel isn't running or no snapshot target was configured. Never throws.*/async snapshotState(): Promise<SnapshotResult | null> {+ return this.captureSnapshot();+ }++ /** Persist the namespace, then remove variables above the per-variable cap. */+ async pruneOversizedVariables(): Promise<SnapshotResult | null> {+ return this.captureSnapshot({ executionTimeoutMs: SNAPSHOT_EXECUTION_TIMEOUT_MS, pruneOversized: true });+ }++ private async captureSnapshot(+ options: { executionTimeoutMs?: number; pruneOversized?: boolean } = {},+ ): Promise<SnapshotResult | null> {const cfg = this.options.snapshot;if (!cfg || !this.isRunning) return null;- const code = buildSnapshotCode(cfg.path, cfg.manifestPath, cfg.maxBytes ?? DEFAULT_SNAPSHOT_MAX_BYTES);+ const code = buildSnapshotCode(+ cfg.path,+ cfg.manifestPath,+ cfg.maxBytes ?? DEFAULT_SNAPSHOT_MAX_BYTES,+ cfg.maxVariableBytes ?? DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,+ options.pruneOversized,+ );try {- const r = await this.enqueueExecute(code, { maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS, internal: true });+ const r = await this.enqueueExecute(+ code,+ { maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS, internal: true },+ options.executionTimeoutMs,+ );if (r.status !== "ok") {- this.appendKernelDiagnostic(`state snapshot failed: ${r.error?.evalue ?? r.stderr}`);+ this.appendKernelDiagnostic(+ `state snapshot ${r.status === "aborted" ? "timed out" : "failed"}: ${r.error?.evalue ?? r.stderr}`,+ );return null;}return parseSnapshotResult(r.stdout, cfg.path);@@ -1535,7 +1576,7 @@ export class KernelManager {if (this.snapshotTimer) clearTimeout(this.snapshotTimer);this.snapshotTimer = globalThis.setTimeout(() => {this.snapshotTimer = undefined;- void this.snapshotState();+ void this.captureSnapshot({ executionTimeoutMs: SNAPSHOT_EXECUTION_TIMEOUT_MS });}, cfg.debounceMs ?? DEFAULT_SNAPSHOT_DEBOUNCE_MS);if (this.snapshotTimer && typeof this.snapshotTimer === "object" && "unref" in this.snapshotTimer) {this.snapshotTimer.unref();diff --git a/packages/coding-agent/src/core/kernel/state-snapshot.ts b/packages/coding-agent/src/core/kernel/state-snapshot.tsindex 6de1219277..8b5dfa7b3a 100644--- a/packages/coding-agent/src/core/kernel/state-snapshot.ts+++ b/packages/coding-agent/src/core/kernel/state-snapshot.ts@@ -9,6 +9,8 @@ import { join } from "node:path";/** Default ceiling on a snapshot payload. Over-cap variables are skipped + reported. */export const DEFAULT_SNAPSHOT_MAX_BYTES = 256 * 1024 * 1024;+/** Default ceiling for one serialized variable. */+export const DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES = 16 * 1024 * 1024;/** Base filename for the kernel snapshot within a session's artifact directory. */const KERNEL_STATE_BASENAME = "kernel-state";@@ -21,6 +23,8 @@ export interface SnapshotResult {saved: string[];/** Names that could not be serialized, with a short reason. */skipped: { name: string; reason: string }[];+ /** Oversized live variables removed by an explicit compaction snapshot. */+ pruned?: string[];/** Payload size on disk, in bytes. */bytes: number;path: string;@@ -53,12 +57,18 @@ function pyStr(value: string): string {* Python that serializes the user namespace to `outPath` (atomic write) and a* sibling `.json` manifest, then prints a single marker line with the result.*/-export function buildSnapshotCode(outPath: string, manifestPath: string, maxBytes: number): string {+export function buildSnapshotCode(+ outPath: string,+ manifestPath: string,+ maxBytes: number,+ maxVariableBytes = DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,+ pruneOversized = false,+): string {// All builtins are sourced via the locally-imported _b alias so the helper keeps// working even when the user namespace shadows names like list/open/print/len.return `def _prime_agent_snapshot_state():- import builtins as _b, json, os, sys, datetime+ import builtins as _b, io, json, os, sys, datetimetry:import dillexcept _b.Exception as _err:@@ -77,9 +87,24 @@ def _prime_agent_snapshot_state():# never snapshot them.always_skip = {"rlm", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}+ class SnapshotSizeLimitExceeded(_b.Exception):+ pass++ class SnapshotBuffer(io.BytesIO):+ def __init__(self, limit):+ io.BytesIO.__init__(self)+ self.limit = limit++ def write(self, chunk):+ if self.tell() + _b.len(chunk) > self.limit:+ raise SnapshotSizeLimitExceeded()+ return io.BytesIO.write(self, chunk)+payload = {}skipped = []+ oversized = []total = 0+ identify_oversized = ${pruneOversized ? "True" : "False"}for name in _b.list(ns.keys()):# Skip internals (dunder/underscore), IPython-injected names, and live# handles. A name matching a builtin (e.g. "list") is a user shadow worth@@ -87,14 +112,25 @@ def _prime_agent_snapshot_state():if name.startswith("_") or name in hidden or name in always_skip:continuevalue = ns[name]+ remaining = ${maxBytes} - total+ buffer_limit = ${maxVariableBytes} if identify_oversized else _b.min(${maxVariableBytes}, remaining)+ buffer = SnapshotBuffer(buffer_limit)# Modules are pickled by reference and re-imported on restore.try:- blob = dill.dumps(value)+ dill.dump(value, buffer)+ blob = buffer.getvalue()+ except SnapshotSizeLimitExceeded:+ if not identify_oversized and remaining < ${maxVariableBytes}:+ skipped.append({"name": name, "reason": "exceeds aggregate snapshot size cap"})+ else:+ skipped.append({"name": name, "reason": "exceeds per-variable snapshot size cap"})+ oversized.append(name)+ continueexcept _b.Exception as _err:skipped.append({"name": name, "reason": _b.type(_err).__name__ + ": " + _b.str(_err)[:200]})continue- if _b.len(blob) > ${maxBytes} or total + _b.len(blob) > ${maxBytes}:- skipped.append({"name": name, "reason": "exceeds snapshot size cap"})+ if total + _b.len(blob) > ${maxBytes}:+ skipped.append({"name": name, "reason": "exceeds aggregate snapshot size cap"})continuepayload[name] = blobtotal += _b.len(blob)@@ -115,10 +151,12 @@ def _prime_agent_snapshot_state():bytes_written = os.path.getsize(${pyStr(outPath)})saved = _b.sorted(payload.keys())+ pruned = _b.sorted(name for name in oversized if name in ns) if ${pruneOversized ? "True" : "False"} else []manifest = {"version": 1,"savedNames": saved,"skipped": skipped,+ "pruned": pruned,"bytes": bytes_written,"pythonVersion": sys.version.split()[0],"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),@@ -128,7 +166,26 @@ def _prime_agent_snapshot_state():json.dump(manifest, fh)except _b.Exception:pass- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"saved": saved, "skipped": skipped, "bytes": bytes_written}))+ pruned_ids = {_b.id(ns[name]) for name in pruned}+ while True:+ try:+ for name in pruned:+ if name in ns:+ del ns[name]+ output_cache = ns.get("Out")+ if _b.isinstance(output_cache, _b.dict):+ for key in _b.list(output_cache.keys()):+ if _b.id(output_cache[key]) in pruned_ids:+ del output_cache[key]+ for name in hidden:+ if name in ns and _b.id(ns[name]) in pruned_ids:+ del ns[name]+ break+ except _b.KeyboardInterrupt:+ # Deletion is idempotent. Finish the short critical section so a+ # snapshot timeout cannot leave only some purge candidates live.+ continue+ _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"saved": saved, "skipped": skipped, "pruned": pruned, "bytes": bytes_written}))try:@@ -229,6 +286,7 @@ interface RawListNames {interface RawSnapshot {saved?: unknown;skipped?: unknown;+ pruned?: unknown;bytes?: unknown;error?: unknown;}@@ -271,9 +329,11 @@ function parseMarkerLine<T>(stdout: string): T | null {export function parseSnapshotResult(stdout: string, path: string): SnapshotResult | null {const raw = parseMarkerLine<RawSnapshot>(stdout);if (!raw || raw.error) return null;+ const pruned = asStringArray(raw.pruned);return {saved: asStringArray(raw.saved),skipped: asReasonArray(raw.skipped),+ pruned: pruned.length > 0 ? pruned : undefined,bytes: typeof raw.bytes === "number" ? raw.bytes : 0,path,};diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex a43c096145..fb3c95c4d3 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -28,7 +28,7 @@ const SIMPLIFIED_TECHNICAL_ENGLISH_PROMPT = [].join("\n");const IPYTHON_CONTROL_PROMPT = [- "IPython is the agent's long-lived notebook: a persistent control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Use it to keep intermediate variables, inspect and transform outputs, write small helper functions, and preserve useful state across turns or compaction.",+ "IPython is the agent's long-lived notebook: a persistent control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.","","Do not assume IPython is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use IPython to coordinate the process and analyze what comes back.","",diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.tsindex affb252ebd..501471b72b 100644--- a/packages/coding-agent/src/core/tools/ipython.ts+++ b/packages/coding-agent/src/core/tools/ipython.ts@@ -362,6 +362,13 @@ export class IpythonKernelProvisioner {return this.startedManager?.isRunning ?? false;}+ /** Remove live variables above the snapshot's per-variable size limit. */+ async pruneOversizedVariables(): Promise<string[] | null> {+ const m = this.startedManager ?? (await this.managerPromise?.catch(() => undefined));+ const result = await m?.pruneOversizedVariables();+ return result ? (result.pruned ?? []) : null;+ }+/** 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));diff --git a/packages/coding-agent/src/modes/interactive/feature-hints.ts b/packages/coding-agent/src/modes/interactive/feature-hints.tsindex 0577511516..17d387fddb 100644--- a/packages/coding-agent/src/modes/interactive/feature-hints.ts+++ b/packages/coding-agent/src/modes/interactive/feature-hints.ts@@ -76,7 +76,7 @@ export const FEATURE_HINTS: readonly FeatureHintDefinition[] = [},{id: "persistent-ipython",- getText: () => "Prime Agent keeps IPython variables and helpers between turns and compactions.",+ getText: () => "Compaction removes IPython variables over 16 MiB; smaller state persists.",},{id: "context-usage",diff --git a/packages/coding-agent/test/ipython-provisioner.test.ts b/packages/coding-agent/test/ipython-provisioner.test.tsindex 176487335f..b243879d20 100644--- a/packages/coding-agent/test/ipython-provisioner.test.ts+++ b/packages/coding-agent/test/ipython-provisioner.test.ts@@ -187,9 +187,10 @@ describe("IpythonKernelProvisioner", () => {expect(countRuns()).toBe(1);});- it("listNamespaceNames() returns null when no kernel is running", async () => {+ it("namespace maintenance returns null when no kernel is running", async () => {const provisioner = new IpythonKernelProvisioner(tempDir, {});expect(await provisioner.listNamespaceNames()).toBeNull();+ expect(await provisioner.pruneOversizedVariables()).toBeNull();});it("does not dispose a running kernel when an ensure caller is aborted", async () => {diff --git a/packages/coding-agent/test/kernel-abort.test.ts b/packages/coding-agent/test/kernel-abort.test.tsindex 91d544cd1f..4afe24d364 100644--- a/packages/coding-agent/test/kernel-abort.test.ts+++ b/packages/coding-agent/test/kernel-abort.test.ts@@ -313,4 +313,53 @@ describe("KernelManager abort handling", () => {expect(controlSend).toHaveBeenCalled();manager.disposeSync();});++ it("starts the snapshot timeout after earlier kernel work finishes", async () => {+ vi.useFakeTimers();+ const manager = new KernelManager({+ cwd: process.cwd(),+ snapshot: { path: "/tmp/test-state.dill", manifestPath: "/tmp/test-state.json" },+ });+ let releaseQueue: () => void = () => {};+ const previousExecution = new Promise<void>((resolve) => {+ releaseQueue = resolve;+ });+ const executeInner = vi.fn(+ async (_code: string, opts: { signal?: AbortSignal }) =>+ await new Promise<{ stdout: string; stderr: string; status: "aborted"; durationMs: number }>((resolve) => {+ opts.signal?.addEventListener(+ "abort",+ () => resolve({ stdout: "", stderr: "", status: "aborted", durationMs: 5000 }),+ { once: true },+ );+ }),+ );+ Object.assign(+ manager as unknown as {+ state: "running";+ executionQueue: Promise<void>;+ executeInner: typeof executeInner;+ start: () => Promise<void>;+ },+ { state: "running", executionQueue: previousExecution, executeInner, start: async () => {} },+ );++ const snapshot = (+ manager as unknown as {+ captureSnapshot: (options?: { executionTimeoutMs?: number }) => Promise<unknown>;+ }+ ).captureSnapshot({ executionTimeoutMs: 5000 });+ await vi.advanceTimersByTimeAsync(5000);+ expect(executeInner).not.toHaveBeenCalled();++ releaseQueue();+ await waitForCalls(executeInner, 1);+ const signal = executeInner.mock.calls[0]?.[1].signal;+ expect(signal?.aborted).toBe(false);+ await vi.advanceTimersByTimeAsync(4999);+ expect(signal?.aborted).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ expect(signal?.aborted).toBe(true);+ await expect(snapshot).resolves.toBeNull();+ });});diff --git a/packages/coding-agent/test/kernel-state-roundtrip.test.ts b/packages/coding-agent/test/kernel-state-roundtrip.test.tsindex a4dcce3514..0c9b3c2eef 100644--- a/packages/coding-agent/test/kernel-state-roundtrip.test.ts+++ b/packages/coding-agent/test/kernel-state-roundtrip.test.ts@@ -1,5 +1,5 @@import { spawnSync } from "node:child_process";-import { existsSync, mkdtempSync, rmSync } from "node:fs";+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { homedir, tmpdir } from "node:os";import { join } from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";@@ -151,6 +151,84 @@ describeIfKernel("kernel state snapshot round-trip (real kernel)", { tags: ["ker}}, 60_000);+ it("caps each variable without reducing the aggregate snapshot budget", async () => {+ const boundedDir = mkdtempSync(join(tmpdir(), "prime-agent-state-bounded-"));+ const manager = new KernelManager({+ python: python as string,+ cwd: boundedDir,+ snapshot: {+ path: join(boundedDir, "bounded.dill"),+ manifestPath: join(boundedDir, "bounded.json"),+ maxBytes: 10 * 1024,+ maxVariableBytes: 8 * 1024,+ },+ });+ try {+ await manager.execute(`pickle_count = 0+class _Counted:+ def __reduce__(self):+ global pickle_count+ pickle_count += 1+ return (dict, ())+large_records = [_Counted() for _ in range(100_000)]+large_text = "x" * 16_384+small_text_one = "a" * 4_000+small_text_two = "b" * 4_000+aggregate_only = "c" * 4_000+late_small = "d" * 1_000`);+ await manager.execute("large_text");++ const snapshot = await manager.snapshotState();+ expect(snapshot?.skipped.map(({ name }) => name)).toEqual(+ expect.arrayContaining(["large_records", "large_text", "aggregate_only"]),+ );+ expect(snapshot?.saved).toEqual(expect.arrayContaining(["small_text_one", "small_text_two", "late_small"]));+ expect(await manager.listNamespaceNames()).toEqual(expect.arrayContaining(["large_records", "large_text"]));++ const compacted = await manager.pruneOversizedVariables();+ expect(compacted?.pruned).toEqual(expect.arrayContaining(["large_records", "large_text"]));+ const remaining = await manager.listNamespaceNames();+ expect(remaining).toEqual(+ expect.arrayContaining(["small_text_one", "small_text_two", "aggregate_only", "late_small"]),+ );+ expect(remaining).not.toContain("large_records");+ expect(remaining).not.toContain("large_text");+ const outputCache = await manager.execute(+ "print(any(isinstance(value, str) and len(value) == 16_384 for value in Out.values()))",+ );+ expect(outputCache.stdout.trim()).toBe("False");+ const count = await manager.execute("print(pickle_count)");+ expect(Number(count.stdout.trim())).toBeLessThan(100_000);+ } finally {+ await manager.dispose();+ rmSync(boundedDir, { recursive: true, force: true });+ }+ }, 60_000);++ it("keeps oversized variables when the compaction snapshot cannot be written", async () => {+ const failedDir = mkdtempSync(join(tmpdir(), "prime-agent-state-prune-failure-"));+ const blocker = join(failedDir, "not-a-directory");+ writeFileSync(blocker, "block snapshot parent");+ const manager = new KernelManager({+ python: python as string,+ cwd: failedDir,+ snapshot: {+ path: join(blocker, "state.dill"),+ manifestPath: join(blocker, "state.json"),+ maxBytes: 64 * 1024,+ maxVariableBytes: 8 * 1024,+ },+ });+ try {+ await manager.execute('large_text = "x" * 16_384');+ expect(await manager.pruneOversizedVariables()).toBeNull();+ expect(await manager.listNamespaceNames()).toContain("large_text");+ } finally {+ await manager.dispose();+ rmSync(failedDir, { 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");diff --git a/packages/coding-agent/test/kernel-state-snapshot.test.ts b/packages/coding-agent/test/kernel-state-snapshot.test.tsindex 7f2719d025..af934fe1d8 100644--- a/packages/coding-agent/test/kernel-state-snapshot.test.ts+++ b/packages/coding-agent/test/kernel-state-snapshot.test.ts@@ -4,6 +4,7 @@ import {buildRestoreCode,buildSnapshotCode,DEFAULT_SNAPSHOT_MAX_BYTES,+ DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,manifestPathIn,parseRestoreResult,parseSnapshotResult,@@ -25,12 +26,14 @@ describe("parseSnapshotResult", () => {const stdout = `${MARKER}${JSON.stringify({saved: ["x", "y"],skipped: [{ name: "sock", reason: "TypeError: cannot pickle" }],+ pruned: ["large_text"],bytes: 1234,})}\n`;const result = parseSnapshotResult(stdout, "/tmp/s.dill");expect(result).toEqual({saved: ["x", "y"],skipped: [{ name: "sock", reason: "TypeError: cannot pickle" }],+ pruned: ["large_text"],bytes: 1234,path: "/tmp/s.dill",});@@ -89,11 +92,13 @@ describe("buildSnapshotCode", () => {expect(code).toContain('"/state/sess.dill"');expect(code).toContain('"/state/sess.json"');expect(code).toContain(String(DEFAULT_SNAPSHOT_MAX_BYTES));+ expect(code).toContain(String(DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES));});it("uses dill, an atomic write, and skips internal handles", () => {expect(code).toContain("import dill");expect(code).toContain("os.replace");+ expect(code).toContain("except _b.KeyboardInterrupt");expect(code).toContain('"rlm"');expect(code).toContain(`print(${JSON.stringify(MARKER)}`);});diff --git a/packages/coding-agent/test/suite/agent-session-compaction.test.ts b/packages/coding-agent/test/suite/agent-session-compaction.test.tsindex 0716e6a2b6..9504460649 100644--- a/packages/coding-agent/test/suite/agent-session-compaction.test.ts+++ b/packages/coding-agent/test/suite/agent-session-compaction.test.ts@@ -94,9 +94,35 @@ describe("AgentSession compaction characterization", () => {await harness.session.prompt("one");await harness.session.prompt("two");- const result = await harness.session.compact();+ const pruneOversizedVariables = vi.fn(async () => ["large_text"]);+ const listNamespaceNames = vi.fn(async () => ["small_value"]);+ const internals = harness.session as unknown as { _ipythonKernelProvisioner?: unknown };+ const previousProvisioner = internals._ipythonKernelProvisioner;+ internals._ipythonKernelProvisioner = {+ hasRunningKernel: true,+ pruneOversizedVariables,+ listNamespaceNames,+ };+ let result!: Awaited<ReturnType<typeof harness.session.compact>>;+ try {+ result = await harness.session.compact();+ } finally {+ internals._ipythonKernelProvisioner = previousProvisioner;+ }const compactionEntries = harness.sessionManager.getEntries().filter((entry) => entry.type === "compaction");+ expect(pruneOversizedVariables).toHaveBeenCalledOnce();+ expect(listNamespaceNames).toHaveBeenCalledOnce();+ expect(pruneOversizedVariables.mock.invocationCallOrder[0] as number).toBeLessThan(+ listNamespaceNames.mock.invocationCallOrder[0] as number,+ );+ expect(harness.session.messages).toContainEqual(+ expect.objectContaining({+ role: "custom",+ customType: "ipython_state",+ content: expect.stringContaining("were removed: large_text"),+ }),+ );expect(result.summary).toBe("summary from extension");expect(compactionEntries).toHaveLength(1);expect(harness.session.messages[0]?.role).toBe("compactionSummary");