PI-RTK-OPTIMIZER(1)

NAME

pi-rtk-optimizerPi extension that optimizes RTK command rewriting and tool output compaction for the coding agent.

SYNOPSIS

INFO

123 stars
13 forks
0 views
TypeScriptDeveloper Tools

DESCRIPTION

Pi extension that optimizes RTK command rewriting and tool output compaction for the coding agent.

README

pi-rtk-optimizer

npm version License

RTK command rewriting and tool output compaction extension for the Pi coding agent.

image

pi-rtk-optimizer automatically rewrites bash tool commands to their rtk equivalents and compacts noisy tool output (bash, read, grep) to reduce context window usage while preserving actionable information for the AI agent.

Features

Command Rewriting

  • Automatic rewriting or suggestion-only mode for common development workflows
  • Delegates bash command rewrite decisions to the installed rtk rewrite command, keeping RTK as the source of truth for supported commands, shell parsing, bypasses, and compound-command behavior
  • Runtime guard when rtk binary is unavailable (raw commands run unchanged and repeated missing-binary rewrite probes are avoided)
  • /rtk show and /rtk verify surface the resolved rtk executable path when the host can resolve it
  • Pi-specific shell safety fixups for rewritten commands on Windows

Output Compaction Pipeline

Multi-stage pipeline to reduce token consumption:

StageDescription
ANSI StrippingRemoves terminal color/formatting codes
Test AggregationSummarizes test runner output (pass/fail counts)
Build FilteringExtracts errors/warnings from build output
Git CompactionCondenses git status, git log, git diff output
Linter AggregationSummarizes linting tool output
Search GroupingGroups grep/rg results by file
Source Code Filteringnone, minimal, or aggressive comment/whitespace removal with userscript metadata preservation
Smart TruncationPreserves file boundaries and important lines while keeping 80-line reads exact
Hard TruncationFinal character limit enforcement

Interactive Settings

  • TUI settings modal via /rtk command
  • Real-time configuration changes without restart
  • Command completions for all subcommands

Session Metrics

  • Tracks compaction savings per tool type
  • View statistics with /rtk stats

Installation

Local Extension Folder

Place this folder in one of the following locations:

~/.pi/agent/extensions/pi-rtk-optimizer                 # Global default (when PI_CODING_AGENT_DIR is unset)
$PI_CODING_AGENT_DIR/extensions/pi-rtk-optimizer        # Global when PI_CODING_AGENT_DIR is set
.pi/extensions/pi-rtk-optimizer                         # Project-specific

Pi auto-discovers extensions in these paths on startup.

npm Package

pi install npm:pi-rtk-optimizer

Git Repository

pi install git:github.com/MasuRii/pi-rtk-optimizer

Usage

Settings Modal

Open the interactive settings modal:

/rtk

Use arrow keys to navigate settings, Enter to cycle values, and Escape to close.

Subcommands

CommandDescription
/rtkOpen settings modal
/rtk showDisplay current configuration and runtime status
/rtk pathShow config file path
/rtk verifyCheck if rtk binary is available
/rtk statsShow output compaction metrics for current session
/rtk clear-statsReset compaction metrics
/rtk resetReset all settings to defaults
/rtk helpDisplay usage help

Configuration

Configuration is stored at:

Default global path: ~/.pi/agent/extensions/pi-rtk-optimizer/config.json
Actual global path: $PI_CODING_AGENT_DIR/extensions/pi-rtk-optimizer/config.json when PI_CODING_AGENT_DIR is set

A starter template is included at config/config.example.json.

For audit or debugging sessions, keep showRewriteNotifications enabled and disable lossy read compaction/source filtering before gathering evidence. Existing config.json files are user-owned runtime state; do not overwrite local choices unless you intentionally want to change live extension behavior.

Configuration Options

Top-Level Settings

OptionTypeDefaultDescription
enabledbooleantrueMaster switch for all extension features
modestring"rewrite""rewrite" (auto-rewrite) or "suggest" (notify only)
guardWhenRtkMissingbooleantrueRun original commands when rtk binary unavailable
showRewriteNotificationsbooleantrueShow rewrite notices in TUI

Rewrite Source

Bash command support is intentionally resolved by the installed rtk binary through rtk rewrite. The extension does not maintain duplicate rewrite rules or category classifiers; update/configure RTK itself for command support policy.

Breaking in 0.6.0: Rewrite category toggles (rewriteGitGithub, rewriteFilesystem, rewriteRust, rewriteJavaScript, rewritePython, rewriteGo, rewriteContainers, rewriteNetwork, and rewritePackageManagers) were removed from the extension config surface. Existing rewrite policy should be configured in RTK because the extension now delegates rewrite ownership to rtk rewrite.

Output Compaction Settings

OptionTypeDefaultDescription
outputCompaction.enabledbooleantrueEnable output compaction pipeline
outputCompaction.stripAnsibooleantrueRemove ANSI escape codes
outputCompaction.readCompaction.enabledbooleanfalseEnable lossy compaction for read output; defaults off so code reads stay exact
outputCompaction.sourceCodeFilteringEnabledbooleanfalseEnable source code filtering for read output when read compaction is enabled
outputCompaction.preserveExactSkillReadsbooleanfalseKeep reads under configured Pi/global/project skill directories exact, bypassing read compaction
outputCompaction.sourceCodeFilteringstring"none"Filter level: "none", "minimal", "aggressive"
outputCompaction.aggregateTestOutputbooleantrueSummarize test runner output
outputCompaction.filterBuildOutputbooleantrueFilter build/compile output
outputCompaction.compactGitOutputbooleantrueCompact git command output
outputCompaction.aggregateLinterOutputbooleantrueSummarize linter output
outputCompaction.groupSearchOutputbooleantrueGroup search results by file
outputCompaction.trackSavingsbooleantrueTrack compaction metrics

Skill-read preservation covers the global Pi skills directory (~/.pi/agent/skills by default, or $PI_CODING_AGENT_DIR/skills when set), ~/.agents/skills, project .pi/skills, and ancestor .agents/skills directories.

Truncation Settings

OptionTypeDefaultRangeDescription
outputCompaction.smartTruncate.enabledbooleanfalseEnable smart line-based truncation for read output when read compaction is enabled
outputCompaction.smartTruncate.maxLinesnumber22040–4000Maximum lines after smart truncation
outputCompaction.truncate.enabledbooleantrueEnable hard character truncation
outputCompaction.truncate.maxCharsnumber120001000–200000Maximum characters in final output

Source Code Filtering Levels

LevelBehavior
noneNo filtering applied
minimalRemoves non-doc comments, collapses blank lines
aggressiveAlso removes imports, keeps only signatures and key logic

Note: When read compaction, source filtering, and read truncation safeguards are active, Pi injects a troubleshooting note for repeated file-edit mismatches. If edits fail because "old text does not match," disable read compaction via /rtk, re-read the file, apply the edit, then re-enable compaction.

Example Configuration

{
  "enabled": true,
  "mode": "rewrite",
  "guardWhenRtkMissing": true,
  "showRewriteNotifications": true,
  "outputCompaction": {
    "enabled": true,
    "stripAnsi": true,
    "readCompaction": {
      "enabled": false
    },
    "sourceCodeFilteringEnabled": false,
    "preserveExactSkillReads": false,
    "sourceCodeFiltering": "none",
    "aggregateTestOutput": true,
    "filterBuildOutput": true,
    "compactGitOutput": true,
    "aggregateLinterOutput": true,
    "groupSearchOutput": true,
    "trackSavings": true,
    "smartTruncate": {
      "enabled": false,
      "maxLines": 220
    },
    "truncate": {
      "enabled": true,
      "maxChars": 12000
    }
  }
}

Technical Details

Architecture

index.ts                    # Pi auto-discovery entrypoint
src/
├── index.ts                # Extension bootstrap and event wiring
├── config-store.ts         # Config load/save with normalization
├── config-modal.ts         # TUI settings modal and /rtk handler
├── command-rewriter.ts         # Command rewrite decision adapter for RTK delegation
├── rtk-rewrite-provider.ts     # Calls `rtk rewrite` as the rewrite source of truth
├── rewrite-pipeline-safety.ts  # Shell-safety fixups for rewritten commands
├── rtk-command-environment.ts  # RTK_DB_PATH scoping for rewritten commands
├── shell-env-prefix.ts         # Environment assignment parsing helpers
├── runtime-guard.ts            # Runtime availability guard helpers for rewrite mode
├── output-compactor.ts         # Tool result compaction pipeline
├── output-metrics.ts           # Savings tracking and reporting
├── tool-execution-sanitizer.ts # Streaming bash execution output sanitizer
├── command-completions.ts      # /rtk subcommand completions
├── windows-command-helpers.ts  # Windows bash compatibility
└── techniques/                 # Compaction technique implementations
    ├── ansi.ts             # ANSI code stripping
    ├── build.ts            # Build output filtering
    ├── test-output.ts      # Test output aggregation
    ├── linter.ts           # Linter output aggregation
    ├── git.ts              # Git output compaction
    ├── search.ts           # Search result grouping
    ├── source.ts           # Source code filtering
    └── truncate.ts         # Smart and hard truncation

Event Hooks

The extension hooks into Pi's event system:

  • tool_call — Rewrites bash commands to rtk equivalents or emits suggestions
  • tool_result — Compacts completed tool output before context consumption
  • tool_execution_start / tool_execution_update / tool_execution_end — Tracks and sanitizes streamed bash output
  • before_agent_start — Conditionally injects source-filter troubleshooting guidance
  • session_start / agent_end — Refreshes config and clears in-session tracking state
  • Registered /rtk command — Handles settings, status, verification, stats, and reset subcommands

Windows Compatibility

Automatic fixes applied on Windows:

  • cd /d <path>cd "<normalized-path>" (converts backslashes)
  • Prepends PYTHONIOENCODING=utf-8 for Python commands

Dependencies

  • Peer dependencies: @mariozechner/pi-coding-agent, @mariozechner/pi-tui
  • Runtime: Node.js ≥20, optional rtk binary for command rewriting
  • Development verification: Node.js ≥20, npm, and Bun for the test scripts

Development

# Transpile-only TypeScript build check
npm run build

Full typecheck

npm run typecheck

Run Bun-based tests

npm run test

Full verification

npm run check

Bundle sanity check

npm run build:check

Credits

Inspired by:

Related Pi Extensions

License

MIT © MasuRii

SEE ALSO

clihub5/9/2026PI-RTK-OPTIMIZER(1)