From 0b164ec03bf261663971d68513911c6beccc335b Mon Sep 17 00:00:00 2001 From: Codder-hermes Date: Wed, 30 Sep 2026 21:03:25 +0300 Subject: [PATCH 1/3] feat: ai do, ai commit, ai explain, ai log, -f globs, --copy, --json, .ai.md context, timing footer, zsh Ctrl+G widget --- pyproject.toml | 5 +- src/ai_cli/extras.py | 343 ++++++++++++++++++++++++++ src/ai_cli/main.py | 534 +++++++++++++++++++++++++++++++++-------- tests/test_features.py | 333 +++++++++++++++++++++++++ 4 files changed, 1107 insertions(+), 108 deletions(-) create mode 100644 src/ai_cli/extras.py create mode 100644 tests/test_features.py diff --git a/pyproject.toml b/pyproject.toml index 6faedcb..2e7167e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,9 +4,10 @@ build-backend = "hatchling.build" [project] name = "ai-flow-cli" -version = "0.11.0" +version = "0.12.0" description = "⚡ Fast, beautiful AI CLI wrapper around modern coding harnesses for Unix pipelines" readme = "README.md" +requires-python = ">=3.11" dependencies = [ "rich>=13.0.0", "pylatexenc>=2.10", @@ -43,7 +44,7 @@ pythonpath = ["src"] testpaths = ["tests"] [tool.ruff] -line-length = 110 +line-length = 125 target-version = "py311" [tool.ruff.lint] diff --git a/src/ai_cli/extras.py b/src/ai_cli/extras.py new file mode 100644 index 0000000..b2ed8bd --- /dev/null +++ b/src/ai_cli/extras.py @@ -0,0 +1,343 @@ +"""Helpers for the everyday extras: commit, do, explain, log, files, context, clipboard, zsh. + +Kept free of heavy imports so `ai` startup stays fast. +""" + +from __future__ import annotations + +import glob +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +from pathlib import Path + +# --- limits ---------------------------------------------------------------------- + +CONTEXT_MAX_BYTES = 16_000 +FILE_MAX_BYTES = 200_000 +FILES_TOTAL_MAX_BYTES = 1_000_000 +DIFF_MAX_BYTES = 60_000 + +# Words that make "ai do ..." a normal question ("ai do you know ..."). +DO_QUESTION_WORDS = frozenset({"you", "i", "we", "they", "it", "u", "not", "people", "cats", "dogs"}) + +# --- prompts --------------------------------------------------------------------- + +EXPLAIN_PROMPT = ( + "Explain the following command output or error concisely: what went wrong and why, " + "then how to fix it. If there is a fix command, show it in a code block." +) + +DO_PROMPT = ( + "Translate the request into ONE shell command for {shell} on {os_name}. " + "Working directory: {cwd}. Output ONLY the command on a single line: no explanation, " + "no markdown, no code fences. Chain with && or pipes if needed. " + "If the request is unsafe or impossible, output a command that is `echo` of the reason.\n\n" + "Request: {request}" +) + +COMMIT_PROMPT = ( + "Write a git commit message for the staged diff below. Use Conventional Commits " + "(type(scope): subject), imperative mood, subject max 72 chars. Add a short body " + "(wrapped at 72) only when the change needs explaining. Match the style of the recent " + "commits. Output ONLY the commit message: no code fences, no commentary." +) + + +# --- per-directory context (.ai.md) --------------------------------------------- + + +def _read_capped(path: Path, limit: int) -> str: + try: + data = path.read_bytes()[: limit + 1] + except OSError: + return "" + text = data[:limit].decode("utf-8", errors="replace").strip() + if len(data) > limit: + text += "\n[... truncated]" + return text + + +def find_project_context(start: Path | None = None) -> Path | None: + """Nearest `.ai.md` walking up from cwd, stopping at $HOME or the filesystem root.""" + cur = (start or Path.cwd()).resolve() + home = Path.home().resolve() + while True: + candidate = cur / ".ai.md" + if candidate.is_file(): + return candidate + if cur == home or cur.parent == cur: + return None + cur = cur.parent + + +def build_context_block(config_dir: Path, start: Path | None = None) -> str: + """Global (~/.config/ai/context.md) + nearest project .ai.md, as a prompt preamble.""" + parts = [] + global_ctx = config_dir / "context.md" + if global_ctx.is_file(): + text = _read_capped(global_ctx, CONTEXT_MAX_BYTES) + if text: + parts.append(f"## User context ({global_ctx})\n{text}") + project = find_project_context(start) + if project and project != global_ctx: + text = _read_capped(project, CONTEXT_MAX_BYTES) + if text: + parts.append(f"## Project context ({project})\n{text}") + return "\n\n".join(parts) + + +# --- -f / --file globs ------------------------------------------------------------- + + +def _is_binary(path: Path) -> bool: + try: + with open(path, "rb") as f: + return b"\0" in f.read(2048) + except OSError: + return True + + +def expand_file_args(patterns: list[str]) -> tuple[str, list[str]]: + """Expand globs into fenced file blocks. Returns (block, warnings).""" + seen: list[Path] = [] + warnings: list[str] = [] + for pattern in patterns: + matches = sorted(glob.glob(os.path.expanduser(pattern), recursive=True)) + if not matches: + warnings.append(f"no files match '{pattern}'") + for m in matches: + p = Path(m) + if p.is_file() and p not in seen: + seen.append(p) + + blocks: list[str] = [] + total = 0 + for p in seen: + if _is_binary(p): + warnings.append(f"skipped binary file {p}") + continue + if total >= FILES_TOTAL_MAX_BYTES: + warnings.append(f"total size limit reached, skipped {p} and the rest") + break + text = _read_capped(p, min(FILE_MAX_BYTES, FILES_TOTAL_MAX_BYTES - total)) + total += len(text.encode()) + lang = p.suffix.lstrip(".") + blocks.append(f"### {p}\n```{lang}\n{text}\n```") + return "\n\n".join(blocks), warnings + + +# --- output helpers -------------------------------------------------------------- + +_FENCE_RE = re.compile(r"```[^\n`]*\n(.*?)```", re.S) + + +def first_code_block(text: str) -> str | None: + m = _FENCE_RE.search(text) + return m.group(1).rstrip("\n") if m else None + + +def clean_single_command(text: str) -> str: + """Turn a model answer into one runnable command line.""" + block = first_code_block(text) + body = block if block is not None else text + lines = [ln.strip() for ln in body.strip().splitlines() if ln.strip()] + lines = [ln for ln in lines if not ln.startswith("#")] or lines + cmd = " && ".join(lines) if len(lines) > 1 and block is not None else (lines[0] if lines else "") + cmd = cmd.strip().strip("`").strip() + if cmd.startswith("$ "): + cmd = cmd[2:] + return cmd + + +def clean_commit_message(text: str) -> str: + block = first_code_block(text) + msg = (block if block is not None else text).strip() + return msg.strip("`").strip() + + +def copy_to_clipboard(text: str) -> str | None: + """Copy using wl-copy / xclip / xsel / pbcopy. Returns the tool used, or None.""" + candidates = [] + if os.environ.get("WAYLAND_DISPLAY"): + candidates.append(["wl-copy"]) + candidates += [["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"], ["pbcopy"]] + if not os.environ.get("WAYLAND_DISPLAY"): + candidates.append(["wl-copy"]) + for cmd in candidates: + if shutil.which(cmd[0]): + try: + subprocess.run(cmd, input=text, text=True, check=True, timeout=5) + return cmd[0] + except (OSError, subprocess.SubprocessError): + continue + return None + + +# --- interactive confirm --------------------------------------------------------- + + +def ask_choice(question: str, default: str = "y") -> str: + """[Y/e/n] prompt read from the terminal. Returns 'y', 'e' or 'n'.""" + try: + ans = input(question).strip().lower() + except (EOFError, KeyboardInterrupt): + sys.stderr.write("\n") + return "n" + return (ans or default)[0] if (ans or default)[0] in "yen" else "n" + + +def edit_line(initial: str, prompt: str = "> ") -> str: + """Let the user edit a line in place (readline prefill).""" + try: + import readline + + readline.set_startup_hook(lambda: readline.insert_text(initial)) + try: + return input(prompt).strip() + finally: + readline.set_startup_hook() + except (ImportError, EOFError, KeyboardInterrupt): + return initial + + +# --- git helpers ----------------------------------------------------------------- + + +def git(*args: str) -> subprocess.CompletedProcess: + return subprocess.run(["git", *args], capture_output=True, text=True) + + +def staged_diff() -> str | None: + """Staged diff (capped), or None when not in a git repo / nothing staged.""" + if not shutil.which("git") or git("rev-parse", "--is-inside-work-tree").returncode != 0: + return None + diff = git("diff", "--staged", "--no-color").stdout + if not diff.strip(): + return None + if len(diff) > DIFF_MAX_BYTES: + stat = git("diff", "--staged", "--stat", "--no-color").stdout + diff = f"{stat}\n{diff[:DIFF_MAX_BYTES]}\n[... diff truncated]" + return diff + + +def recent_commits(n: int = 10) -> str: + return git("log", f"-{n}", "--pretty=format:%s").stdout.strip() + + +# --- session log ----------------------------------------------------------------- + + +def read_session_messages(path: Path) -> list[dict[str, str]]: + from ai_cli.main import _extract_text_from_content + + messages: list[dict[str, str]] = [] + try: + with open(path, encoding="utf-8") as f: + for line in f: + try: + data = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(data, dict) and data.get("type") == "message": + msg = data.get("message", {}) + if msg.get("role") in ("user", "assistant"): + text = _extract_text_from_content(msg.get("content")).strip() + if text: + messages.append({"role": msg["role"], "content": text}) + except OSError: + pass + return messages + + +def _first_user_line(messages: list[dict[str, str]]) -> str: + for m in messages: + if m["role"] == "user": + # skip the context preamble we inject + text = m["content"] + if text.startswith("## ") and "\n\n" in text: + text = text.rsplit("\n\n", 1)[-1] + return " ".join(text.split())[:100] + return "(empty)" + + +def list_sessions(cache_dir: Path) -> list[dict]: + from datetime import datetime + + out = [] + for path in cache_dir.glob("*/*/*.jsonl"): + msgs = read_session_messages(path) + if not msgs: + continue + mtime = path.stat().st_mtime + out.append( + { + "path": str(path), + "harness": path.parent.parent.name, + "when": datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M"), + "mtime": mtime, + "turns": sum(1 for m in msgs if m["role"] == "user"), + "title": _first_user_line(msgs), + } + ) + return sorted(out, key=lambda s: s["mtime"], reverse=True) + + +def format_transcript(messages: list[dict[str, str]]) -> str: + parts = [] + for m in messages: + label = "**You**" if m["role"] == "user" else "**AI**" + parts.append(f"{label}\n\n{m['content']}") + return "\n\n---\n\n".join(parts) + + +def self_command() -> str: + """Shell-quoted way to re-invoke this CLI (for fzf previews).""" + argv0 = sys.argv[0] if sys.argv else "" + if argv0 and os.path.isfile(argv0) and os.access(argv0, os.X_OK): + return shlex.quote(os.path.abspath(argv0)) + return f"{shlex.quote(sys.executable)} -m ai_cli.main" + + +def pick_session_fzf(sessions: list[dict]) -> str | None: + lines = [f"{s['path']}\t{s['when']} {s['harness']:<8} {s['turns']:>3}× {s['title']}" for s in sessions] + preview = f"{self_command()} --show-session {{1}}" + try: + proc = subprocess.run( + [ + "fzf", "--delimiter", "\t", "--with-nth", "2..", "--no-sort", + "--prompt", "ai log> ", "--preview", preview, + "--preview-window", "right,60%,wrap", "--height", "90%", + ], + input="\n".join(lines), + text=True, + stdout=subprocess.PIPE, + ) + except OSError: + return None + if proc.returncode != 0 or not proc.stdout.strip(): + return None + return proc.stdout.split("\t", 1)[0].strip() + + +# --- zsh widget -------------------------------------------------------------------- + +ZSH_SNIPPET = r"""# ai-flow-cli zsh integration — add to ~/.zshrc: +# eval "$(ai --zsh)" +# Ctrl+G (or $AI_ZSH_KEY) turns the text on your command line into a shell command. +_ai_flow_widget() { + [[ -z "$BUFFER" ]] && return + local orig="$BUFFER" out + BUFFER="⏳ $orig"; zle -R + out=$(ai do --print -- "$orig" /dev/null) + if [[ -n "$out" ]]; then BUFFER="$out"; else BUFFER="$orig"; fi + CURSOR=${#BUFFER} + zle -R +} +zle -N _ai_flow_widget +bindkey "${AI_ZSH_KEY:-^G}" _ai_flow_widget +""" diff --git a/src/ai_cli/main.py b/src/ai_cli/main.py index 0347776..7eab537 100755 --- a/src/ai_cli/main.py +++ b/src/ai_cli/main.py @@ -566,10 +566,19 @@ def print_help() -> None: ai ai [options] cat file | ai - git diff | ai "review these changes" + +Commands: + ai do Propose a shell command, then [Y]es run / [e]dit / [n]o + ai commit Commit message from the staged diff, confirm, then git commit + ai explain Explain piped output/errors: make 2>&1 | ai explain + ai log [query] Browse/search past sessions (fzf), -a to print all matches Options: + -f, --file Add file(s) as context (repeatable, quote globs: 'src/**/*.py') + -c, --copy Copy the answer (first code block if any) to the clipboard + --json Machine-readable output: {{"response", "harness", "model", "seconds"}} --raw Output raw text directly without markdown rendering + --no-context Don't inject ~/.config/ai/context.md or the nearest .ai.md --no-tools, -nt Disable tool execution so the AI has no access to tools --tools, -t Enable tool execution / auto-approval (default: enabled) --new Start a new session for this terminal (wipe previous context) @@ -577,29 +586,31 @@ def print_help() -> None: --clear Clear session history for current terminal tab and exit -a, --agent Use specific agent harness ({supported}) -H, --handoff [name] Handoff current session context to harness TUI - --wizard Interactive selector to choose and save default harness -m, --model Specify model name override + --wizard Interactive selector to choose and save default harness + --zsh Print zsh widget (Ctrl+G: command line -> shell command) -V, --version Show version and exit -h, --help Show this help message -- Stop option parsing; everything after is the prompt +Context: + ~/.config/ai/context.md and the nearest .ai.md (walking up from cwd) are added to + every prompt. Put project conventions there. + Environment: AI_HARNESS Default harness (overrides ~/.config/ai/config.json) - -Session Persistence: - Queries in the same terminal tab/pane automatically share context. - Use --new or --clear to reset, or --no-session for one-off ephemeral questions. + AI_NO_FOOTER=1 Hide the "harness · model · time" footer Examples: ai "how do I extract a .tar.gz file?" - ai "what was the command you just suggested?" - ai --new "start a completely different topic" - cat main.py | ai "explain what this code does" - git diff | ai "write a concise commit message for this diff" - ai -a claude "how to optimize this query?" + ai do find files over 100MB in home + git add -p && ai commit + cargo build 2>&1 | ai explain + ai -f 'src/**/*.luau' "where is the save logic?" + ai -c "regex for an email address" + ai log "rojo" ai -H omp "continue this task and write the files" - ai -H claude - ai --wizard + eval "$(ai --zsh)" # in ~/.zshrc """ print(help_text) @@ -611,6 +622,7 @@ def _run_harness(cmd: list[str]) -> tuple[str, str]: cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + stdin=subprocess.DEVNULL, text=True, ) stdout_data, stderr_data = proc.communicate() @@ -626,137 +638,447 @@ def _run_harness(cmd: list[str]) -> tuple[str, str]: return stdout_data, stderr_data -def main() -> None: - args = sys.argv[1:] +def _do_question_words() -> frozenset[str]: + from ai_cli.extras import DO_QUESTION_WORDS - if args and args[0] in ("-V", "--version"): - from ai_cli import __version__ + return DO_QUESTION_WORDS - print(f"ai-flow-cli {__version__}") - sys.exit(0) - # Check for wizard flag immediately - if "--wizard" in args: - run_harness_wizard(console=_make_console(), current_harness=load_config().get("harness")) - sys.exit(0) +SUBCOMMANDS = frozenset({"do", "commit", "explain", "log"}) - # Check for clear session flag - if "--clear" in args: - clear_terminal_session() - print("Session cleared for this terminal.") - sys.exit(0) - if not args and sys.stdin.isatty(): - print_help() - sys.exit(0) +class Options: + """Parsed command-line options.""" - # Check for help flag - if any(arg in ("-h", "--help") for arg in args): - print_help() - sys.exit(0) + def __init__(self) -> None: + self.raw = False + self.enable_tools = True + self.session_mode = "auto" + self.model: str | None = None + self.harness: str | None = None + self.handoff = False + self.handoff_harness: str | None = None + self.copy = False + self.json = False + self.use_context = True + self.files: list[str] = [] + self.print_only = False # `ai do --print` + self.all_matches = False # `ai log -a` + self.words: list[str] = [] + + @property + def prompt(self) -> str: + return " ".join(self.words).strip() - # Parse our custom options - raw_mode = False - enable_tools = True - session_mode = "auto" - model_override = None - cli_harness = None - handoff_mode = False - handoff_harness = None - prompt_words = [] +def parse_args(args: list[str]) -> Options: + o = Options() i = 0 while i < len(args): arg = args[i] + nxt = args[i + 1] if i + 1 < len(args) else None if arg == "--": - prompt_words.extend(args[i + 1 :]) + o.words.extend(args[i + 1 :]) break if arg == "--raw": - raw_mode = True + o.raw = True elif arg in ("--tools", "-t"): - enable_tools = True + o.enable_tools = True elif arg in ("--no-tools", "-nt", "--without-tools"): - enable_tools = False + o.enable_tools = False elif arg == "--new": - session_mode = "new" + o.session_mode = "new" elif arg == "--no-session": - session_mode = "none" - elif arg in ("-a", "--agent", "--harness", "-m", "--model"): - if i + 1 < len(args): - if arg in ("-m", "--model"): - model_override = args[i + 1] - else: - cli_harness = args[i + 1] - i += 1 - else: - prompt_words.append(arg) + o.session_mode = "none" + elif arg in ("-c", "--copy"): + o.copy = True + elif arg == "--json": + o.json = True + elif arg == "--no-context": + o.use_context = False + elif arg == "--print": + o.print_only = True + elif arg in ("--all",): + o.all_matches = True + elif arg in ("-f", "--file") and nxt is not None: + o.files.append(nxt) + i += 1 + elif arg.startswith("--file="): + o.files.append(arg.split("=", 1)[1]) + elif arg in ("-a", "--agent", "--harness") and nxt is not None: + o.harness = nxt + i += 1 + elif arg in ("-m", "--model") and nxt is not None: + o.model = nxt + i += 1 elif arg.startswith(("--agent=", "--harness=")): - cli_harness = arg.split("=", 1)[1] + o.harness = arg.split("=", 1)[1] elif arg.startswith("--model="): - model_override = arg.split("=", 1)[1] + o.model = arg.split("=", 1)[1] elif arg in ("-H", "--handoff"): - handoff_mode = True - nxt = args[i + 1].lower() if i + 1 < len(args) else "" - if nxt in HARNESS_REGISTRY: - handoff_harness = nxt + o.handoff = True + if nxt is not None and nxt.lower() in HARNESS_REGISTRY: + o.handoff_harness = nxt.lower() i += 1 elif arg.startswith("--handoff="): - handoff_mode = True - handoff_harness = arg.split("=", 1)[1].strip().lower() or None + o.handoff = True + o.handoff_harness = arg.split("=", 1)[1].strip().lower() or None else: - prompt_words.append(arg) + o.words.append(arg) i += 1 + return o - prompt = " ".join(prompt_words).strip() - # Handle piped stdin - stdin_content = "" - if not sys.stdin.isatty(): - try: - stdin_content = sys.stdin.read().strip() - except (OSError, UnicodeDecodeError): - pass +def _read_stdin() -> str: + if sys.stdin.isatty(): + return "" + try: + return sys.stdin.read().strip() + except (OSError, UnicodeDecodeError): + return "" + + +def _compose_prompt(opts: Options, body: str) -> str: + """Prepend context files and -f files to the prompt body.""" + from ai_cli import extras + + sections = [] + if opts.use_context: + ctx = extras.build_context_block(CONFIG_DIR) + if ctx: + sections.append(ctx) + if opts.files: + block, warnings = extras.expand_file_args(opts.files) + for w in warnings: + sys.stderr.write(f"ai: {w}\n") + if block: + sections.append(f"## Files\n{block}") + sections.append(body) + return "\n\n".join(s for s in sections if s) + + +def query_harness( + opts: Options, prompt: str, console: Any | None = None, status: str = "Thinking" +) -> tuple[str, str, float]: + """Resolve harness, run the prompt. Returns (stdout, harness_name, seconds).""" + import time + + harness_name = resolve_harness(opts.harness, console=console) + if not shutil.which(harness_name): + _harness_missing_error(harness_name) + builder = HARNESS_REGISTRY[harness_name]["builder"] + cmd = builder(opts.model, opts.enable_tools, prompt, session_mode=opts.session_mode) + + t0 = time.monotonic() + if console is not None: + with console.status(f"[bold blue]{status} ({harness_name})...[/bold blue]", spinner="dots"): + out, err = _run_harness(cmd) + else: + out, err = _run_harness(cmd) + elapsed = time.monotonic() - t0 + if not out and err: + sys.stderr.write(err) + return out or "", harness_name, elapsed + + +def _footer(console: Any | None, harness: str, model: str | None, seconds: float) -> None: + if os.environ.get("AI_NO_FOOTER"): + return + text = f"{harness}{' · ' + model if model else ''} · {seconds:.1f}s" + if console is not None: + console.print(f"[grey50]{text}[/grey50]", justify="right", highlight=False) + elif sys.stderr.isatty(): + sys.stderr.write(f"\x1b[90m{text}\x1b[0m\n") + + +def _emit(opts: Options, out: str, harness: str, seconds: float, console: Any | None) -> None: + """Print a normal answer in the requested format, then handle --copy and footer.""" + from ai_cli import extras + + if opts.json: + payload = { + "response": out.strip(), + "harness": harness, + "model": opts.model, + "seconds": round(seconds, 2), + } + code = extras.first_code_block(out) + if code is not None: + payload["code"] = code + print(json.dumps(payload, ensure_ascii=False)) + elif console is not None: + if out: + render_mixed_markdown_with_math(out.strip(), console) + elif out: + sys.stdout.write(sanitize_inline_math(out)) + if not out.endswith("\n"): + sys.stdout.write("\n") + sys.stdout.flush() + + if opts.copy and out: + code = extras.first_code_block(out) + tool = extras.copy_to_clipboard(code if code is not None else out.strip()) + what = "code block" if code is not None else "answer" + msg = f"✓ copied {what} ({tool})" if tool else "✗ no clipboard tool found (install wl-clipboard)" + sys.stderr.write(f"\x1b[90m{msg}\x1b[0m\n" if sys.stderr.isatty() else msg + "\n") + + if not opts.json: + _footer(console, harness, opts.model, seconds) + + +def _console_for(opts: Options) -> Any | None: + render = sys.stdout.isatty() and not opts.raw and not opts.json and HAS_RICH + return _make_console() if render else None + + +# --- subcommands ----------------------------------------------------------------- + + +def cmd_explain(opts: Options) -> None: + from ai_cli import extras + + piped = _read_stdin() + if not piped and not opts.prompt and not opts.files: + sys.stderr.write("usage: 2>&1 | ai explain [extra question]\n") + sys.exit(2) + body = f"{extras.EXPLAIN_PROMPT}\n\n```\n{piped}\n```" if piped else extras.EXPLAIN_PROMPT + if opts.prompt: + body = f"{body}\n\n{opts.prompt}" + console = _console_for(opts) + out, harness, secs = query_harness(opts, _compose_prompt(opts, body), console, status="Explaining") + _emit(opts, out, harness, secs, console) + + +def cmd_do(opts: Options) -> None: + from ai_cli import extras + + request = opts.prompt or _read_stdin() + if not request: + sys.stderr.write("usage: ai do \n") + sys.exit(2) + shell = os.path.basename(os.environ.get("SHELL", "sh")) + os_name = "Linux" if sys.platform.startswith("linux") else sys.platform + prompt = extras.DO_PROMPT.format(shell=shell, os_name=os_name, cwd=os.getcwd(), request=request) + opts.enable_tools = False + opts.session_mode = "none" + console = None if opts.print_only else _console_for(opts) + out, harness, secs = query_harness(opts, _compose_prompt(opts, prompt), console, status="Thinking") + command = extras.clean_single_command(out) + if not command: + sys.stderr.write("ai: no command produced\n") + sys.exit(1) + + if opts.print_only or opts.json: + print(json.dumps({"command": command, "harness": harness, "seconds": round(secs, 2)}) if opts.json else command) + return + if opts.copy: + extras.copy_to_clipboard(command) + + if console is not None: + from rich.syntax import Syntax + + console.print(Syntax(command, "bash", theme="ansi_dark", background_color="default", word_wrap=True)) + else: + sys.stderr.write(f"$ {command}\n") + _footer(console, harness, opts.model, secs) + + if not os.isatty(0) and not _reopen_tty(): + print(command) + return + choice = extras.ask_choice("Run it? [Y/e/n] ") + if choice == "e": + command = extras.edit_line(command) + choice = "y" if command else "n" + if choice != "y": + sys.exit(1) + _append_shell_history(command) + sys.exit(subprocess.call(command, shell=True, executable=os.environ.get("SHELL") or None)) + + +def _reopen_tty() -> bool: + """When stdin was piped, reattach it to the terminal for the confirm prompt.""" + try: + fd = os.open("/dev/tty", os.O_RDONLY) + except OSError: + return False + os.dup2(fd, 0) + os.close(fd) + sys.stdin = open(0, closefd=False) + return True + + +def _append_shell_history(command: str) -> None: + """Best effort: add the executed command to zsh/bash history file.""" + import time + + shell = os.path.basename(os.environ.get("SHELL", "")) + histfile = os.environ.get("HISTFILE") or str(Path.home() / (".zsh_history" if shell == "zsh" else ".bash_history")) + try: + with open(histfile, "a", encoding="utf-8") as f: + if shell == "zsh": + f.write(f": {int(time.time())}:0;{command}\n") + else: + f.write(command + "\n") + except OSError: + pass + + +def cmd_commit(opts: Options) -> None: + from ai_cli import extras + + diff = extras.staged_diff() + if diff is None: + sys.stderr.write("ai commit: nothing staged (git add first) or not a git repository\n") + sys.exit(1) + body = f"{extras.COMMIT_PROMPT}\n\nRecent commits:\n{extras.recent_commits()}\n\nStaged diff:\n```diff\n{diff}\n```" + if opts.prompt: + body += f"\n\nExtra instruction: {opts.prompt}" + opts.enable_tools = False + opts.session_mode = "none" + console = None if opts.print_only else _console_for(opts) + out, harness, secs = query_harness(opts, _compose_prompt(opts, body), console, status="Writing commit") + message = extras.clean_commit_message(out) + if not message: + sys.stderr.write("ai commit: empty message\n") + sys.exit(1) + if opts.print_only or not sys.stdin.isatty(): + print(message) + return + + if console is not None: + from rich.panel import Panel + + console.print(Panel(message, title="commit message", border_style="grey50", expand=False)) + else: + print(f"\n{message}\n") + _footer(console, harness, opts.model, secs) + + choice = extras.ask_choice("Commit? [Y/e/n] ") + if choice == "n": + sys.exit(1) + if choice == "e": + sys.exit(subprocess.call(["git", "commit", "-e", "-m", message])) + sys.exit(subprocess.call(["git", "commit", "-m", message])) + + +def cmd_log(opts: Options) -> None: + from ai_cli import extras + + sessions = extras.list_sessions(CACHE_DIR) + query = opts.prompt.lower() + if query: + sessions = [ + s for s in sessions + if query in s["title"].lower() + or any(query in m["content"].lower() for m in extras.read_session_messages(Path(s["path"]))) + ] + if not sessions: + sys.stderr.write("ai log: no sessions found" + (f" matching '{opts.prompt}'" if query else "") + "\n") + sys.exit(1) + + if opts.json: + print(json.dumps([{k: v for k, v in s.items() if k != "mtime"} for s in sessions], ensure_ascii=False)) + return + + interactive = sys.stdout.isatty() and sys.stdin.isatty() and shutil.which("fzf") and not opts.all_matches + if interactive: + chosen = extras.pick_session_fzf(sessions) + if chosen: + _show_session(Path(chosen), opts) + return + for s in sessions: + print(f"{s['when']} {s['harness']:<8} {s['turns']:>3}× {s['title']}") + + +def _show_session(path: Path, opts: Options) -> None: + from ai_cli import extras + + text = extras.format_transcript(extras.read_session_messages(path)) + console = _console_for(opts) + if console is not None: + render_mixed_markdown_with_math(text, console) + else: + print(text) + + +def main() -> None: + args = sys.argv[1:] + + if args and args[0] in ("-V", "--version"): + from ai_cli import __version__ + + print(f"ai-flow-cli {__version__}") + sys.exit(0) + if args[:1] == ["--zsh"]: + from ai_cli.extras import ZSH_SNIPPET + + print(ZSH_SNIPPET) + sys.exit(0) + + if args[:1] == ["--show-session"] and len(args) > 1: + _show_session(Path(args[1]), parse_args(args[2:])) + sys.exit(0) + + # Check for wizard flag immediately + if "--wizard" in args: + run_harness_wizard(console=_make_console(), current_harness=load_config().get("harness")) + sys.exit(0) + + # Check for clear session flag + if "--clear" in args: + clear_terminal_session() + print("Session cleared for this terminal.") + sys.exit(0) + + if not args and sys.stdin.isatty(): + print_help() + sys.exit(0) + + # Check for help flag (before "--" only) + head = args[: args.index("--")] if "--" in args else args + if any(arg in ("-h", "--help") for arg in head): + print_help() + sys.exit(0) + + # Subcommands: first word only, and `ai do you know ...` stays a question. + if args and args[0] in SUBCOMMANDS: + sub = args[0] + rest = args[1:] + is_question = sub == "do" and rest[:1] and rest[0].lower() in _do_question_words() + if not is_question: + opts = parse_args(rest) + if sub == "log" and opts.harness is not None and opts.harness not in HARNESS_REGISTRY: + # `ai log -a rojo`: -a means "print all" here, not --agent + opts.all_matches = True + opts.words.insert(0, opts.harness) + opts.harness = None + elif sub == "log" and "-a" in rest and opts.harness is None: + opts.all_matches = True + {"do": cmd_do, "commit": cmd_commit, "explain": cmd_explain, "log": cmd_log}[sub](opts) + return + + opts = parse_args(args) + prompt = opts.prompt + + stdin_content = _read_stdin() if stdin_content: prompt = f"{stdin_content}\n\n{prompt}" if prompt else stdin_content # Handoff mode: transfer context to harness TUI and open it - if handoff_mode: - target = handoff_harness or cli_harness or resolve_harness(None, console=_make_console()) + if opts.handoff: + target = opts.handoff_harness or opts.harness or resolve_harness(None, console=_make_console()) execute_handoff(target_harness=target, extra_instruction=prompt) return - if not prompt: + if not prompt and not opts.files: print_help() sys.exit(1) - # Only build a Rich console when we will actually render to a terminal. - render = sys.stdout.isatty() and not raw_mode and HAS_RICH - console = _make_console() if render else None - - harness_name = resolve_harness(cli_harness, console=console) - if not shutil.which(harness_name): - _harness_missing_error(harness_name) - - builder = HARNESS_REGISTRY[harness_name]["builder"] - cmd = builder(model_override, enable_tools, prompt, session_mode=session_mode) - - if render and console is not None: - # Show clean spinner while harness processes - with console.status(f"[bold blue]Thinking ({harness_name})...[/bold blue]", spinner="dots"): - stdout_data, stderr_data = _run_harness(cmd) - if stdout_data: - render_mixed_markdown_with_math(stdout_data.strip(), console) - elif stderr_data: - sys.stderr.write(stderr_data) - else: - # Piped stdout or raw mode or no rich: direct output - stdout_data, stderr_data = _run_harness(cmd) - if stdout_data: - sys.stdout.write(sanitize_inline_math(stdout_data)) - sys.stdout.flush() - elif stderr_data: - sys.stderr.write(stderr_data) + console = _console_for(opts) + full_prompt = _compose_prompt(opts, prompt or "Review these files.") + out, harness, secs = query_harness(opts, full_prompt, console) + _emit(opts, out, harness, secs, console) if __name__ == "__main__": diff --git a/tests/test_features.py b/tests/test_features.py new file mode 100644 index 0000000..5a1d156 --- /dev/null +++ b/tests/test_features.py @@ -0,0 +1,333 @@ +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +from ai_cli import extras +from ai_cli import main as cli + + +class FakeProc: + def __init__(self, out="output", err="", rc=0): + self.returncode = rc + self._out, self._err = out, err + + def communicate(self): + return self._out, self._err + + +@pytest.fixture +def harness(monkeypatch): + """Only `pi` installed; every call returns `state['out']`. Captures commands.""" + state = {"out": "answer\n", "calls": []} + + def fake_run(cmd): + state["calls"].append(cmd) + return state["out"], "" + + real_which = __import__("shutil").which + monkeypatch.setattr( + "shutil.which", lambda name: f"/usr/bin/{name}" if name == "pi" else real_which(name) if name == "git" else None + ) + monkeypatch.setattr(cli, "_run_harness", fake_run) + monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False) + monkeypatch.setenv("AI_NO_FOOTER", "1") + return state + + +def run(monkeypatch, *argv): + monkeypatch.setattr(sys, "argv", ["ai", *argv]) + cli.main() + + +def prompt_of(state): + return state["calls"][-1][-1] + + +# --- 1. --json --------------------------------------------------------------------- + + +def test_json_output(monkeypatch, harness, capsys): + harness["out"] = "Use this:\n```bash\nls -la\n```\n" + run(monkeypatch, "--json", "--no-session", "list files") + data = json.loads(capsys.readouterr().out) + assert data["harness"] == "pi" + assert data["code"] == "ls -la" + assert "ls -la" in data["response"] + assert isinstance(data["seconds"], float) + + +# --- 2. --copy --------------------------------------------------------------------- + + +def test_copy_prefers_code_block(monkeypatch, harness, capsys): + copied = [] + monkeypatch.setattr(extras, "copy_to_clipboard", lambda t: copied.append(t) or "wl-copy") + harness["out"] = "Try\n```\nrg foo\n```\n" + run(monkeypatch, "-c", "--raw", "--no-session", "search") + assert copied == ["rg foo"] + assert "copied code block" in capsys.readouterr().err + + +def test_copy_whole_answer_without_code(monkeypatch, harness): + copied = [] + monkeypatch.setattr(extras, "copy_to_clipboard", lambda t: copied.append(t) or "wl-copy") + harness["out"] = "just text\n" + run(monkeypatch, "--copy", "--raw", "--no-session", "q") + assert copied == ["just text"] + + +# --- 3. -f globs ---------------------------------------------------------------------- + + +def test_file_globs_are_added(monkeypatch, harness, tmp_path): + (tmp_path / "a.py").write_text("print('A')\n") + (tmp_path / "b.py").write_text("print('B')\n") + (tmp_path / "bin.dat").write_bytes(b"\0\1\2") + monkeypatch.chdir(tmp_path) + run(monkeypatch, "-f", "*.py", "-f", "*.dat", "--raw", "--no-session", "--no-context", "review") + p = prompt_of(harness) + assert "### a.py" in p and "print('B')" in p + assert "bin.dat" not in p.split("## Files", 1)[1].split("review")[0] or "\0" not in p + assert p.rstrip().endswith("review") + + +def test_file_glob_without_prompt(monkeypatch, harness, tmp_path): + (tmp_path / "x.txt").write_text("hello") + monkeypatch.chdir(tmp_path) + run(monkeypatch, "--file=x.txt", "--raw", "--no-session", "--no-context") + assert "hello" in prompt_of(harness) + + +def test_missing_glob_warns(tmp_path): + block, warnings = extras.expand_file_args([str(tmp_path / "nope*.py")]) + assert block == "" and "no files match" in warnings[0] + + +# --- 4. per-dir context -------------------------------------------------------------- + + +def test_project_and_global_context(monkeypatch, harness, tmp_path, isolated_dirs): + proj = tmp_path / "proj" / "sub" + proj.mkdir(parents=True) + (tmp_path / "proj" / ".ai.md").write_text("Use Luau strict mode.") + cfg = isolated_dirs / "config" + cfg.mkdir(parents=True, exist_ok=True) + (cfg / "context.md").write_text("I use Arch + niri.") + monkeypatch.setattr(Path, "home", lambda: tmp_path) + monkeypatch.chdir(proj) + run(monkeypatch, "--raw", "--no-session", "hi") + p = prompt_of(harness) + assert "Use Luau strict mode." in p and "I use Arch + niri." in p + run(monkeypatch, "--raw", "--no-session", "--no-context", "hi") + assert prompt_of(harness).strip() == "hi" + + +def test_context_stops_at_home(monkeypatch, tmp_path): + (tmp_path / ".ai.md").write_text("outside") + home = tmp_path / "home" + (home / "p").mkdir(parents=True) + monkeypatch.setattr(Path, "home", lambda: home) + assert extras.find_project_context(home / "p") is None + + +# --- 5. explain ------------------------------------------------------------------------ + + +def test_explain_wraps_piped_output(monkeypatch, harness): + monkeypatch.setattr(cli, "_read_stdin", lambda: "error: E0382 borrow of moved value") + run(monkeypatch, "explain", "--raw", "--no-context") + p = prompt_of(harness) + assert "what went wrong" in p and "E0382" in p + + +def test_explain_without_input_errors(monkeypatch, harness): + monkeypatch.setattr(cli, "_read_stdin", lambda: "") + with pytest.raises(SystemExit) as e: + run(monkeypatch, "explain") + assert e.value.code == 2 + + +# --- 6. do ------------------------------------------------------------------------------ + + +@pytest.mark.parametrize( + ("raw", "cmd"), + [ + ("ls -la\n", "ls -la"), + ("```bash\nfind . -size +100M\n```", "find . -size +100M"), + ("`du -sh *`", "du -sh *"), + ("$ echo hi", "echo hi"), + ("```sh\ncd /tmp\nls\n```", "cd /tmp && ls"), + ], +) +def test_clean_single_command(raw, cmd): + assert extras.clean_single_command(raw) == cmd + + +def test_do_print_mode(monkeypatch, harness, capsys): + harness["out"] = "```bash\nfind ~ -size +100M\n```" + run(monkeypatch, "do", "--print", "big", "files") + assert capsys.readouterr().out.strip() == "find ~ -size +100M" + cmd = harness["calls"][-1] + assert "--no-tools" in cmd and "--no-session" in cmd + assert "big files" in cmd[-1] + + +def test_do_confirm_runs(monkeypatch, harness): + harness["out"] = "echo ok" + ran = [] + monkeypatch.setattr(extras, "ask_choice", lambda q, default="y": "y") + monkeypatch.setattr(cli, "_append_shell_history", lambda c: None) + monkeypatch.setattr("subprocess.call", lambda c, **k: ran.append(c) or 0) + monkeypatch.setattr("os.isatty", lambda fd: True) + with pytest.raises(SystemExit) as e: + run(monkeypatch, "do", "--raw", "say ok") + assert e.value.code == 0 and ran == ["echo ok"] + + +def test_do_decline(monkeypatch, harness): + harness["out"] = "rm -rf /tmp/x" + monkeypatch.setattr(extras, "ask_choice", lambda q, default="y": "n") + monkeypatch.setattr("os.isatty", lambda fd: True) + monkeypatch.setattr("subprocess.call", lambda *a, **k: pytest.fail("must not run")) + with pytest.raises(SystemExit) as e: + run(monkeypatch, "do", "--raw", "clean tmp") + assert e.value.code == 1 + + +def test_do_you_know_is_a_question(monkeypatch, harness, capsys): + run(monkeypatch, "do", "you", "know", "rust?", "--raw", "--no-session", "--no-context") + assert prompt_of(harness) == "do you know rust?" + + +# --- 7. commit -------------------------------------------------------------------------- + + +@pytest.fixture +def repo(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + g = lambda *a: subprocess.run(["git", *a], check=True, capture_output=True) # noqa: E731 + g("init", "-q") + g("config", "user.email", "t@t") + g("config", "user.name", "t") + (tmp_path / "f.txt").write_text("one\n") + g("add", ".") + g("commit", "-qm", "feat: initial") + return g + + +def test_commit_nothing_staged(monkeypatch, harness, repo): + with pytest.raises(SystemExit) as e: + run(monkeypatch, "commit") + assert e.value.code == 1 + + +def test_commit_print(monkeypatch, harness, repo, tmp_path, capsys): + (tmp_path / "f.txt").write_text("two\n") + repo("add", ".") + harness["out"] = "```\nfix(f): change one to two\n```" + run(monkeypatch, "commit", "--print", "--no-context") + assert capsys.readouterr().out.strip() == "fix(f): change one to two" + p = prompt_of(harness) + assert "+two" in p and "feat: initial" in p + + +def test_commit_confirm_commits(monkeypatch, harness, repo, tmp_path): + (tmp_path / "f.txt").write_text("three\n") + repo("add", ".") + harness["out"] = "chore: three" + monkeypatch.setattr(extras, "ask_choice", lambda q, default="y": "y") + with pytest.raises(SystemExit) as e: + run(monkeypatch, "commit", "--raw", "--no-context") + assert e.value.code == 0 + log = subprocess.run(["git", "log", "-1", "--pretty=%s"], capture_output=True, text=True).stdout.strip() + assert log == "chore: three" + + +# --- 8. log ----------------------------------------------------------------------------- + + +def _session(cache: Path, harness_name: str, key: str, turns: list[tuple[str, str]]): + d = cache / harness_name / key + d.mkdir(parents=True) + with open(d / "s.jsonl", "w") as f: + for role, text in turns: + f.write(json.dumps({"type": "message", "message": {"role": role, "content": text}}) + "\n") + + +def test_log_lists_and_filters(monkeypatch, harness, isolated_dirs, capsys): + cache = isolated_dirs / "cache" / "sessions" + _session(cache, "pi", "k1", [("user", "how to use rojo sync"), ("assistant", "run rojo serve")]) + _session(cache, "omp", "k2", [("user", "tar extract"), ("assistant", "tar xzf")]) + monkeypatch.setattr(sys.stdout, "isatty", lambda: False) + run(monkeypatch, "log") + out = capsys.readouterr().out + assert "rojo sync" in out and "tar extract" in out + run(monkeypatch, "log", "serve") + out = capsys.readouterr().out + assert "rojo sync" in out and "tar extract" not in out + run(monkeypatch, "log", "--json") + assert {s["harness"] for s in json.loads(capsys.readouterr().out)} == {"pi", "omp"} + + +def test_log_empty(monkeypatch, harness): + with pytest.raises(SystemExit) as e: + run(monkeypatch, "log", "nothing") + assert e.value.code == 1 + + +# --- 9. footer --------------------------------------------------------------------------- + + +def test_footer_on_stderr_tty(monkeypatch, harness, capsys): + monkeypatch.delenv("AI_NO_FOOTER") + monkeypatch.setattr(sys.stderr, "isatty", lambda: True) + run(monkeypatch, "--raw", "--no-session", "-m", "gpt-x", "q") + err = capsys.readouterr().err + assert "pi · gpt-x ·" in err and err.rstrip().endswith("s\x1b[0m") + + +def test_no_footer_when_piped(monkeypatch, harness, capsys): + monkeypatch.delenv("AI_NO_FOOTER") + monkeypatch.setattr(sys.stderr, "isatty", lambda: False) + run(monkeypatch, "--raw", "--no-session", "q") + assert capsys.readouterr().err == "" + + +# --- 10. zsh widget ------------------------------------------------------------------------ + + +def test_zsh_snippet(monkeypatch, capsys): + with pytest.raises(SystemExit): + run(monkeypatch, "--zsh") + out = capsys.readouterr().out + assert "zle -N _ai_flow_widget" in out and "ai do --print" in out + + +def test_zsh_snippet_is_valid_zsh(monkeypatch): + import shutil + + if not shutil.which("zsh"): + pytest.skip("zsh not installed") + r = subprocess.run(["zsh", "-n"], input=extras.ZSH_SNIPPET, text=True, capture_output=True) + assert r.returncode == 0, r.stderr + + +# --- regressions ------------------------------------------------------------------------ + + +def test_help_mentions_new_commands(monkeypatch, capsys): + with pytest.raises(SystemExit): + run(monkeypatch, "--help") + out = capsys.readouterr().out + for word in ("ai do", "ai commit", "ai explain", "ai log", "--copy", "--json", "--file", "--zsh", ".ai.md"): + assert word in out + + +def test_import_stays_light(): + code = "import sys, ai_cli.main; print('ai_cli.extras' in sys.modules, 'rich.markdown' in sys.modules)" + out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True) + assert out.stdout.strip() == "False False" From 015736e44b116d1b0b6a588d95779f18b7e52811 Mon Sep 17 00:00:00 2001 From: Codder-hermes Date: Wed, 30 Sep 2026 21:03:25 +0300 Subject: [PATCH 2/3] docs: document the new commands and context files --- README.md | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b1b5753..0a95b8b 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,16 @@ Wraps fast headless AI harnesses (`pi`, `omp`, `claude`, `codex`, `copilot`, `op - 🎨 **Rich Terminal Markdown & LaTeX** — renders clean markdown, tables, syntax highlighting, and math formulas in the terminal. - 💬 **No Quotes Required** — run `ai what is the biggest object on earth` directly. - 🚰 **Pure Unix Pipelines** — stdin context injection and clean raw text output when piped. -- 🛠️ **Tools On Demand** — pass `--tools` when agentic filesystem/system actions are needed. +- 🛠️ **Tools On Demand** — tools are on by default; `--no-tools` for plain answers. +- 🐚 **`ai do`** — natural language → one shell command, confirm `[Y/e/n]` before it runs. +- 📝 **`ai commit`** — Conventional Commit message from your staged diff, matching your repo's style. +- 🩺 **`ai explain`** — `make 2>&1 | ai explain` tells you what broke and how to fix it. +- 📂 **`-f 'src/**/*.py'`** — attach files by glob as context. +- 📋 **`-c / --copy`** — copy the answer (or just its code block) to the clipboard. +- 🧭 **Per-directory context** — `.ai.md` in a project + `~/.config/ai/context.md`, injected automatically. +- 🔎 **`ai log`** — fuzzy-search past sessions with fzf and a live preview. +- 🧾 **`--json`** — machine-readable output for scripts. +- ⌨️ **zsh widget** — type what you want, press `Ctrl+G`, get the command. --- @@ -104,6 +113,58 @@ Output is automatically raw and unformatted when redirected to a pipe or file: ai "generate a python regex for uuid4" > regex.txt ``` +### 7. Shell Commands: `ai do` +```bash +ai do find files over 100MB in my home +# $ find ~ -type f -size +100M -exec ls -lh {} + +# Run it? [Y/e/n] +``` +`e` lets you edit the command before running; executed commands land in your shell history. +`ai do --print ...` only prints the command (great for scripts). + +### 8. Commit Messages: `ai commit` +```bash +git add -p +ai commit # shows the message → [Y]es commit / [e]dit in $EDITOR / [n]o +ai commit --print # just print it +ai commit "mention the issue #12" +``` + +### 9. Explain Errors: `ai explain` +```bash +cargo build 2>&1 | ai explain +journalctl -u nginx -n 50 | ai explain "why won't it start?" +``` + +### 10. Files as Context: `-f / --file` +```bash +ai -f 'src/**/*.luau' "where is player data saved?" +ai -f README.md -f pyproject.toml "is the install section accurate?" +``` +Binary files are skipped; each file is capped at 200 KB (1 MB total). + +### 11. Clipboard, JSON & Footer +```bash +ai -c "regex for an ipv4 address" # copies the code block (wl-copy/xclip/pbcopy) +ai --json "capital of France" | jq -r .response +``` +A dim `harness · model · 3.2s` footer is shown on terminals. Hide it with `AI_NO_FOOTER=1`. + +### 12. Session History: `ai log` +```bash +ai log # fzf picker with preview (plain list without fzf) +ai log rojo # only sessions mentioning "rojo" +ai log -a --json # everything, as JSON +``` + +### 13. zsh Widget +```bash +# ~/.zshrc +eval "$(ai --zsh)" +``` +Type `undo last git commit but keep changes`, press **Ctrl+G** → the line becomes +`git reset --soft HEAD~1`. Review, then Enter. Change the key with `AI_ZSH_KEY`. + --- ## ⚙️ Configuration @@ -120,6 +181,14 @@ You can change it anytime via: ai --wizard ``` +### Context files +Anything in these files is prepended to every prompt (skip with `--no-context`): + +| File | Scope | +|---|---| +| `~/.config/ai/context.md` | Always: who you are, your OS, preferences | +| `.ai.md` (nearest, walking up from cwd, stops at `$HOME`) | Per project: conventions, stack, commands | + --- ## 📄 License From e97ebde66c21e25177e018d603b5377937a3a3da Mon Sep 17 00:00:00 2001 From: Codder-hermes Date: Wed, 30 Sep 2026 21:03:25 +0300 Subject: [PATCH 3/3] chore(release): 0.12.0 --- .SRCINFO | 6 +++--- PKGBUILD | 4 ++-- src/ai_cli/__init__.py | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.SRCINFO b/.SRCINFO index a8bd470..97680f5 100644 --- a/.SRCINFO +++ b/.SRCINFO @@ -1,6 +1,6 @@ pkgbase = ai-flow-cli - pkgdesc = Ultra-fast streaming AI CLI & agent for Unix terminals - pkgver = 0.11.0 + pkgdesc = Fast terminal AI for Unix pipelines: wraps pi, omp, claude, codex, copilot & opencode + pkgver = 0.12.0 pkgrel = 1 url = https://github.com/Codder13/ai-flow-cli arch = any @@ -11,7 +11,7 @@ pkgbase = ai-flow-cli depends = python depends = python-rich depends = python-pylatexenc - source = ai-flow-cli-0.11.0.tar.gz::https://github.com/Codder13/ai-flow-cli/archive/refs/tags/v0.11.0.tar.gz + source = ai-flow-cli-0.12.0.tar.gz::https://github.com/Codder13/ai-flow-cli/archive/refs/tags/v0.12.0.tar.gz sha256sums = 4292cd8f5e36141a7347e33431491c633725ad5b2549dd8ce65aadb3d57bc62c pkgname = ai-flow-cli diff --git a/PKGBUILD b/PKGBUILD index f6ec7f6..09bf1d4 100644 --- a/PKGBUILD +++ b/PKGBUILD @@ -1,8 +1,8 @@ # Maintainer: Denis Bolba pkgname=ai-flow-cli -pkgver=0.11.0 +pkgver=0.12.0 pkgrel=1 -pkgdesc="Ultra-fast streaming AI CLI & agent for Unix terminals" +pkgdesc="Fast terminal AI for Unix pipelines: wraps pi, omp, claude, codex, copilot & opencode" arch=('any') url="https://github.com/Codder13/ai-flow-cli" license=('MIT') diff --git a/src/ai_cli/__init__.py b/src/ai_cli/__init__.py index d145148..f6f1b42 100644 --- a/src/ai_cli/__init__.py +++ b/src/ai_cli/__init__.py @@ -1,3 +1,3 @@ """ai-flow-cli: terminal AI wrapper around coding harnesses for Unix pipelines.""" -__version__ = "0.11.0" +__version__ = "0.12.0"