omp packages

pi-nunc0.5.1

In-session rolling context and working memory extension for Pi.

GitHub Actions Published 4 hours ago ~1.6K downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

Nunc

Nunc is a Pi extension designed to keep a single long-running session coherent inside a finite context window.

Scope stays strictly within the active session branch: /new starts with empty memory, and /tree, /fork, and /clone follow the selected branch. Nunc avoids cross-session memory databases, user profiling, or background document indexing—durable project knowledge belongs in code, docs, and commits.

How It Works

Stock compaction replaces older conversation history with a single flat summary, which often drops exact constraints, parameters, or mid-task state over multiple compactions, and invalidates prompt caches when summaries move. Nunc replaces that summary with incremental working-memory slots (M) and a cache-friendly context layout:

Normal turn:   F | R_before | M | R_after
Compaction:    F | M | B | K   -->   updated M + retained K
  1. Verbatim recent history (R / K): Recent turns stay verbatim so the model sees exact tool calls, outputs, and immediate context.
  2. Anchored working memory (M): Information that still matters after older turns age out—goals, constraints, decisions, inputs, and unfinished work—lives in discrete text slots ({ id, text }). During normal turns, unchanged M stays anchored at the history boundary where it was last sent (R_before | M | R_after), keeping the prompt prefix stable for provider caching.
  3. Incremental maintenance: When Pi triggers compaction (threshold, overflow recovery, or /compact), Nunc splits active history into retiring B and retained K, then performs one extraction transaction using the current model and thinking by default, or the effective extraction selection described below. Bounded transient transport retries stay on the same route; there is no model-repair loop. The model returns a structured JSON patch (add, update, remove, priority, required, and optional toolResultEdits). All required items are kept together. Capacity, cancellation and provider-error failures preserve existing state. Eligible completed-response failures can instead save a mechanical window roll with unchanged M and retained K, visibly marking that retired history was not extracted. Targeted compaction does not use that fallback.
  4. Tool-result cleanup & overflow calibration: Completed business-tool outputs that have already been distilled into M (or duplicated in K) can be compacted or summarized in place while keeping raw originals in the session JSONL. If a provider undercounts tokens or rejects a maintenance request for context overflow, Nunc records branch-bound calibration so a later attempt can use a smaller eligible payload or fail without dispatching the same rejected request.

Tools and TUI

Interactive TUI & Commands

  • /nunc or F7: Opens the Nunc overlay in TUI mode (Slots tab to search, preview, edit, or delete memory slots; Context tab to inspect the live F / M / R layout, token budgets, and last maintenance record). In non-TUI modes, /nunc prints the full text report.
  • /nunc details: Prints the text report (slot occupancy, budgets, last main/maintenance status, and recent diagnostics) without calling a model.
  • /nunc model [<selector> | default]: With no argument, show the effective maintenance model, thinking, source, and any static headroom advisory. A selector sets a session-only override; default clears it if the configured or inherited route resolves. On stock Pi 1.7.0, typing /nunc model opens suggestions; Tab accepts the highlighted item. Neither the command nor its presets switch the main model.
  • Footer indicator: Shows slot count and memory-target occupancy (🧠 8·42%, 🧠 0 when empty, 🧠 ↻8 during maintenance/save, 🧠 !8·roll for a mechanical roll, 🧠 !8 for an operational warning, 🧠 !8·cap for capacity advice, 🧠 × when unavailable).

Nunc checks extraction-route readiness and normal-trigger headroom at startup. A smaller extraction window can warn even before the first turn without blocking fitting main requests or an early /compact. Switching to a fitting extraction route can clear the advisory immediately, without another compaction; unrelated runway advice stays active while its evidence still applies. /nunc details separates the current warning from diagnostic history. Pi still owns compaction scheduling and recovery: Nunc does not schedule background compaction, rewrite settings.json, or reject main requests with CAPACITY merely because the extraction window is smaller.

Optional Model Tools (--nunc-memory-tools)

By default, Nunc manages M only during compaction without changing the model's toolset. When enabled via --nunc-memory-tools or Pi settings ({"nunc": {"memoryTools": true}}), Nunc exposes two tools to the model:

  • nunc_memory_read: Reads current slots, revision, and budget; also supports read-only keyword search (query) and entry lookup (entryIds, originals) over retired messages and cleaned tool outputs on the current session branch.
  • nunc_memory_patch: Atomically adds, updates, or removes memory slots (and optional toolResultEdits) during a turn using compare-and-swap (expectedRevision).

Requirements

Dependency Version
Node Stable >=22.19.0 (.node-version: 26 for live checks)
npm Stable >=11.5.1
Pi / @earendil-works/pi-ai / @earendil-works/pi-tui Runtime & peerDependencies: ^1.7.0; devDependencies pinned to 1.7.0

Runtime constraints:

  • Persistent sessions only (--no-session is rejected).
  • Native images only (images.blockImages must remain false).
  • Single custom compaction owner (do not run another compaction extension alongside Nunc).

Quick Start

Install the published Pi package:

pi install npm:pi-nunc

Alternatively, add the versioned package to ~/.pi/agent/settings.json (merge it into any existing packages list):

{"packages": ["npm:pi-nunc@^0.5.0"]}

From Source

Obtain a checkout of the Nunc source, then run from its root:

npm ci --ignore-scripts --no-audit --no-fund
npm run build

node node_modules/@earendil-works/pi-coding-agent/dist/cli.js \
  --offline --no-extensions -e dist/src/index.js

With a custom config file or model memory tools enabled:

node node_modules/@earendil-works/pi-coding-agent/dist/cli.js \
  --offline --no-extensions -e dist/src/index.js \
  --nunc-config ./nunc.json --nunc-memory-tools

package.json registers "pi": { "extensions": ["./dist/src/index.js"] }, so the repo directory can also be loaded as a local Pi package after npm run build.

Configuration

Pi settings.json

In ~/.pi/agent/settings.json or a trusted project .pi/settings.json, set nunc.model to choose the maintenance and eligible UI cleanup model, and optionally nunc.models to list Tab completion presets. A trusted project's model overrides the global model without discarding its presets; a project models list replaces the global list. Nested sections still merge by field. Untrusted project settings are ignored.

Before choosing a maintenance model in settings or with /nunc model: The selected model and native API must support the request media and thinking level, with working Pi-managed authentication. Its provider/account determines extraction billing, cache behavior, and latency separately from the main session; no savings or cache hits are guaranteed. A different extraction provider receives frozen F/M and the selected B/K transcript, including instructions, tool data, and native images when present. Check that the transfer complies with that provider's data-handling terms and your requirements.

{
  "nunc": {
    "memoryTools": false,
    "toolResultCleanup": true,
    "model": "openai/gpt-6.2-sol:low",
    "models": ["openai/gpt-6.1-terra:medium", "google-vertex/gemini-4-hydrogen:low", "session"]
  }
}

Model selectors

Use "<provider>/<model-id>[:<thinking>]" or "session[:<thinking>]" in nunc.model, nunc.models, or /nunc model. session follows the main model; omitting thinking inherits the session's level. For a qualified model, Nunc splits at the first / and looks up the entire model ID first. Only if that lookup misses does it try the final colon as a thinking separator. For example, if acme/worker:v2 is the catalog identity, it matches as-is; acme/worker:v2:low selects it with low thinking unless that entire ID also exists. Supported thinking spellings are off, minimal, low, medium, high, xhigh, and max; pi-virtual is not an extraction route.

A /nunc model override takes precedence over configuration for the active session, survives in-process /reload, and is not written to settings, config files, or the session transcript. It does not carry over to a new session or survive a process restart. See Pi configuration for resolution and command details for completion behavior.

--nunc-config JSON

--nunc-config shadows the settings-based engine configuration; its fields are not filled in from nunc engine settings. All fields are optional. policyFile resolves relative to the config file's directory.

Before setting model with --nunc-config: The selected model and native API must support the request media and thinking level, with working Pi-managed authentication. Its provider/account determines extraction billing, cache behavior, and latency separately from the main session; no savings or cache hits are guaranteed. A different extraction provider receives frozen F/M and the selected B/K transcript, including instructions, tool data, and native images when present. Check that the transfer complies with that provider's data-handling terms and your requirements.

Field Default Purpose
policyFile unset Supplemental UTF-8 Markdown maintenance preferences appended to policies/default.md.
memory.fraction 0.1 Planning reserve fraction of available context ([0, 1)).
memory.targetTokens 8192 Soft organizing target for M.
memory.maxTokens unset Optional advisory ceiling on the maintenance organizing target.
memory.hardMaxTokens unset Optional hard cap on saved M (when unset, required slots may exceed the soft target).
rolling.keepRecentFraction 0.5 Target fraction of post-M context kept as verbatim K ((0, 1)).
model unset (inherit session model and thinking) Maintenance and eligible UI cleanup selector, such as "openai/gpt-6.2-sol:low".
models unset Ordered list of completion presets; does not select a model on its own.
extraction.toolResults "auto" "auto" (stage retiring-tool reduction first, tighten only as needed) or "full" (no tool-body truncation).
extraction.headTailChars 200 Unicode code points kept at each end in the tighter stage; the retiring-only stage keeps at least 1,000 at each end.
extraction.outputTokens "auto" "auto" (scales from an 8192 floor up to model output capability) or positive integer.
budget.safetyTokens 1024 Safety margin subtracted from input limits.
budget.growthTokens 1024 Post-compaction growth room reserved for upcoming turns.
budget.extraMainInputTokens 0 Extra input token allowance for main requests.
budget.extraExtractionInputTokens 0 Extra input token allowance for maintenance requests.
budget.inputLimit unset Optional explicit input token ceiling.
budget.imageTokens unset Optional per-image token estimate override (defaults to Pi's heuristic).

Example nunc.json (overriding rolling.keepRecentFraction from 0.5 to 0.67):

{
  "policyFile": "./preferences.md",
  "memory": { "fraction": 0.1, "maxTokens": 2000, "hardMaxTokens": 8192 },
  "rolling": { "keepRecentFraction": 0.67 },
  "extraction": { "toolResults": "auto", "headTailChars": 200 },
  "budget": { "safetyTokens": 1024, "growthTokens": 1024 }
}

resolveExtractionSelection validates explicit choices; inherited thinking can be normalized for the chosen extraction model. Extraction uses a separate extractionBudget for its input, output and media checks, not the main model's window or trigger. A broken extraction setting or failed extraction does not silently fall back to another model, credential, or explicit thinking level. Main-turn projection and enabled nunc_memory_read / nunc_memory_patch remain available under their own checks. See Pi configuration and the Context UI.

Development

npm ci and npm run build compile the extension. npm run check:engine uses the Node/npm floors above. The full check suite (scripts/check.mjs all) additionally requires Node ^26.7.0 for live preflight, historical Git objects and offline dependency-cache entries for comparison fixtures, POSIX PTYs, and /usr/bin/python3. The check runner rejects versions below the declared floors, malformed versions, and prereleases. Checks report the actual observed Node/npm versions; live preflight records the observed Node version in its receipt and SHA-256 binding, invalidating earlier receipts after a runtime change. See docs/DEVELOPMENT.md and docs/LIVE.md.

The build first emits TypeScript JS and declarations, then bundles dist/src/index.js into one ESM unit using the locked TypeScript compiler API (no additional bundler dependency). Local engine, Pi, and UI modules stay within that unit so Pi's /reload cannot combine an upgraded entrypoint with stale native ESM submodules. Host @earendil-works/pi-* modules and node:* builtins remain external. The standalone ./pi and ./engine exports and declarations remain available. Live build parity applies the same compiler and bundle transformation in memory without rewriting artifacts.

Comparison tests prepare and remove isolated temporary worktrees from 70dacad and immutable scoped-task pre-change commit 1d4fc4a210b64f71871ab3f5c10093215a25990c. Each fixture uses its own tracked dependency lock with offline installation and disabled lifecycle scripts; no pre-existing .scratch checkout is required.

Documentation

Detailed specifications live in docs/: