prime-agent-context
v6.3.5
Published
Local paging for large Prime Agent tool output and a durable task snapshot
Maintainers
Readme
Prime Context
Prime Context keeps large Prime Agent tool output out of the model context without losing it, and keeps the current task visible during long sessions.
Install
From npm:
prime-agent package install npm:prime-agent-contextFrom a local checkout:
prime-agent package install /absolute/path/to/prime-agent-contextFor one local run:
prime-agent -e /absolute/path/to/prime-agent-contextPrime Context 6.3.5 targets Prime Agent v0.8.1 and Node.js >=22.8.0.
Observation broker
Prime Context uses a stateful observation broker with three outputs:
- Pass through for short, novel, decision-useful results.
- Structured capsule for large or repetitive output, retaining the test summary, every detected failing-test ID, exception messages, source locations, and command status.
- Delta capsule for repeated outcomes or content, showing an unchanged result or the changed document section. Changed test counts use a structured capsule so novel composite output is not discarded.
The broker compares exact content directly across recent tools and normalizes clean tests, failing-test sets, exceptions, and command failures. It does not use hashes. A repeated source read can therefore collapse even when a different command returned it. Composite output also replaces exact prior sections of at least 512 bytes with unchanged-section markers when the novel remainder is at most 30% of the source. Small changed documents use a bounded line delta under the same admission limit. Exception normalization accepts diagnostic Type: message lines or a bare exception type, not source-code references to exception classes. Counted test outcomes such as 1 failed, 8 passed in 0.10s must occupy a result-shaped line; phrases such as Return 0 succeeded, 1 failed/cancelled inside requirements remain ordinary content.
Failure capsules use token-return-on-investment admission. A sampled failure below 8 KiB passes through when its capsule would exceed 30% of the original result. Clean success and large repetitive output remain aggressive archive candidates. The goal is to reduce likely follow-up model calls rather than maximize compression ratio.
Large-output paging
Before, a tool can return many thousands of visible lines directly to the model. After installing Prime Context, output at or above 24 KiB becomes a bounded capsule:
<prime_context_output id="obs_01..." tool="ipython" bytes="118442" lines="2638" source="visible-tool-result">
Large output archived locally. The excerpt below is incomplete.
...
Read exact visible text: prime_context action=read id=obs_01... startLine=1 endLine=80
Search exact visible text: prime_context action=search id=obs_01... query="AssertionError"
</prime_context_output>Prime Context stores the selected public text exactly in a local gzip file. For most tools this is the visible result text. For Bash, Prime Context uses the typed public fullOutputPath when Prime Agent provides it, and labels the capsule source public-complete-output. It falls back to visible text if that file is unavailable.
The model can list recent observations, recover a line range, or search with the prime_context tool:
prime_context action=list limit=20
prime_context action=read id=obs_01... startLine=200 endLine=279
prime_context action=search id=obs_01... query="AssertionError"
prime_context action=search id=obs_01... query="AssertionError" contextLines=4
prime_context action=search id=obs_01... query="TRACE" matchOffset=50 maxMatches=5
prime_context action=search query="AssertionError" limit=20Listing shows recent observation IDs, tool names, source, byte and line counts, error status, and archive times. It does not return archived bodies. Search with an ID inspects one observation. Search without an ID checks the newest 20 observations by default, or the bounded limit supplied by the caller.
Search is case-insensitive fixed-string search. The model-facing tool returns at most 80 lines per read, 10 matches per search, 20 observations per list, and 12 KiB per read or search response. The caller can set contextLines from 0 to 20 when a diagnostic needs a narrower or wider excerpt. startLine and matchOffset page through later content instead of pulling one broad recovery into model context. Nearby matches share one context window instead of repeating lines. The /pc UI commands retain the configured readMaxBytes budget for human inspection. Prime Context does not archive its own recovery responses again.
Capsules prioritize recognized terminal outcomes, every detected failing-test ID, direct exceptions, source locations, command status, and a bounded amount of neighboring context before warning-only lines. Exact repeated observations can become delta capsules across tools, semantically identical test or command outcomes become outcome deltas, and changed small or medium documents can show only their changed section. Distinct medium-sized results retain a two-result grace period; later 8–24 KiB results use an at-most 1.5 KiB capsule, preventing repeated source dumps from bypassing the normal threshold. Verbose command-usage output of at least 4 KiB with ten or more option lines is also archived immediately, preserving the leading fatal or usage evidence instead of exposing a long help listing. Trace-only bursts of at least 2 KiB are sampled when six or more trace/debug/progress lines make up at least 80% of the output, even without a terminal status line. If such a trace has no decisive diagnostic, its capsule omits misleading Read/Search recovery hints and recommends rerunning the original command with filtered output. Repetitive decisive lines are deduplicated by shape, and each excerpt line has a byte bound so one payload cannot consume the capsule. Repetitive output uses a smaller capsule. A clean repetitive command success keeps its terminal summary plus a bounded informative non-trace head in an at-most 768-byte capsule and omits both Read and Search recovery actions. Clean capsules and deltas use the first-class workflow tracker to distinguish COMMAND_CLEAN, STAGE_CLEAN, and GOAL_READY. While requirements remain unlocked they explicitly say to keep the active goal open; only a current cumulative post-lock pass can advertise goal readiness; when the same tool later archives the same normalized clean terminal result, such as TEST_RESULT PASS 9/9, a smaller delta capsule reports that the terminal success is unchanged even if wrapper or trace text differs; terminal failures retain up to 1 KiB of decisive evidence. In compact terminal-failure capsules, Markdown bullet prose is not promoted as a decisive diagnostic, so staged requirement text cannot displace actual failure and exception lines. Capsule search hints prefer a concrete FAIL test_module.TestCase.test_name prefix when present and otherwise name a fixed string present in the archived text; when no safe searchable token exists, Prime Context omits the search hint rather than advertising a guaranteed miss. Excerpts retain their original source coordinates through signal selection and truncation, then are packed as complete escaped line fragments, so repeated or prefix-identical lines keep exact labels and a byte boundary cannot cut a numbered line or XML entity; a compact recovery-only capsule is used when fixed metadata leaves no excerpt room. The suggested read action targets an asymmetric window from 20 lines before through 10 lines after the highest-priority selected line, favoring leading traceback and requirement context instead of defaulting to the first 200 lines. Capsule size and the effective archive threshold can also decrease as context usage rises. Configured values remain normal upper bounds.
Durable task snapshot
Prime Context injects task context only when it adds information that is not already visible. A new session with an empty snapshot receives no duplicate task message. After compaction removes the root request, Prime Context restores it. Focus, open items, and pinned outputs remain available whenever they are set:
<prime_context_task>
ROOT_REQUEST
"Implement Prime Context from the current specification."
FOCUS
"Finish archive read/search and package smoke."
OPEN_ITEMS
- [item_1] Implement range reads.
PINNED_OUTPUTS
- obs_01...
</prime_context_task>The task context is appended after persisted conversation history and has no changing timestamp. Volatile lock, test, and readiness fields therefore cannot invalidate the provider cache prefix for earlier assistant and tool history. During staged work the message contains only compact workflow state and one direct action or completion guard. If compaction hides a user instruction, Prime Context restores a bounded exact copy of the missing instruction instead of a heuristic extracted contract. Unchanged state reuses the same rendered message. When nothing must be restored, the context hook is a literal no-op.
During a staged active goal, Prime Context tracks requirements_revision, locked, latest_test_revision, latest_test_result, cumulative_suite, goal_ready, and one of COMMAND_CLEAN, STAGE_CLEAN, or GOAL_READY. Only a declaration at the beginning of the complete user message can lock requirements. The transition is monotonic and cannot be reversed by later branch synchronization. A test result becomes stale when requirements advance. A smaller focused suite cannot replace the largest cumulative suite already observed. GOAL_READY requires the current revision's cumulative suite to pass after lock with no later decisive failure. Before that point, the context injects a completion guard. After it, GOAL_READY says Call await goal.complete() now and says not to inspect the goal API, read source, reconstruct requirements, run probes, or rerun an unchanged suite unless new evidence appears.
Prime Context does not change Prime Agent's child APIs or scheduler. Before each model call, it keeps only the current goal_context prompt and coalesces consecutive idle continuation turns when their normalized polling result is unchanged. Volatile observation UUIDs and elapsed values do not make the same poll look new. State transitions, user steering, and distinct results stay visible. This prevents a multi-hour external job from forcing compaction merely because Prime Agent emitted the same goal continuation repeatedly. Prime Agent still owns continuation timing and may still show its live Goal continuation banner in the UI.
Prime Context also keeps only the newest IPython kernel-state notice. When Prime Agent generates a long inventory of live IPython names after compaction or session restoration, the context hook replaces that inventory with the name count and a focused globals() lookup hint. Kernel values remain untouched and available in the persistent kernel.
Its compact economic policy says to work locally for one package or one serial critical path. On later staged changes, patch only changed sections instead of rewriting unchanged file bodies. Delegation is reserved for independent concurrent work with a distinct deliverable whose expected parent-work savings exceed launch, context reconstruction, and reply-integration cost. Prime Agent 0.8.1 permits one additional RLM level by default, so the same threshold applies recursively and expected savings must exceed all descendant cost. Multiple children must not review the same files or tests. Outside explicitly staged work, the Prime Agent goal continues to own task continuity unless explicit Prime Context focus, open items, or pins exist.
Focus, open items, and pinned output IDs use the newest full snapshot stored on the selected branch. When a session is forked, pinned observation files are copied into the fork archive so those IDs remain readable.
The model-facing tool supports list, read, search, status, and update. Snapshot updates can set or clear focus, add or complete work items, and pin or unpin observation IDs.
Success-adjusted economics
Prime Context treats workflow correctness as a gate, not a speed metric. Evaluation priority is: correct cumulative result and completion after lock, end-to-end compactions, end-to-end cost including recursive children, then call and token diagnostics. Visible bytes is a mechanism diagnostic, not an outcome metric. Early completion and capped timeouts remain condition failures rather than artificial efficiency wins. The broker does not chase a higher compression ratio when a result already has good token return on investment.
Broker metrics
prime_context status and /pc status report the workflow revision, monotonic lock, latest test, cumulative suite, and readiness; pass-through, structured-capsule, and delta decisions; visible bytes saved; recovery calls and whether they returned evidence; context turns after the first clean success; child launches observed after capsules; and context-token load per KiB saved. These session-local signals make follow-up-call cost visible without changing Prime Agent telemetry or scheduling.
Commands
/pc status
/pc list [limit]
/pc read <observation-id> [start:end]
/pc search <observation-id|all> <fixed text>
/pc focus <text>
/pc focus clear
/pc add <text>
/pc done <item-id>
/pc pin <observation-id>
/pc unpin <observation-id>
/pc mode on|off
/pc cleanup current
/pc doctorMode changes last for the current session. Commands remain available when the mode is off.
Configuration
Prime Context reads these optional files, with project values overriding global values:
~/.prime/agent/prime-context.json
<repo>/.prime/agent/prime-context.jsonExample:
{
"enabled": true,
"minTextBytes": 24576,
"capsuleMaxBytes": 6144,
"readMaxBytes": 65536
}Invalid values use their defaults and are reported once by /pc doctor. capsuleMaxBytes must be at least 512 so the capsule can retain its recovery boundary. readMaxBytes remains the /pc UI budget and an upper bound for model recovery; model reads and searches have a separate 12 KiB safety cap.
Storage and removal
Archives are stored under:
~/.prime/agent/prime-context/sessions/<session-id>/Set PRIME_CONTEXT_HOME to use a different storage root. Prime Context does not delete archives automatically. Use /pc cleanup current to remove only the active session’s archives and clear their pinned IDs. To remove all stored observations manually:
rm -rf ~/.prime/agent/prime-contextRemove the npm package with:
prime-agent package remove npm:prime-agent-contextRemoving the package does not remove archived files; delete the storage directory separately if desired.
Limitations
- Most tools archive only text visible in the public tool-result payload; Bash also uses its typed public complete-output source when available.
- Capsule reduction uses generic output heuristics rather than tool-specific parsers.
- There is no remote sync.
- There is no automatic cleanup.
- There is no Continual Harness integration.
- Prime Context makes no claim of general productivity improvement.
