hffmnnj.context-trim
v0.2.0
Published
Lossless native tool output compaction for OpenCode V2, with optional Clef-assisted outgoing context selection.
Readme
Context Trim
Lossless native tool output compaction for OpenCode V2, with optional Clef-assisted outgoing context selection.
Completed native glob results repeat the same absolute directory on every
line; completed Code Mode discovery displays repeat the same return-type
suffixes across signatures. This plugin compacts that repetition out of the
tool display text so fewer context bytes carry the same result. Nothing is
discarded: every path, signature, description, order, duplicate, notice, and
pagination value survives in the lossless formatters, and anything they do not positively
recognize passes through unchanged. Runtime schemas and tool calls are never
changed; only the completed display text is rewritten.
The optional semantic stage below has a different contract: it can defer old return schemas from an outgoing request, explicitly marking omissions and recovering from unchanged host history. It is off by default and is not a self-contained lossless encoding.
Install
Requires OpenCode V2. Add the package to your OpenCode config:
{
"$schema": "https://opencode.ai/config.json",
"plugins": ["hffmnnj.context-trim"]
}The npm package name and plugin id are both hffmnnj.context-trim. OpenCode
installs the package and reloads the config on save.
Plugin options are optional:
{
"plugins": [
{
"package": "hffmnnj.context-trim",
"options": { "enabled": true, "codemode": true }
}
]
}enabled: false disables the plugin and codemode: false disables Code Mode
factoring alone. The opt-in Clef stage is described below.
Lossless formats
Glob directory factoring
A compactable display is a list of absolute paths sharing one directory
prefix. The plugin rewrites it to a @dir header line followed by one suffix
per line:
@dir /repo/src/
a.ts
b.tsprefix + suffix rebuilds each original path exactly (no normalization, no
sorting, no escaping). The original trailing line feed is preserved, as is the
recognized native truncation footer. Reconstruction of the example above
yields /repo/src/a.ts and /repo/src/b.ts, duplicates and order included.
The rewrite applies only when it is strictly smaller in UTF-8 bytes.
Code Mode signature-suffix factoring
A compactable Code Mode display is canonical JSON only: an array of 2–256
discovery entries, or an exact {items, remaining, next} search envelope.
Each entry holds only string path, signature, and optional description;
paths are tools member-access paths and each signature starts with its exact
path followed by (. Repeated identical suffixes starting at ): Promise<
(keeping ): Promise in the prefix) and ending in > are factored when the
suffix is at least 256 UTF-8 bytes and appears at least twice. This is textual
factoring, not type parsing; shortened signatures are not executable.
The complete display becomes explicit JSON with
format: "context-trim/codemode-signatures@1", a suffixes table
(s1, s2, …), and value holding the original array/envelope. A factored
signature is {"prefix": "…", "ref": "s1"}; unfactored signatures stay
strings. Reconstruction is prefix + suffixes[ref] per factored signature,
restoring the original JSON values exactly (not the original indentation).
All paths, descriptions, order, duplicates, and pagination survive inside
value. References exist only inside this explicit format, so they cannot
collide with type identifiers.
The recognizer is strict and canonical: after stripping ASCII whitespace outside
strings, the text must match JSON.stringify(JSON.parse(text)), rejecting duplicate keys,
precision loss, negative zero, and alternate escape/numeric spellings.
Unknown, already-factored, malformed, or non-saving inputs pass through
unchanged. Input is capped at 4 MiB per feature (glob and Code Mode each);
there is no execution, subprocess, I/O, dependency, or cache.
Lossless after-hook boundary
- Single
tool.hook("execute.after")on completed nativeglobresults and completed Code Modeexecutedisplays with string code; glob behavior is unchanged by the Code Mode addition. - Rewrites only the verbatim display text in
result.content(string or text parts). A stringresult.outputexactly equal to the old display text is updated to the same compacted text; tool input, structured output, metadata, file parts, notice identities, and truncated states stay intact. Skips errors, still-running calls and unsupported shapes; Code Mode additionally skipstruncated: truemetadata and any non-text content parts. Glob retains its recognized native truncation footer. Exceptions leave the original result untouched. - The lossless formatters do not execute tools, edit source/history, make network calls, add commands or change permissions. Shell filtering and Code Mode JSON whitespace compaction stay with RTK; grep label stripping is explicitly deferred.
Exclusions
Declined inputs pass through byte-identical (fail open on errors):
- Tools other than completed native
globand Code Modeexecutedisplays, failed or still-running calls, incompatible shapes. - Glob: relative paths, carriage returns, U+2028/U+2029 separators.
- Glob: unexpected blank lines or notice lines, unknown truncation wrappers,
empty suffixes, suffix/header collisions, prefixes no longer than
/. - Rewrites that would not be strictly smaller, and inputs over the 4 MiB cap.
Configuration and bypass
- Plugin option
enabled: falsedisables the plugin. - Plugin option
codemode: falsedisables Code Mode factoring alone. CONTEXT_TRIM_DISABLED=1in the process environment disables it.RTK_DISABLED=1, code mentioningrtk, or the exactcontext-trim:rawmarker bypasses Code Mode factoring only. These are not alternate execution routes.- Process/config controls use the normal config/environment reload; code markers are checked per call. There is no separate raw command or permission route. Do not request raw preemptively: retry raw only after the default display fails, and only for safe non-mutating retries.
Options are set on the same package entry shown under Install, for
example {"package": "hffmnnj.context-trim", "options": {"enabled": false}}.
Formatted tool text may be persisted. Disabling this plugin affects future
tool calls, not past results; old outputs remain reconstructable from their
header/suffix or prefix/suffix-table form. This is separate from
opencode-trim-1 and its /trim controls, which do not disable Context Trim
(existing /trim raw does not disable this plugin). Existing context plugins
remain unchanged and may independently transform outgoing context.
Optional Clef context selection
Enable explicitly with "options": {"clef": {"enabled": true}} on this plugin's
configuration entry. This default integration uses an existing Clef installation
over SSH and the model remains clef-flash. The SSH destination and remote
helper/key paths are no longer built in: existing installations must migrate
by creating ~/.config/opencode-context-trim/clef.json for the server's user.
For local Clef only:
{
"sshTarget": "[email protected]",
"helperPath": "/srv/clef/helper.py",
"keyFile": "/srv/clef/api-key"
}Replace all three example values with the existing installation's values. This
file names the remote key file, not the key itself. The home path must be absolute.
The home directory, .config,
and opencode-context-trim directory must be owned by the server user, be real
directories, and not be group- or world-writable. The file must be a regular,
non-symlink file owned by that user, not group- or world-writable, and at most
4 KiB. For example, create the last directory with mode 0700 and the file with
mode 0600. Only an operator who controls the server user's home should edit
these settings; project/plugin options cannot supply them. The SSH target is a
hostname optionally prefixed by user@; helper and key paths must be absolute
paths containing only ASCII letters, digits, /, ., _, and -, with no
. or .. path components. SSH configuration and host-key checks remain the
operator's responsibility. No remote command or executable can be supplied.
The configuration is read on demand, so creating or correcting it requires no
server restart. Missing, invalid, or unsafe configuration leaves context intact;
context_trim.status reports the content-free configuration-error state.
Alternatively, opt in to hosted System One with "options": {"clef":
{"enabled": true, "provider": "typesafe", "model": "jev-latest"}}.
The operator must also explicitly authorize hosted use in the same per-user file;
for hosted only:
{ "allowTypesafe": true }To allow both local Clef and hosted System One, use one combined file:
{
"sshTarget": "[email protected]",
"helperPath": "/srv/clef/helper.py",
"keyFile": "/srv/clef/api-key",
"allowTypesafe": true
}The file's ownership and permissions requirements apply to all three examples.
All three SSH fields must appear together if any is present; unknown fields and
non-boolean allowTypesafe invalidate the file. Without allowTypesafe: true,
hosted requests are not made even if a project selects the hosted provider and
the process has a TypeSafe key. Granting or revoking the flag takes effect on
subsequent decisions without changing the process environment. An already-started
request is not recalled by changing the file.
The model is optional and defaults to jev-latest; other hosted model names and
aliases up to 256 UTF-8 bytes are supported. A process can hold up to 128 distinct
hosted model clients; further new models leave the optional stage off until a
process reload. Set TYPESAFE_API_KEY in the server process environment.
This explicitly sends the bounded complete latest user query and candidate
summaries to https://api.typesafe.ai/v1/systemone, outside your machine; do
not enable it if those contents must remain local. Different models may have
different prediction quality; the existing threshold is not a calibration
guarantee. Unknown or invalid Clef options disable the optional stage. If the
selected service is unavailable or rejects a request, selection fails open.
The endpoint, credential source, executable and command cannot be configured by
project options; redirects are rejected and no new service is started.
Only a primary context hook is added. It considers old, correlated native
Code Mode discovery displays, keeps the newest eligible discovery as working
context, and asks Clef whether older tool capabilities could still be useful
for the complete latest user request. Each batch names every candidate
operation; it sends neither full schemas nor conversation history. A finite
relevance probability at or below 0.02 permits deferral; uncertainty preserves
the complete display. That threshold is conservative policy, not a calibrated
accuracy guarantee.
Eligible displays are 8–64 KiB and must save at least 4 KiB and 25% after
markers. Their historical context-trim/deferred-discovery@1 projection is
independent of the current query and keeps
paths, descriptions, input-signature prefixes, short return types, order,
duplicates and pagination. Large return types are explicitly marked deferred.
Full original displays that are kept, undecided, or newest remain available as
quoted working-context data at the outgoing conversation tail. Semantic decisions
change that working tail rather than repeatedly changing the historical projection.
Operator instructions, skill catalogs/bodies, user/assistant text, tool calls,
tool availability, metadata and persisted history remain unchanged. Protected
namespaces, errors, truncation, mixed/file results, current-turn results,
attachments and unsupported inputs pass through.
Useful calls, not every tool call
- At most one new two-candidate batch per context request. Continuations can advance to additional unclassified candidates; completed keep/defer decisions are reused while the query is unchanged.
- One active call across plugin locations per provider/model (the SSH Clef client is process-wide), at least 1.5 seconds between starts, at most 30 starts per rolling minute and three seconds per session. There is no hourly ration or once-per-turn lockout.
- Thirty-minute success cache, identical in-flight joins, thirty-second failure backoff; no queue, automatic retries, startup calls or auxiliary-request calls. Per-candidate runtime decisions also remain reusable while their complete source and user-query hash are unchanged.
- Complete query up to 512 UTF-8 bytes, two summaries up to 160 bytes each, request body up to 1,400 bytes, 1.5-second timeout, 16 KiB stdout and 2 KiB stderr caps (hosted responses have a 16 KiB streaming cap). Oversize, local Clef token overflow, malformed responses and unavailable services preserve context. Byte limits are not tokenizer guarantees.
Recovery and measurement
Discover the exact context_trim.status and context_trim.control tool paths
through Code Mode search. control with action: "raw" restores original
host-history results on future requests; resume re-enables semantic selection.
No underlying tool is replayed. This does not undo earlier lossless formatting
or native compaction, and the other plugin's /trim raw is a separate control.
Use raw recovery when the default view is insufficient, not preemptively.
Global enabled: false, CONTEXT_TRIM_DISABLED=1, RTK_DISABLED=1 and explicit
raw markers bypass semantic edits. Status reports content-free call/cache/token
and outgoing-byte counters, not queries, schemas, credentials or billing.
Changing a user query may change the selected working tail. Raw controls,
compaction and newly eligible history can still cause deliberate cache transitions;
byte reductions alone are not a dollar-savings claim.
Built against the OpenCode V2 plugin API (@opencode/plugin, pinned to
2.0.32 — see package.json).
Evidence
The actual formatter compacted 200 captured glob samples from 4,048,496 to 2,013,944 bytes, saving 2,034,552 bytes (50.3%). An independent comparison reconstructed all 37,957 paths, order, duplicates and notices exactly. The sample was biased largest-first with a date spread; this is a sample-local byte measurement, not a production forecast or billed-token-saving claim. The Code Mode formatter reduced one captured 12-signature discovery result from 92,435 to 12,303 bytes: 80,132 bytes saved (86.7%). Independent inverse logic reconstructed every original signature and JSON value/key order exactly; the compacted representation was unchanged on a second pass. This is one sample-local offline measurement, not a production forecast or billed-token claim. Already-truncated live displays are intentionally not recovered or rewritten; the full captured result measures the formatter, not that exclusion.
Live V2 verification also passed on two real discovery shapes: a complete two-tool search envelope shrank from 17,656 to 10,544 bytes (40.3%); a projected path/signature array shrank from 15,229 to 8,117 bytes (46.7%). Both restored the corresponding baseline exactly, including key order, with truncation false. These overlap in source data and must not be summed as independent winnings. The server PID stayed unchanged; no restart or extra OpenCode host was used.
Development
bun test src/index.test.ts— adapter wiring tests against a faithful fake context exposing onlyoptionsandtool.hook.bun test src/glob.test.ts— formatter mapping tests with worked examples.bun run typecheck && bun test— complete local checks.
