Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions code_puppy/cli_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,12 +395,17 @@ async def interactive_mode(message_renderer, initial_command: str = None) -> Non
if initial_command:
from code_puppy.command_line.shell_passthrough import (
execute_shell_passthrough,
is_known_cli_command,
is_shell_passthrough,
)

if is_shell_passthrough(initial_command):
execute_shell_passthrough(initial_command)
initial_command = None
elif is_known_cli_command(initial_command):
# Auto-detect known CLI commands — bypass AI agent, zero tokens
execute_shell_passthrough(f"!{initial_command.strip()}")
initial_command = None

# Initialize the runtime agent manager
if initial_command:
Expand Down Expand Up @@ -597,13 +602,20 @@ async def interactive_mode(message_renderer, initial_command: str = None) -> Non
# Shell pass-through: !<command> executes directly, bypassing the agent
from code_puppy.command_line.shell_passthrough import (
execute_shell_passthrough,
is_known_cli_command,
is_shell_passthrough,
)

if is_shell_passthrough(task):
execute_shell_passthrough(task)
continue

# Auto-detect known CLI commands (e.g. `ls`, `git status`, `grep …`)
# and route them directly to the shell — zero tokens consumed.
if is_known_cli_command(task):
execute_shell_passthrough(f"!{task.strip()}")
continue

# Check for exit commands (plain text or command form)
if task.strip().lower() in ["exit", "quit"] or task.strip().lower() in [
"/exit",
Expand Down Expand Up @@ -1014,13 +1026,19 @@ async def execute_single_prompt(prompt: str, message_renderer) -> None:
# Shell pass-through: !<cmd> bypasses the agent even in -p mode
from code_puppy.command_line.shell_passthrough import (
execute_shell_passthrough,
is_known_cli_command,
is_shell_passthrough,
)

if is_shell_passthrough(prompt):
execute_shell_passthrough(prompt)
return

# Auto-detect known CLI commands — bypass AI agent, zero tokens consumed
if is_known_cli_command(prompt):
execute_shell_passthrough(f"!{prompt.strip()}")
return

from code_puppy.messaging import emit_info

emit_info(f"Executing prompt: {prompt}")
Expand Down
200 changes: 200 additions & 0 deletions code_puppy/command_line/shell_passthrough.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@
Prepend a prompt with `!` to execute it as a shell command directly,
bypassing the agent entirely. Inspired by Claude Code's `!` prefix.

Also auto-detects well-known CLI commands (e.g. ``ls``, ``git``, ``grep``)
so users can type them without the ``!`` prefix and still bypass the AI agent
— consuming zero tokens.

Examples:
!ls -la
!git status
!python --version
ls -la ← auto-detected, no tokens used
git status ← auto-detected, no tokens used
ls | grep test ← auto-detected, no tokens used
"""

import os
import re
import subprocess
import sys
import time
Expand All @@ -25,6 +33,198 @@
# Banner identifier — matches the key in DEFAULT_BANNER_COLORS
_BANNER_NAME = "shell_passthrough"

# ---------------------------------------------------------------------------
# Auto-detection: known CLI commands that should bypass the AI agent
# ---------------------------------------------------------------------------
# When a user types one of these commands directly (without the ``!`` prefix),
# Code Puppy automatically routes the input to the shell — no tokens consumed.
#
# Extend this set to add more commands. Keep it sorted for readability.
KNOWN_CLI_COMMANDS: frozenset[str] = frozenset(
{
# ── Archives ──────────────────────────────────────────────────────
"bzip2",
"gunzip",
"gzip",
"tar",
"unzip",
"xz",
"zip",
# ── Build / package managers ──────────────────────────────────────
"cargo",
"cmake",
"gradle",
"make",
"maven",
"mvn",
"npm",
"npx",
"pip",
"pip3",
"poetry",
"pnpm",
"yarn",
# ── Containers / orchestration ────────────────────────────────────
"docker",
"docker-compose",
"helm",
"kubectl",
"podman",
# ── File system ───────────────────────────────────────────────────
"cat",
"cd",
"chmod",
"chown",
"cp",
"dir",
"du",
"file",
"find",
"head",
"la",
"less",
"ll",
"ln",
"locate",
"ls",
"mkdir",
"more",
"mv",
"popd",
"pushd",
"pwd",
"rm",
"rmdir",
"tail",
"touch",
"tree",
"wc",
# ── Language runtimes ─────────────────────────────────────────────
"go",
"java",
"javac",
"node",
"python",
"python3",
"ruby",
"rustc",
# ── Misc utilities ────────────────────────────────────────────────
"alias",
"cal",
"date",
"df",
"echo",
"env",
"export",
"free",
"history",
"id",
"info",
"man",
"open",
"pbcopy",
"pbpaste",
"printf",
"type",
"uname",
"unalias",
"uptime",
"which",
"whereis",
"whoami",
"xclip",
"xsel",
# ── Network ───────────────────────────────────────────────────────
"curl",
"dig",
"host",
"ifconfig",
"ip",
"nc",
"netstat",
"nslookup",
"ping",
"rsync",
"scp",
"ssh",
"wget",
# ── Process / system ──────────────────────────────────────────────
"bg",
"fg",
"htop",
"jobs",
"kill",
"killall",
"ps",
"top",
"who",
# ── System package managers ───────────────────────────────────────
"apt",
"apt-get",
"dnf",
"pacman",
"snap",
"systemctl",
"yum",
# ── Text processing ───────────────────────────────────────────────
"awk",
"cut",
"diff",
"egrep",
"fgrep",
"grep",
"jq",
"patch",
"rg",
"ripgrep",
"sed",
"sort",
"tee",
"tr",
"uniq",
"xargs",
# ── Version control ───────────────────────────────────────────────
"git",
"hg",
"svn",
}
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.

# Pre-compiled regex: first "word" of the input (handles leading whitespace)
_FIRST_WORD_RE = re.compile(r"^\s*(\S+)")


def is_known_cli_command(task: str) -> bool:
"""Return True when *task* starts with a well-known CLI command name.

This lets users type ``ls -la`` or ``git status`` directly — without the
``!`` prefix — and have Code Puppy route the input to the shell instead of
the AI agent (zero tokens consumed).

The check is intentionally conservative:
* Only the very first token is tested against ``KNOWN_CLI_COMMANDS``.
* Input that already starts with ``!`` or ``/`` is excluded (handled
elsewhere).
* Single-word inputs that match (e.g. ``pwd``) are accepted.

Args:
task: Raw user input string.

Returns:
True if the first word of *task* is a known CLI command.
"""
stripped = task.strip()
# Already handled by other code paths
if stripped.startswith(SHELL_PASSTHROUGH_PREFIX) or stripped.startswith("/"):
return False

match = _FIRST_WORD_RE.match(stripped)
if not match:
return False

first_word = match.group(1).lower()
return first_word in KNOWN_CLI_COMMANDS


def _get_console() -> Console:
"""Get a Rich console for direct output.
Expand Down
76 changes: 76 additions & 0 deletions tests/test_shell_passthrough.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@

from code_puppy.command_line.shell_passthrough import (
_BANNER_NAME,
KNOWN_CLI_COMMANDS,
SHELL_PASSTHROUGH_PREFIX,
_format_banner,
execute_shell_passthrough,
extract_command,
is_known_cli_command,
is_shell_passthrough,
)

Expand Down Expand Up @@ -69,6 +71,80 @@ def test_prefix_constant(self):
assert SHELL_PASSTHROUGH_PREFIX == "!"


class TestIsKnownCliCommand:
"""Test auto-detection of well-known CLI commands.

Users should be able to type ``ls -la`` or ``git status`` directly and
have Code Puppy route the input to the shell without touching the AI agent
(zero tokens consumed).
"""

# ── Positive cases ────────────────────────────────────────────────────

def test_ls_alone(self):
"""Bare `ls` is a known CLI command."""
assert is_known_cli_command("ls") is True

def test_ls_with_flags(self):
"""`ls -la` is auto-detected."""
assert is_known_cli_command("ls -la") is True

def test_ls_pipe_grep(self):
"""`ls | grep test` is auto-detected via the leading `ls`."""
assert is_known_cli_command("ls | grep test") is True

def test_git_status(self):
"""`git status` is auto-detected."""
assert is_known_cli_command("git status") is True

def test_grep_pattern(self):
"""`grep -r foo .` is auto-detected."""
assert is_known_cli_command("grep -r foo .") is True

def test_pwd(self):
"""Single-word known command is accepted."""
assert is_known_cli_command("pwd") is True

def test_leading_whitespace(self):
"""Leading whitespace before a known command is tolerated."""
assert is_known_cli_command(" ls -la") is True

def test_case_insensitive_first_word(self):
"""First-word check is case-insensitive (LS → ls)."""
assert is_known_cli_command("LS -la") is True

def test_known_commands_set_non_empty(self):
"""KNOWN_CLI_COMMANDS must contain at least the basics."""
for cmd in ("ls", "git", "grep", "cat", "pwd", "find"):
assert cmd in KNOWN_CLI_COMMANDS

# ── Negative cases ────────────────────────────────────────────────────

def test_natural_language_not_detected(self):
"""Natural language prompts must NOT be auto-detected as CLI commands."""
assert is_known_cli_command("write me a python script") is False

def test_slash_command_excluded(self):
"""`/help` is a Code Puppy command, not a shell command."""
assert is_known_cli_command("/help") is False

def test_bang_prefix_excluded(self):
"""`!ls` is already handled by `is_shell_passthrough`; skip here."""
assert is_known_cli_command("!ls") is False

def test_unknown_command(self):
"""An unknown first word is not auto-detected."""
assert is_known_cli_command("frobnicator --foo") is False

def test_empty_string(self):
"""Empty input is not a CLI command."""
assert is_known_cli_command("") is False

def test_whitespace_only(self):
"""Whitespace-only input is not a CLI command."""
assert is_known_cli_command(" ") is False


class TestExtractCommand:
"""Test command extraction from pass-through input."""

Expand Down