omp packages

@samfp/pi-steering-hooks0.4.0

Deterministic tool-call guardrails for pi — enforce rules with before-tool hooks instead of prompts. Zero token cost, 100% reliability.

GitHub Actions Published 25 days ago MIT ~274 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

pi-steering-hooks

Deterministic tool-call guardrails for pi. Enforce rules with before-tool hooks instead of prompts — zero token cost, 100% reliability.

Prompt-based rules ("never force push") work most of the time. Steering hooks work every time. They intercept tool calls before execution and block violations deterministically, with an override escape hatch for when the agent has a good reason.

Inspired by Strands Agents: Steering Accuracy Beats Prompts.

Install

pi install npm:@samfp/pi-steering-hooks

Default Rules

Repo safety:

Rule Tool What it blocks
no-force-push bash git push --force (destructive history rewrite)
no-hard-reset bash git reset --hard (discards uncommitted work)
no-rm-rf-slash bash rm -rf / (catastrophic, no override allowed)
conventional-commits bash Non-conventional git commit -m messages
no-long-running-commands bash Dev servers and watchers that block the agent

File-authoring guardrails (added in 0.3.0): steer the agent toward the write and edit tools (which show diffs and run through LSP) instead of bash commands that author files invisibly.

Rule Tool What it blocks
no-sed-inplace bash sed -i ... (in-place edits without diff review)
no-perl-inplace bash perl -i / perl -pi
no-awk-inplace bash awk -i inplace
no-heredoc-to-file bash cat <<EOF > path and friends authoring source files
no-redirect-source-author bash echo|printf|cat … > file.<sourceext>
no-tee-source bash tee file.<sourceext>

The file-authoring rules have two structural escape hatches so legitimate generation pipelines aren't blocked:

  1. Script pattern — write a tools/refactor.py or scripts/gen.sh, then run it. Subprocess writes are not inspected.
  2. Scratch directories — redirects into /tmp/, /dev/, dist/, build/, generated/, out/, reports/, coverage/, target/, .cache/ are always allowed.

Plus the standard per-command override (# steering-override: <rule> — <reason>) for one-off cases.

If you don't want a default rule, disable it via steering.json:

{ "disable": ["no-tee-source", "conventional-commits"] }

Override Mechanism

When a rule fires, the agent can retry with an override comment:

git push --force origin main  # steering-override: no-force-push — deploying hotfix to unblock prod

The override is allowed through but logged to the session for audit. Rules with noOverride: true (like no-rm-rf-slash) cannot be overridden.

Custom Rules

Create steering.json in your project root or ~/.pi/agent/:

{
  "disable": ["conventional-commits"],
  "rules": [
    {
      "name": "no-git-push",
      "tool": "bash",
      "field": "command",
      "pattern": "\\bgit\\s+push\\b",
      "reason": "Pushes go through the project's review CLI, not `git push`."
    },
    {
      "name": "aws-requires-profile",
      "tool": "bash",
      "field": "command",
      "pattern": "\\baws\\s+[a-z]",
      "unless": "(--profile|AWS_PROFILE=|\\baws\\s+(sts\\s+get-caller-identity|configure)\\b)",
      "reason": "Always use --profile or AWS_PROFILE with aws CLI commands."
    },
    {
      "name": "no-write-env-files",
      "tool": "write",
      "field": "path",
      "pattern": "\\.env",
      "reason": "Don't overwrite .env files — they may contain secrets.",
      "noOverride": true
    }
  ]
}

Rule Format

Field Type Description
name string Unique rule identifier
tool "bash" | "write" | "edit" Which tool to intercept
field "command" | "path" | "content" Which input field to test
pattern string Regex — if it matches, the rule fires (violation)
requires string? Additional regex that must also match (AND condition)
unless string? Regex exemption — if this matches, rule doesn't fire
reason string Message shown to the agent when blocked
noOverride boolean? If true, no override escape hatch

Config Locations

Checked in order (first found wins):

  1. ./steering.json (project root)
  2. ~/.pi/agent/steering.json (global)

Config Errors

A broken config never stops pi from starting. A file that isn't valid JSON is skipped, and the next location (or the default rules) is used. A rule with an invalid regex, or with neither pattern nor test, is skipped; a rules or disable that isn't an array is ignored, so a string disable turns off no rule. Every other rule still applies. Each problem is shown as a notification when the session starts. Outside the interactive TUI (in print, json and RPC mode) it is also printed to stderr.

If a rule throws while it is evaluated, it is treated as not matching, and it is reported the same way, once per rule per session.

How It Works

  1. Extension registers a tool_call hook
  2. On every bash/write/edit call, rules are evaluated against the tool input
  3. If a rule matches: block the call and return the reason to the agent
  4. Agent sees the block message and adjusts its approach
  5. If the agent has a legitimate reason, it can retry with # steering-override: rule-name — reason
  6. Overrides are logged via appendEntry for audit

No tokens spent on rule enforcement. No prompt drift. No "oops, the model forgot the rule this time."

Programmatic API

The package exports its internals so other extensions can build on top:

import {
  // Types
  type Rule, type BashRule, type WriteRule, type EditRule,
  type BashInput, type WriteInput, type EditInput,
  type CompiledRule, type SteeringConfig,

  // Defaults
  DEFAULT_RULES,

  // Path helpers — useful when authoring file-authoring guardrails
  SCRATCH_PATH_PREFIXES, isScratchPath,

  // Shell-string helpers — strip noise before scanning for shell metachars
  stripHeredocBodies, stripQuotedStrings, stripBashComments,

  // Rule lifecycle
  compileRule, buildRules, buildRuleSet, evaluateRule, testRule,

  // Override extraction
  extractOverride,

  // Config loader (`./steering.json` then `~/.pi/agent/steering.json`)
  loadConfig, readConfig,
} from "@samfp/pi-steering-hooks";

Function-form rules (procedural)

When a rule needs more than a regex — e.g. parsing structure, applying multi-stage transforms, or consulting a path allowlist — use the test function form instead of pattern:

import {
  type BashRule,
  isScratchPath,
  stripHeredocBodies,
  stripQuotedStrings,
} from "@samfp/pi-steering-hooks";

const noHeredocToFile: BashRule = {
  name: "no-heredoc-to-file",
  tool: "bash",
  reason:
    "Use the `write` tool to author files. Heredoc-to-file hides content from diff review and skips LSP.",
  test: ({ command }) => {
    if (!/<<[-~]?\s*['"]?\w+['"]?/.test(command)) return false;
    // Strip heredoc bodies + quotes so embedded `>` chars don't false-positive
    // on Python comparisons, awk programs, etc.
    const cleaned = stripQuotedStrings(stripHeredocBodies(command));
    for (const m of cleaned.matchAll(/>>?\s*([^\s|&;<>()]+)/g)) {
      const target = m[1].replace(/^['"]|['"]$/g, "");
      if (target.startsWith("&")) continue;
      if (isScratchPath(target)) continue;
      return true;
    }
    return false;
  },
};

pattern and test are mutually exclusive — compileRule throws if a rule has both or neither. buildRules throws on the first malformed rule; buildRuleSet skips it and returns { rules, errors }, which is what the extension uses. Likewise readConfig returns parse errors instead of logging them.

Function rules can only be added in code (not from steering.json, which is JSON).

Why heredoc-stripping matters

A naive > scan against python3 - <<'EOF' ... if x > 80: ... EOF will treat the Python comparison as a shell redirect to a file named 80:. The exported stripHeredocBodies helper removes heredoc bodies (preserving the opener line, where real shell redirects often live) before metachar scanning. Same logic applies to stripQuotedStrings for grep '>' file style false positives.

The regression case is covered in index.test.ts so it can't come back.

License

MIT