Compare commits
248 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 49531864f1 | |||
| 84fa08ab45 | |||
| f97bd44f05 | |||
| 9bc865b8fa | |||
| af1a61a468 | |||
| f610ed312c | |||
| 159f2d3330 | |||
| f5d465b5a9 | |||
| 37a36dd36d | |||
| 6601654b3a | |||
| 8d1d7ba184 | |||
| e3eb8c1b02 | |||
| b6ad2f09a5 | |||
| 0db472aaa5 | |||
| 1d7c584b55 | |||
| 4f0b91adda | |||
| 5c82a0e632 | |||
| 7a8a99b604 | |||
| 1e7c7cd65d | |||
| 6acb1dc091 | |||
| aed3879844 | |||
| a8fc9bbc54 | |||
| 2bccb11e53 | |||
| 352bbb76f2 | |||
| c54962b0e0 | |||
| 68e3993234 | |||
| 9648ddd69d | |||
| 7c66dfd36b | |||
| b0e65e4041 | |||
| abbda81659 | |||
| 62237bcd3b | |||
| 6486dd9b43 | |||
| 914f30c8e0 | |||
| b555256d21 | |||
| f1f1f88181 | |||
| a764fd6b75 | |||
| 2273817f5f | |||
| 997007439e | |||
| 41bf788a51 | |||
| f7aac0785b | |||
| 611547afa5 | |||
| f39c7a75f2 | |||
| 2e8efdaa12 | |||
| 495f63f0d8 | |||
| efc72c5ceb | |||
| b4a4a38fec | |||
| ffe899a3c0 | |||
| 94c89cea05 | |||
| b02a41c8e0 | |||
| f5a5724823 | |||
| fbb6681cd2 | |||
| 5b0774958a | |||
| 4a07b97eab | |||
| 10c8e2baae | |||
| 09c8c9d83e | |||
| 5caf502009 | |||
| 04a7085007 | |||
| 6022aeb2b0 | |||
| e77e33ce2f | |||
| f87e5d2796 | |||
| 3c436fda54 | |||
| 173403379f | |||
| 688d1fe58a | |||
| b1b95a4560 | |||
| a024a764d6 | |||
| 686526bbd4 | |||
| 5134462deb | |||
| d7ddc365ec | |||
| 6108b9e3d1 | |||
| a6cf8585ef | |||
| baf833427a | |||
| d21945dbc0 | |||
| 7f39bf1eca | |||
| dcda8216dc | |||
| ff49e7ce93 | |||
| b63d26f0cd | |||
| 64fd3206a2 | |||
| 2a651ebd7b | |||
| 491fd049b0 | |||
| c9e2f9bae6 | |||
| 7b87459a72 | |||
| 4935a64a13 | |||
| a84c8a425d | |||
| 16c0e71147 | |||
| 0728262a9e | |||
| 7aa80fb0a4 | |||
| 28b6eb0a9a | |||
| 353c0a8239 | |||
| 44b07c8e27 | |||
| 76e59c2d0e | |||
| c92e07b866 | |||
| 9aa8722ec3 | |||
| 7daa4f4ebe | |||
| a788b8941e | |||
| 16bc534837 | |||
| eef0e3dea0 | |||
| 5d9ecec82c | |||
| 6980640324 | |||
| a0868a9b49 | |||
| 877ece07be | |||
| f6a3f235df | |||
| a4f7a45e56 | |||
| 94ef08db6b | |||
| 57942219a8 | |||
| 03244e8d24 | |||
| d7066d7d37 | |||
| 124db19e68 | |||
| e89da02d49 | |||
| cf0a8f21d5 | |||
| 2d45406982 | |||
| f592840d39 | |||
| 9090bddf68 | |||
| 4981a63224 | |||
| 1238bbe000 | |||
| f29f306692 | |||
| 9024e2b914 | |||
| 6849d5ef12 | |||
| 3c6e689de9 | |||
| 1994367a2e | |||
| c3a92a092b | |||
| 6a94373c4f | |||
| 83280f68cc | |||
| 21759898fb | |||
| 02df6d893c | |||
| 8f9d601fdc | |||
| 40e42c8918 | |||
| 6e12bb3acb | |||
| 16b6f24e3e | |||
| 25628d1d58 | |||
| e813736b47 | |||
| 7e2c6ea037 | |||
| 3f6d7d56f6 | |||
| bbb94367e1 | |||
| 79fdafce97 | |||
| 24671f5f2a | |||
| e0b14a42f2 | |||
| 3e8788dd44 | |||
| 38a4c55eaa | |||
| c7b7fe98ec | |||
| 4820a6706f | |||
| 3308b483f7 | |||
| 4ce4ac0b0e | |||
| 3722840d2c | |||
| 02f25b7bec | |||
| d86888704f | |||
| de6b6e20a5 | |||
| 1e8a5e08ed | |||
| 218ebbf32f | |||
| c49e7f4b22 | |||
| 9588c8c562 | |||
| 1948ac1284 | |||
| 3f92b7d963 | |||
| 5553e61dbf | |||
| 7f987737f9 | |||
| 5182f86133 | |||
| a50099ad74 | |||
| 20ba5523ee | |||
| 0b2b3701dc | |||
| 438b05b8a3 | |||
| e2a31b192f | |||
| b827d3d047 | |||
| 9c0cf274a3 | |||
| 85ae319690 | |||
| 449f133a1f | |||
| 2f6b03ef65 | |||
| d4030dc598 | |||
| 3271697f6b | |||
| cbfef5a5df | |||
| 52efd5f341 | |||
| 200cdbc4bd | |||
| 8525819ab4 | |||
| bcd52d526c | |||
| 7effade1d3 | |||
| dc0fee2ee3 | |||
| ea04a25ed6 | |||
| 282dcdce88 | |||
| b49f58bc16 | |||
| cdc425ae93 | |||
| 3525cb3949 | |||
| 9d85420bf6 | |||
| 641c95131f | |||
| 708c626176 | |||
| 5210e196f2 | |||
| 30c375b6c5 | |||
| baf49b1e69 | |||
| 96e0436d43 | |||
| 498e6e61b6 | |||
| 99064b6c41 | |||
| ee58b0ac32 | |||
| 990f93d467 | |||
| 44a00619b5 | |||
| 6923ee439f | |||
| c997b19b53 | |||
| c9daf68fea | |||
| ba9d083088 | |||
| 825dfc0722 | |||
| 3e4eacd1d3 | |||
| 23253219a3 | |||
| cc2b85a86d | |||
| 58dd6f3efa | |||
| c81d0f1593 | |||
| ae0dd3fc51 | |||
| 80dffa9f41 | |||
| ab0ae4fe04 | |||
| d31e068277 | |||
| 690f5c7056 | |||
| 0da8a3f193 | |||
| 15f81d9728 | |||
| b80db89391 | |||
| f413a63c5a | |||
| 33ad3797a1 | |||
| 55e6b0583d | |||
| ae9c3af096 | |||
| 0bd560b408 | |||
| 083b621b7d | |||
| d2a193e5c1 | |||
| acbfe47a4b | |||
| 60c859b3ab | |||
| 82078afd6d | |||
| 7851af14a9 | |||
| c2f5ccea3b | |||
| fab63d224b | |||
| 15e5c1206b | |||
| 38aba1a6bb | |||
| d0d3079df5 | |||
| 56de1170ee | |||
| 952e4819fe | |||
| 5ac0d152cb | |||
| 40c44470e8 | |||
| 5c37df1b22 | |||
| 5e81185df3 | |||
| 7534c9ef8d | |||
| 9545a4b3ad | |||
| e94df2c48a | |||
| cdf95002fc | |||
| 4c066bf2da | |||
| e57844e742 | |||
| 33d11ae223 | |||
| 05e90d3e2b | |||
| fe414d49e6 | |||
| d002d35bde | |||
| c9c3d17db0 | |||
| a909455f97 | |||
| 67381b02db | |||
| 235f84fa19 | |||
| 9c777c8429 | |||
| 0b17a0f4c8 | |||
| 2eabe55fe6 |
@@ -1,20 +0,0 @@
|
||||
[target.x86_64-unknown-linux-musl]
|
||||
linker = "x86_64-linux-gnu-gcc"
|
||||
rustflags = ["-C", "target-feature=+crt-static", "-C", "link-arg=-lgcc"]
|
||||
|
||||
[target.aarch64-unknown-linux-gnu]
|
||||
linker = "aarch64-linux-gnu-gcc"
|
||||
|
||||
[target.aarch64-unknown-linux-musl]
|
||||
linker = "aarch64-linux-gnu-gcc"
|
||||
rustflags = ["-C", "target-feature=+crt-static", "-C", "link-arg=-lgcc"]
|
||||
|
||||
[target.armv7-unknown-linux-gnueabihf]
|
||||
linker = "arm-linux-gnueabihf-gcc"
|
||||
|
||||
[target.armv7-unknown-linux-musleabihf]
|
||||
linker = "arm-linux-gnueabihf-gcc"
|
||||
rustflags = ["-C", "target-feature=+crt-static", "-C", "link-arg=-lgcc"]
|
||||
|
||||
[target.x86_64-pc-windows-gnu]
|
||||
linker = "x86_64-w64-mingw32-gcc"
|
||||
39
.gitignore
vendored
39
.gitignore
vendored
@@ -1,13 +1,12 @@
|
||||
### Custom
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
|
||||
### Rust template
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
dev/
|
||||
.agents/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
@@ -19,17 +18,10 @@ Cargo.lock
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
|
||||
# RustRover
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
### JetBrains template
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
.idea/
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
@@ -60,14 +52,15 @@ Cargo.lock
|
||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# since they will be recreated, and may cause churn. Uncomment if using
|
||||
# auto-import.
|
||||
# .idea/artifacts
|
||||
# .idea/compiler.xml
|
||||
# .idea/jarRepositories.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/*.iml
|
||||
# .idea/modules
|
||||
# *.iml
|
||||
# *.ipr
|
||||
.idea/artifacts
|
||||
.idea/compiler.xml
|
||||
.idea/jarRepositories.xml
|
||||
.idea/modules.xml
|
||||
.idea/*.iml
|
||||
.idea/modules
|
||||
*.iml
|
||||
*.ipr
|
||||
.idea
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
@@ -104,3 +97,9 @@ fabric.properties
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
### rust-analyzer template
|
||||
# Can be generated by other build systems other than cargo (ex: bazelbuild/rust_rules)
|
||||
rust-project.json
|
||||
|
||||
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# Pre-commit hooks configuration
|
||||
# See https://pre-commit.com for more information
|
||||
|
||||
repos:
|
||||
# General file checks
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v5.0.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
- id: check-yaml
|
||||
- id: check-toml
|
||||
- id: check-merge-conflict
|
||||
- id: check-added-large-files
|
||||
args: ['--maxkb=1000']
|
||||
- id: mixed-line-ending
|
||||
|
||||
# Rust formatting
|
||||
- repo: https://github.com/doublify/pre-commit-rust
|
||||
rev: v1.0
|
||||
hooks:
|
||||
- id: fmt
|
||||
name: cargo fmt
|
||||
description: Format Rust code with rustfmt
|
||||
- id: cargo-check
|
||||
name: cargo check
|
||||
description: Check Rust code compilation
|
||||
- id: clippy
|
||||
name: cargo clippy
|
||||
description: Lint Rust code with clippy
|
||||
args: ['--all-features', '--', '-D', 'warnings']
|
||||
|
||||
# Optional: run on all files when config changes
|
||||
default_install_hook_types: [pre-commit, pre-push]
|
||||
1
.tmp
Submodule
1
.tmp
Submodule
Submodule .tmp added at 4928f2cdca
131
.woodpecker.yml
131
.woodpecker.yml
@@ -1,131 +0,0 @@
|
||||
when:
|
||||
event: tag
|
||||
tag: v*
|
||||
|
||||
variables:
|
||||
- &rust_image 'rust:1.83'
|
||||
|
||||
matrix:
|
||||
include:
|
||||
# Linux
|
||||
- TARGET: x86_64-unknown-linux-gnu
|
||||
ARTIFACT: owlen-linux-x86_64-gnu
|
||||
PLATFORM: linux
|
||||
EXT: ""
|
||||
- TARGET: x86_64-unknown-linux-musl
|
||||
ARTIFACT: owlen-linux-x86_64-musl
|
||||
PLATFORM: linux
|
||||
EXT: ""
|
||||
- TARGET: aarch64-unknown-linux-gnu
|
||||
ARTIFACT: owlen-linux-aarch64-gnu
|
||||
PLATFORM: linux
|
||||
EXT: ""
|
||||
- TARGET: aarch64-unknown-linux-musl
|
||||
ARTIFACT: owlen-linux-aarch64-musl
|
||||
PLATFORM: linux
|
||||
EXT: ""
|
||||
- TARGET: armv7-unknown-linux-gnueabihf
|
||||
ARTIFACT: owlen-linux-armv7-gnu
|
||||
PLATFORM: linux
|
||||
EXT: ""
|
||||
- TARGET: armv7-unknown-linux-musleabihf
|
||||
ARTIFACT: owlen-linux-armv7-musl
|
||||
PLATFORM: linux
|
||||
EXT: ""
|
||||
# Windows
|
||||
- TARGET: x86_64-pc-windows-gnu
|
||||
ARTIFACT: owlen-windows-x86_64
|
||||
PLATFORM: windows
|
||||
EXT: ".exe"
|
||||
|
||||
steps:
|
||||
- name: build
|
||||
image: *rust_image
|
||||
commands:
|
||||
# Install cross-compilation tools
|
||||
- apt-get update
|
||||
- apt-get install -y musl-tools gcc-aarch64-linux-gnu g++-aarch64-linux-gnu gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf mingw-w64 zip
|
||||
|
||||
# Verify cross-compilers are installed
|
||||
- which aarch64-linux-gnu-gcc || echo "aarch64-linux-gnu-gcc not found!"
|
||||
- which arm-linux-gnueabihf-gcc || echo "arm-linux-gnueabihf-gcc not found!"
|
||||
- which x86_64-w64-mingw32-gcc || echo "x86_64-w64-mingw32-gcc not found!"
|
||||
|
||||
# Add rust target
|
||||
- rustup target add ${TARGET}
|
||||
|
||||
# Set up cross-compilation environment variables and build
|
||||
- |
|
||||
case "${TARGET}" in
|
||||
aarch64-unknown-linux-gnu)
|
||||
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=/usr/bin/aarch64-linux-gnu-gcc
|
||||
export CC_aarch64_unknown_linux_gnu=/usr/bin/aarch64-linux-gnu-gcc
|
||||
export CXX_aarch64_unknown_linux_gnu=/usr/bin/aarch64-linux-gnu-g++
|
||||
export AR_aarch64_unknown_linux_gnu=/usr/bin/aarch64-linux-gnu-ar
|
||||
;;
|
||||
aarch64-unknown-linux-musl)
|
||||
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=/usr/bin/aarch64-linux-gnu-gcc
|
||||
export CC_aarch64_unknown_linux_musl=/usr/bin/aarch64-linux-gnu-gcc
|
||||
export CXX_aarch64_unknown_linux_musl=/usr/bin/aarch64-linux-gnu-g++
|
||||
export AR_aarch64_unknown_linux_musl=/usr/bin/aarch64-linux-gnu-ar
|
||||
;;
|
||||
armv7-unknown-linux-gnueabihf)
|
||||
export CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER=/usr/bin/arm-linux-gnueabihf-gcc
|
||||
export CC_armv7_unknown_linux_gnueabihf=/usr/bin/arm-linux-gnueabihf-gcc
|
||||
export CXX_armv7_unknown_linux_gnueabihf=/usr/bin/arm-linux-gnueabihf-g++
|
||||
export AR_armv7_unknown_linux_gnueabihf=/usr/bin/arm-linux-gnueabihf-ar
|
||||
;;
|
||||
armv7-unknown-linux-musleabihf)
|
||||
export CARGO_TARGET_ARMV7_UNKNOWN_LINUX_MUSLEABIHF_LINKER=/usr/bin/arm-linux-gnueabihf-gcc
|
||||
export CC_armv7_unknown_linux_musleabihf=/usr/bin/arm-linux-gnueabihf-gcc
|
||||
export CXX_armv7_unknown_linux_musleabihf=/usr/bin/arm-linux-gnueabihf-g++
|
||||
export AR_armv7_unknown_linux_musleabihf=/usr/bin/arm-linux-gnueabihf-ar
|
||||
;;
|
||||
x86_64-pc-windows-gnu)
|
||||
export CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=/usr/bin/x86_64-w64-mingw32-gcc
|
||||
export CC_x86_64_pc_windows_gnu=/usr/bin/x86_64-w64-mingw32-gcc
|
||||
export CXX_x86_64_pc_windows_gnu=/usr/bin/x86_64-w64-mingw32-g++
|
||||
export AR_x86_64_pc_windows_gnu=/usr/bin/x86_64-w64-mingw32-ar
|
||||
;;
|
||||
esac
|
||||
|
||||
# Build the project
|
||||
cargo build --release --all-features --target ${TARGET}
|
||||
|
||||
- name: package
|
||||
image: *rust_image
|
||||
commands:
|
||||
- apt-get update && apt-get install -y zip
|
||||
- mkdir -p dist
|
||||
- |
|
||||
if [ "${PLATFORM}" = "windows" ]; then
|
||||
cp target/${TARGET}/release/owlen.exe dist/owlen.exe
|
||||
cp target/${TARGET}/release/owlen-code.exe dist/owlen-code.exe
|
||||
cd dist
|
||||
zip -9 ${ARTIFACT}.zip owlen.exe owlen-code.exe
|
||||
cd ..
|
||||
mv dist/${ARTIFACT}.zip .
|
||||
sha256sum ${ARTIFACT}.zip > ${ARTIFACT}.zip.sha256
|
||||
else
|
||||
cp target/${TARGET}/release/owlen dist/owlen
|
||||
cp target/${TARGET}/release/owlen-code dist/owlen-code
|
||||
cd dist
|
||||
tar czf ${ARTIFACT}.tar.gz owlen owlen-code
|
||||
cd ..
|
||||
mv dist/${ARTIFACT}.tar.gz .
|
||||
sha256sum ${ARTIFACT}.tar.gz > ${ARTIFACT}.tar.gz.sha256
|
||||
fi
|
||||
|
||||
- name: release
|
||||
image: plugins/gitea-release
|
||||
settings:
|
||||
api_key:
|
||||
from_secret: gitea_token
|
||||
base_url: https://somegit.dev
|
||||
files:
|
||||
- ${ARTIFACT}.tar.gz
|
||||
- ${ARTIFACT}.tar.gz.sha256
|
||||
- ${ARTIFACT}.zip
|
||||
- ${ARTIFACT}.zip.sha256
|
||||
title: Release ${CI_COMMIT_TAG}
|
||||
note: "Release ${CI_COMMIT_TAG}"
|
||||
81
CHANGELOG.md
81
CHANGELOG.md
@@ -1,81 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Comprehensive documentation suite including guides for architecture, configuration, testing, and more.
|
||||
- Rustdoc examples for core components like `Provider` and `SessionController`.
|
||||
- Module-level documentation for `owlen-tui`.
|
||||
|
||||
### Changed
|
||||
- The main `README.md` has been updated to be more concise and link to the new documentation.
|
||||
|
||||
---
|
||||
|
||||
## [0.1.10] - 2025-10-03
|
||||
|
||||
### Added
|
||||
- **Material Light Theme**: A new built-in theme, `material-light`, has been added.
|
||||
|
||||
### Fixed
|
||||
- **UI Readability**: Fixed a bug causing unreadable text in light themes.
|
||||
- **Visual Selection**: The visual selection mode now correctly colors unselected text portions.
|
||||
|
||||
### Changed
|
||||
- **Theme Colors**: The color palettes for `gruvbox`, `rose-pine`, and `monokai` have been corrected.
|
||||
- **In-App Help**: The `:help` menu has been significantly expanded and updated.
|
||||
|
||||
## [0.1.9] - 2025-10-03
|
||||
|
||||
*This version corresponds to the release tagged v0.1.10 in the source repository.*
|
||||
|
||||
### Added
|
||||
- **Material Light Theme**: A new built-in theme, `material-light`, has been added.
|
||||
|
||||
### Fixed
|
||||
- **UI Readability**: Fixed a bug causing unreadable text in light themes.
|
||||
- **Visual Selection**: The visual selection mode now correctly colors unselected text portions.
|
||||
|
||||
### Changed
|
||||
- **Theme Colors**: The color palettes for `gruvbox`, `rose-pine`, and `monokai` have been corrected.
|
||||
- **In-App Help**: The `:help` menu has been significantly expanded and updated.
|
||||
|
||||
## [0.1.8] - 2025-10-02
|
||||
|
||||
### Added
|
||||
- **Command Autocompletion**: Implemented intelligent command suggestions and Tab completion in command mode.
|
||||
|
||||
### Changed
|
||||
- **Build & CI**: Fixed cross-compilation for ARM64, ARMv7, and Windows.
|
||||
|
||||
## [0.1.7] - 2025-10-02
|
||||
|
||||
### Added
|
||||
- **Tabbed Help System**: The help menu is now organized into five tabs for easier navigation.
|
||||
- **Command Aliases**: Added `:o` as a short alias for `:load` / `:open`.
|
||||
|
||||
### Changed
|
||||
- **Session Management**: Improved AI-generated session descriptions.
|
||||
|
||||
## [0.1.6] - 2025-10-02
|
||||
|
||||
### Added
|
||||
- **Platform-Specific Storage**: Sessions are now saved to platform-appropriate directories (e.g., `~/.local/share/owlen` on Linux).
|
||||
- **AI-Generated Session Descriptions**: Conversations can be automatically summarized on save.
|
||||
|
||||
### Changed
|
||||
- **Migration**: Users on older versions can manually move their sessions from `~/.config/owlen/sessions` to the new platform-specific directory.
|
||||
|
||||
## [0.1.4] - 2025-10-01
|
||||
|
||||
### Added
|
||||
- **Multi-Platform Builds**: Pre-built binaries are now provided for Linux (x86_64, aarch64, armv7) and Windows (x86_64).
|
||||
- **AUR Package**: Owlen is now available on the Arch User Repository.
|
||||
|
||||
### Changed
|
||||
- **Build System**: Switched from OpenSSL to rustls for better cross-platform compatibility.
|
||||
@@ -1,121 +0,0 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that are welcoming, open, and respectful.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
[security@owlibou.com](mailto:security@owlibou.com). All complaints will be
|
||||
reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interaction in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.1, available at
|
||||
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
||||
121
CONTRIBUTING.md
121
CONTRIBUTING.md
@@ -1,121 +0,0 @@
|
||||
# Contributing to Owlen
|
||||
|
||||
First off, thank you for considering contributing to Owlen! It's people like you that make Owlen such a great tool.
|
||||
|
||||
Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue, assessing changes, and helping you finalize your pull requests.
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
This project and everyone participating in it is governed by the [Owlen Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior.
|
||||
|
||||
## How Can I Contribute?
|
||||
|
||||
### Reporting Bugs
|
||||
|
||||
This is one of the most helpful ways you can contribute. Before creating a bug report, please check a few things:
|
||||
|
||||
1. **Check the [troubleshooting guide](docs/troubleshooting.md).** Your issue might be a common one with a known solution.
|
||||
2. **Search the existing issues.** It's possible someone has already reported the same bug. If so, add a comment to the existing issue instead of creating a new one.
|
||||
|
||||
When you are creating a bug report, please include as many details as possible. Fill out the required template, the information it asks for helps us resolve issues faster.
|
||||
|
||||
### Suggesting Enhancements
|
||||
|
||||
If you have an idea for a new feature or an improvement to an existing one, we'd love to hear about it. Please provide as much context as you can about what you're trying to achieve.
|
||||
|
||||
### Your First Code Contribution
|
||||
|
||||
Unsure where to begin contributing to Owlen? You can start by looking through `good first issue` and `help wanted` issues.
|
||||
|
||||
### Pull Requests
|
||||
|
||||
The process for submitting a pull request is as follows:
|
||||
|
||||
1. **Fork the repository** and create your branch from `main`.
|
||||
2. **Set up pre-commit hooks** (see [Development Setup](#development-setup) above). This will automatically format and lint your code.
|
||||
3. **Make your changes.**
|
||||
4. **Run the tests.**
|
||||
- `cargo test --all`
|
||||
5. **Commit your changes.** The pre-commit hooks will automatically run `cargo fmt`, `cargo check`, and `cargo clippy`. If you need to bypass the hooks (not recommended), use `git commit --no-verify`.
|
||||
6. **Add a clear, concise commit message.** We follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification.
|
||||
7. **Push to your fork** and submit a pull request to Owlen's `main` branch.
|
||||
8. **Include a clear description** of the problem and solution. Include the relevant issue number if applicable.
|
||||
|
||||
## Development Setup
|
||||
|
||||
To get started with the codebase, you'll need to have Rust installed. Then, you can clone the repository and build the project:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/Owlibou/owlen.git
|
||||
cd owlen
|
||||
cargo build
|
||||
```
|
||||
|
||||
### Pre-commit Hooks
|
||||
|
||||
We use [pre-commit](https://pre-commit.com/) to automatically run formatting and linting checks before each commit. This helps maintain code quality and consistency.
|
||||
|
||||
**Install pre-commit:**
|
||||
|
||||
```sh
|
||||
# Arch Linux
|
||||
sudo pacman -S pre-commit
|
||||
|
||||
# Other Linux/macOS
|
||||
pip install pre-commit
|
||||
|
||||
# Verify installation
|
||||
pre-commit --version
|
||||
```
|
||||
|
||||
**Setup the hooks:**
|
||||
|
||||
```sh
|
||||
cd owlen
|
||||
pre-commit install
|
||||
```
|
||||
|
||||
Once installed, the hooks will automatically run on every commit. You can also run them manually:
|
||||
|
||||
```sh
|
||||
# Run on all files
|
||||
pre-commit run --all-files
|
||||
|
||||
# Run on staged files only
|
||||
pre-commit run
|
||||
```
|
||||
|
||||
The pre-commit hooks will check:
|
||||
- Code formatting (`cargo fmt`)
|
||||
- Compilation (`cargo check`)
|
||||
- Linting (`cargo clippy --all-features`)
|
||||
- General file hygiene (trailing whitespace, EOF newlines, etc.)
|
||||
|
||||
## Coding Style
|
||||
|
||||
- We use `cargo fmt` for automated code formatting. Please run it before committing your changes.
|
||||
- We use `cargo clippy` for linting. Your code should be free of any clippy warnings.
|
||||
|
||||
## Commit Message Conventions
|
||||
|
||||
We use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for our commit messages. This allows for automated changelog generation and makes the project history easier to read.
|
||||
|
||||
The basic format is:
|
||||
|
||||
```
|
||||
<type>[optional scope]: <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer(s)]
|
||||
```
|
||||
|
||||
**Types:** `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`, `build`, `ci`.
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
feat(provider): add support for Gemini Pro
|
||||
```
|
||||
|
||||
Thank you for your contribution!
|
||||
86
Cargo.toml
86
Cargo.toml
@@ -1,64 +1,34 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"crates/owlen-core",
|
||||
"crates/owlen-tui",
|
||||
"crates/owlen-cli",
|
||||
"crates/owlen-ollama",
|
||||
"crates/app/cli",
|
||||
"crates/app/ui",
|
||||
"crates/core/agent",
|
||||
"crates/llm/core",
|
||||
"crates/llm/anthropic",
|
||||
"crates/llm/ollama",
|
||||
"crates/llm/openai",
|
||||
"crates/platform/auth",
|
||||
"crates/platform/config",
|
||||
"crates/platform/credentials",
|
||||
"crates/platform/hooks",
|
||||
"crates/platform/permissions",
|
||||
"crates/platform/plugins",
|
||||
"crates/tools/ask",
|
||||
"crates/tools/bash",
|
||||
"crates/tools/fs",
|
||||
"crates/tools/notebook",
|
||||
"crates/tools/plan",
|
||||
"crates/tools/skill",
|
||||
"crates/tools/slash",
|
||||
"crates/tools/task",
|
||||
"crates/tools/todo",
|
||||
"crates/tools/web",
|
||||
"crates/integration/mcp-client",
|
||||
"crates/integration/jsonrpc",
|
||||
]
|
||||
exclude = []
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.9"
|
||||
edition = "2021"
|
||||
authors = ["Owlibou"]
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0"
|
||||
repository = "https://somegit.dev/Owlibou/owlen"
|
||||
homepage = "https://somegit.dev/Owlibou/owlen"
|
||||
keywords = ["llm", "tui", "cli", "ollama", "chat"]
|
||||
categories = ["command-line-utilities"]
|
||||
|
||||
[workspace.dependencies]
|
||||
# Async runtime and utilities
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
tokio-stream = "0.1"
|
||||
tokio-util = { version = "0.7", features = ["rt"] }
|
||||
futures = "0.3"
|
||||
futures-util = "0.3"
|
||||
|
||||
# TUI framework
|
||||
ratatui = "0.28"
|
||||
crossterm = "0.28"
|
||||
tui-textarea = "0.6"
|
||||
|
||||
# HTTP client and JSON handling
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
|
||||
# Utilities
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
anyhow = "1.0"
|
||||
thiserror = "1.0"
|
||||
|
||||
# Configuration
|
||||
toml = "0.8"
|
||||
shellexpand = "3.1"
|
||||
|
||||
# Database
|
||||
sled = "0.34"
|
||||
|
||||
# For better text handling
|
||||
textwrap = "0.16"
|
||||
|
||||
# Async traits
|
||||
async-trait = "0.1"
|
||||
|
||||
# CLI framework
|
||||
clap = { version = "4.0", features = ["derive"] }
|
||||
|
||||
# Dev dependencies
|
||||
tempfile = "3.8"
|
||||
tokio-test = "0.4"
|
||||
|
||||
# For more keys and their definitions, see https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
rust-version = "1.91"
|
||||
|
||||
661
LICENSE
661
LICENSE
@@ -1,661 +0,0 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
311
PERMISSION_SYSTEM.md
Normal file
311
PERMISSION_SYSTEM.md
Normal file
@@ -0,0 +1,311 @@
|
||||
# Permission System - TUI Implementation
|
||||
|
||||
## Overview
|
||||
|
||||
The TUI now has a fully functional interactive permission system that allows users to grant, deny, or permanently allow tool executions through an elegant popup interface.
|
||||
|
||||
## Features Implemented
|
||||
|
||||
### 1. Interactive Permission Popup
|
||||
|
||||
**Location:** `crates/app/ui/src/components/permission_popup.rs`
|
||||
|
||||
- **Visual Design:**
|
||||
- Centered modal popup with themed border
|
||||
- Tool name highlighted with icon (⚡)
|
||||
- Context information (file path, command, etc.)
|
||||
- Four selectable options with icons
|
||||
- Keyboard shortcuts and navigation hints
|
||||
|
||||
- **Options Available:**
|
||||
- ✓ `[a]` **Allow once** - Execute this one time
|
||||
- ✓✓ `[A]` **Always allow** - Add permanent rule to permission manager
|
||||
- ✗ `[d]` **Deny** - Refuse this operation
|
||||
- ? `[?]` **Explain** - Show what this operation does
|
||||
|
||||
- **Navigation:**
|
||||
- Arrow keys (↑/↓) to select options
|
||||
- Enter to confirm selection
|
||||
- Keyboard shortcuts (a/A/d/?) for quick selection
|
||||
- Esc to deny and close
|
||||
|
||||
### 2. Permission Flow Integration
|
||||
|
||||
**Location:** `crates/app/ui/src/app.rs`
|
||||
|
||||
#### New Components:
|
||||
|
||||
1. **PendingToolCall struct:**
|
||||
```rust
|
||||
struct PendingToolCall {
|
||||
tool_name: String,
|
||||
arguments: Value,
|
||||
perm_tool: PermTool,
|
||||
context: Option<String>,
|
||||
}
|
||||
```
|
||||
Stores information about tool awaiting permission.
|
||||
|
||||
2. **TuiApp fields:**
|
||||
- `pending_tool: Option<PendingToolCall>` - Current pending tool
|
||||
- `permission_tx: Option<oneshot::Sender<bool>>` - Channel to signal decision
|
||||
|
||||
3. **execute_tool_with_permission() method:**
|
||||
```rust
|
||||
async fn execute_tool_with_permission(
|
||||
&mut self,
|
||||
tool_name: &str,
|
||||
arguments: &Value,
|
||||
) -> Result<String>
|
||||
```
|
||||
|
||||
**Flow:**
|
||||
1. Maps tool name to PermTool enum (Read, Write, Edit, Bash, etc.)
|
||||
2. Extracts context (file path, command, etc.)
|
||||
3. Checks permission via PermissionManager
|
||||
4. If `Allow` → Execute immediately
|
||||
5. If `Deny` → Return error
|
||||
6. If `Ask` → Show popup and wait for user decision
|
||||
|
||||
**Async Wait Mechanism:**
|
||||
- Creates oneshot channel for permission response
|
||||
- Shows permission popup
|
||||
- Awaits channel response (with 5-minute timeout)
|
||||
- Event loop continues processing keyboard events
|
||||
- When user responds, channel signals and execution resumes
|
||||
|
||||
### 3. Permission Decision Handling
|
||||
|
||||
**Location:** `crates/app/ui/src/app.rs:184-254`
|
||||
|
||||
When user makes a choice in the popup:
|
||||
|
||||
- **Allow Once:**
|
||||
- Signals permission granted (sends `true` through channel)
|
||||
- Tool executes once
|
||||
- No persistent changes
|
||||
|
||||
- **Always Allow:**
|
||||
- Adds new rule to PermissionManager
|
||||
- Rule format: `perms.add_rule(tool, context, Action::Allow)`
|
||||
- Example: Always allow reading from `src/` directory
|
||||
- Signals permission granted
|
||||
- All future matching operations auto-approved
|
||||
|
||||
- **Deny:**
|
||||
- Signals permission denied (sends `false`)
|
||||
- Tool execution fails with error
|
||||
- Error shown in chat
|
||||
|
||||
- **Explain:**
|
||||
- Shows explanation of what the tool does
|
||||
- Popup remains open for user to choose again
|
||||
- Tool-specific explanations:
|
||||
- `read` → "read a file from disk"
|
||||
- `write` → "write or overwrite a file"
|
||||
- `edit` → "modify an existing file"
|
||||
- `bash` → "execute a shell command"
|
||||
- `grep` → "search for patterns in files"
|
||||
- `glob` → "list files matching a pattern"
|
||||
|
||||
### 4. Agent Loop Integration
|
||||
|
||||
**Location:** `crates/app/ui/src/app.rs:488`
|
||||
|
||||
Changed from:
|
||||
```rust
|
||||
match execute_tool(tool_name, arguments, &self.perms).await {
|
||||
```
|
||||
|
||||
To:
|
||||
```rust
|
||||
match self.execute_tool_with_permission(tool_name, arguments).await {
|
||||
```
|
||||
|
||||
This ensures all tool calls in the streaming agent loop go through the permission system.
|
||||
|
||||
## Architecture Details
|
||||
|
||||
### Async Concurrency Model
|
||||
|
||||
The implementation uses Rust's async/await with tokio to handle the permission flow without blocking the UI:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Event Loop │
|
||||
│ (continuously running at 60 FPS) │
|
||||
│ │
|
||||
│ while running { │
|
||||
│ terminal.draw(...) ← Always responsive │
|
||||
│ if let Ok(event) = event_rx.try_recv() { │
|
||||
│ handle_event(event).await │
|
||||
│ } │
|
||||
│ tokio::sleep(16ms).await ← Yields to runtime │
|
||||
│ } │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
↕
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Keyboard Event Listener │
|
||||
│ (separate tokio task) │
|
||||
│ │
|
||||
│ loop { │
|
||||
│ event = event_stream.next().await │
|
||||
│ event_tx.send(Input(key)) │
|
||||
│ } │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
↕
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Permission Request Flow │
|
||||
│ │
|
||||
│ 1. Tool needs permission (PermissionDecision::Ask) │
|
||||
│ 2. Create oneshot channel (tx, rx) │
|
||||
│ 3. Show popup, store tx │
|
||||
│ 4. await rx ← Yields to event loop │
|
||||
│ 5. Event loop continues, handles keyboard │
|
||||
│ 6. User presses 'a' → handle_event processes │
|
||||
│ 7. tx.send(true) signals channel │
|
||||
│ 8. rx.await completes, returns true │
|
||||
│ 9. Tool executes with permission │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Key Insight
|
||||
|
||||
The implementation works because:
|
||||
1. **Awaiting is non-blocking:** When we `await rx`, we yield control to the tokio runtime
|
||||
2. **Event loop continues:** The outer event loop continues to run its iterations
|
||||
3. **Keyboard events processed:** The separate event listener task continues reading keyboard
|
||||
4. **Channel signals resume:** When user responds, the channel completes and we resume
|
||||
|
||||
This creates a smooth UX where the UI remains responsive while waiting for permission.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Example 1: First-time File Write
|
||||
|
||||
```
|
||||
User: "Create a new file hello.txt with 'Hello World'"
|
||||
|
||||
Agent: [Calls write tool]
|
||||
|
||||
┌───────────────────────────────────────┐
|
||||
│ 🔒 Permission Required │
|
||||
├───────────────────────────────────────┤
|
||||
│ ⚡ Tool: write │
|
||||
│ 📝 Context: │
|
||||
│ hello.txt │
|
||||
├───────────────────────────────────────┤
|
||||
│ ▶ ✓ [a] Allow once │
|
||||
│ ✓✓ [A] Always allow │
|
||||
│ ✗ [d] Deny │
|
||||
│ ? [?] Explain │
|
||||
│ │
|
||||
│ ↑↓ Navigate Enter to select Esc... │
|
||||
└───────────────────────────────────────┘
|
||||
|
||||
User presses 'a' → File created once
|
||||
```
|
||||
|
||||
### Example 2: Always Allow Bash in Current Directory
|
||||
|
||||
```
|
||||
User: "Run npm test"
|
||||
|
||||
Agent: [Calls bash tool]
|
||||
|
||||
[Permission popup shows with context: "npm test"]
|
||||
|
||||
User presses 'A' → Rule added: bash("npm test*") → Allow
|
||||
|
||||
Future: User: "Run npm test:unit"
|
||||
Agent: [Executes immediately, no popup]
|
||||
```
|
||||
|
||||
### Example 3: Explanation Request
|
||||
|
||||
```
|
||||
User: "Read my secrets.env file"
|
||||
|
||||
[Permission popup appears]
|
||||
|
||||
User presses '?' →
|
||||
|
||||
System: "Tool 'read' requires permission. This operation
|
||||
will read a file from disk."
|
||||
|
||||
[Popup remains open]
|
||||
|
||||
User presses 'd' → Permission denied
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
Build status: ✅ All tests pass
|
||||
```bash
|
||||
cargo build --workspace # Success
|
||||
cargo test --workspace --lib # 28 tests passed
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
The permission system respects three modes from `PermissionManager`:
|
||||
|
||||
1. **Plan Mode** (default):
|
||||
- Read operations (read, grep, glob) → Auto-allowed
|
||||
- Write operations (write, edit) → Ask
|
||||
- System operations (bash) → Ask
|
||||
|
||||
2. **AcceptEdits Mode**:
|
||||
- Read operations → Auto-allowed
|
||||
- Write operations → Auto-allowed
|
||||
- System operations (bash) → Ask
|
||||
|
||||
3. **Code Mode**:
|
||||
- All operations → Auto-allowed
|
||||
- No popups shown
|
||||
|
||||
User can override mode with CLI flag: `--mode code`
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential improvements:
|
||||
|
||||
1. **Permission History:**
|
||||
- Show recently granted/denied permissions
|
||||
- `/permissions` command to view active rules
|
||||
|
||||
2. **Temporary Rules:**
|
||||
- "Allow for this session" option
|
||||
- Rules expire when TUI closes
|
||||
|
||||
3. **Pattern-based Rules:**
|
||||
- "Always allow reading from `src/` directory"
|
||||
- "Always allow bash commands starting with `npm`"
|
||||
|
||||
4. **Visual Feedback:**
|
||||
- Show indicator when permission auto-granted by rule
|
||||
- Different styling for policy-denied vs user-denied
|
||||
|
||||
5. **Rule Management:**
|
||||
- `/clear-rules` command
|
||||
- Edit/remove specific rules interactively
|
||||
|
||||
## Files Modified
|
||||
|
||||
- `crates/app/ui/src/app.rs` - Main permission flow logic
|
||||
- `crates/app/ui/src/events.rs` - Removed unused event type
|
||||
- `crates/app/ui/src/components/permission_popup.rs` - Pre-existing, now fully integrated
|
||||
|
||||
## Summary
|
||||
|
||||
The TUI permission system is now fully functional, providing:
|
||||
- ✅ Interactive permission popups with keyboard navigation
|
||||
- ✅ Four permission options (allow once, always, deny, explain)
|
||||
- ✅ Runtime permission rule updates
|
||||
- ✅ Async flow that keeps UI responsive
|
||||
- ✅ Integration with existing permission manager
|
||||
- ✅ Tool-specific context and explanations
|
||||
- ✅ Timeout handling (5 minutes)
|
||||
- ✅ All tests passing
|
||||
|
||||
Users can now safely interact with the AI agent while maintaining control over potentially dangerous operations.
|
||||
49
PKGBUILD
49
PKGBUILD
@@ -1,49 +0,0 @@
|
||||
# Maintainer: vikingowl <christian@nachtigall.dev>
|
||||
pkgname=owlen
|
||||
pkgver=0.1.9
|
||||
pkgrel=1
|
||||
pkgdesc="Terminal User Interface LLM client for Ollama with chat and code assistance features"
|
||||
arch=('x86_64')
|
||||
url="https://somegit.dev/Owlibou/owlen"
|
||||
license=('AGPL-3.0-or-later')
|
||||
depends=('gcc-libs')
|
||||
makedepends=('cargo' 'git')
|
||||
options=(!lto) # avoid LTO-linked ring symbol drop with lld
|
||||
source=("$pkgname-$pkgver.tar.gz::$url/archive/v$pkgver.tar.gz")
|
||||
sha256sums=('cabb1cfdfc247b5d008c6c5f94e13548bcefeba874aae9a9d45aa95ae1c085ec')
|
||||
|
||||
prepare() {
|
||||
cd $pkgname
|
||||
cargo fetch --target "$(rustc -vV | sed -n 's/host: //p')"
|
||||
}
|
||||
|
||||
build() {
|
||||
cd $pkgname
|
||||
export RUSTFLAGS="${RUSTFLAGS:-} -C link-arg=-Wl,--no-as-needed"
|
||||
export CARGO_PROFILE_RELEASE_LTO=false
|
||||
export CARGO_TARGET_DIR=target
|
||||
cargo build --frozen --release --all-features
|
||||
}
|
||||
|
||||
check() {
|
||||
cd $pkgname
|
||||
export RUSTFLAGS="${RUSTFLAGS:-} -C link-arg=-Wl,--no-as-needed"
|
||||
cargo test --frozen --all-features
|
||||
}
|
||||
|
||||
package() {
|
||||
cd $pkgname
|
||||
|
||||
# Install binaries
|
||||
install -Dm755 target/release/owlen "$pkgdir/usr/bin/owlen"
|
||||
install -Dm755 target/release/owlen-code "$pkgdir/usr/bin/owlen-code"
|
||||
|
||||
# Install documentation
|
||||
install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||
|
||||
# Install built-in themes for reference
|
||||
install -Dm644 themes/README.md "$pkgdir/usr/share/$pkgname/themes/README.md"
|
||||
for theme in themes/*.toml; do
|
||||
install -Dm644 "$theme" "$pkgdir/usr/share/$pkgname/themes/$(basename $theme)"
|
||||
done
|
||||
}
|
||||
363
PLUGIN_HOOKS_INTEGRATION.md
Normal file
363
PLUGIN_HOOKS_INTEGRATION.md
Normal file
@@ -0,0 +1,363 @@
|
||||
# Plugin Hooks Integration
|
||||
|
||||
This document describes how the plugin system integrates with the hook system to allow plugins to define lifecycle hooks.
|
||||
|
||||
## Overview
|
||||
|
||||
Plugins can now define hooks in a `hooks/hooks.json` file that will be automatically registered with the `HookManager` during application startup. This allows plugins to:
|
||||
|
||||
- Intercept and validate tool calls before execution (PreToolUse)
|
||||
- React to tool execution results (PostToolUse)
|
||||
- Run code at session boundaries (SessionStart, SessionEnd)
|
||||
- Process user input (UserPromptSubmit)
|
||||
- Handle context compaction (PreCompact)
|
||||
|
||||
## Plugin Hook Configuration
|
||||
|
||||
Plugins define hooks in `hooks/hooks.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"description": "Validation and logging hooks for the plugin",
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/validate.py",
|
||||
"timeout": 5000
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/bash_guard.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostToolUse": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "echo 'Tool executed' >> ${CLAUDE_PLUGIN_ROOT}/logs/tool.log && exit 0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Hook Configuration Schema
|
||||
|
||||
- **description** (optional): A human-readable description of what the hooks do
|
||||
- **hooks**: A map of event names to hook matchers
|
||||
- **PreToolUse**: Hooks that run before a tool is executed
|
||||
- **PostToolUse**: Hooks that run after a tool is executed
|
||||
- **SessionStart**: Hooks that run when a session starts
|
||||
- **SessionEnd**: Hooks that run when a session ends
|
||||
- **UserPromptSubmit**: Hooks that run when the user submits a prompt
|
||||
- **PreCompact**: Hooks that run before context compaction
|
||||
|
||||
### Hook Matcher
|
||||
|
||||
Each hook matcher contains:
|
||||
|
||||
- **matcher** (optional): A regex pattern to match against tool names (for PreToolUse events)
|
||||
- Example: `"Edit|Write"` matches both Edit and Write tools
|
||||
- Example: `".*"` matches all tools
|
||||
- If not specified, the hook applies to all tools
|
||||
- **hooks**: An array of hook definitions
|
||||
|
||||
### Hook Definition
|
||||
|
||||
Each hook definition contains:
|
||||
|
||||
- **type**: The hook type (`"command"` or `"prompt"`)
|
||||
- **command**: The shell command to execute (for command-type hooks)
|
||||
- Can use `${CLAUDE_PLUGIN_ROOT}` which is replaced with the plugin's base path
|
||||
- **prompt** (future): An LLM prompt for AI-based validation
|
||||
- **timeout** (optional): Timeout in milliseconds (default: no timeout)
|
||||
|
||||
## Variable Substitution
|
||||
|
||||
The following variables are automatically substituted in hook commands:
|
||||
|
||||
- **${CLAUDE_PLUGIN_ROOT}**: The absolute path to the plugin directory
|
||||
- Example: `~/.config/owlen/plugins/my-plugin`
|
||||
- Useful for referencing scripts within the plugin
|
||||
|
||||
## Hook Execution Behavior
|
||||
|
||||
### Exit Codes
|
||||
|
||||
Hooks communicate their decision via exit codes:
|
||||
|
||||
- **0**: Allow the operation to proceed
|
||||
- **2**: Deny the operation (blocks the tool call)
|
||||
- **Other**: Error (operation fails with error message)
|
||||
|
||||
### Input/Output
|
||||
|
||||
Hooks receive JSON input via stdin containing the event data:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "preToolUse",
|
||||
"tool": "Edit",
|
||||
"args": {
|
||||
"path": "/path/to/file.txt",
|
||||
"old_string": "foo",
|
||||
"new_string": "bar"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern Matching
|
||||
|
||||
For PreToolUse hooks, the `matcher` field is treated as a regex pattern:
|
||||
|
||||
- `"Edit|Write"` - Matches Edit OR Write tools
|
||||
- `"Bash"` - Matches only Bash tool
|
||||
- `".*"` - Matches all tools
|
||||
- No matcher - Applies to all tools
|
||||
|
||||
### Multiple Hooks
|
||||
|
||||
- Multiple plugins can define hooks for the same event
|
||||
- All matching hooks are executed in sequence
|
||||
- If any hook denies (exit code 2), the operation is blocked
|
||||
- File-based hooks in `.owlen/hooks/` are executed first, then plugin hooks
|
||||
|
||||
## Integration Architecture
|
||||
|
||||
### Loading Process
|
||||
|
||||
1. **Application Startup** (`main.rs`):
|
||||
```rust
|
||||
// Create hook manager
|
||||
let mut hook_mgr = HookManager::new(".");
|
||||
|
||||
// Register plugin hooks
|
||||
for plugin in app_context.plugin_manager.plugins() {
|
||||
if let Ok(Some(hooks_config)) = plugin.load_hooks_config() {
|
||||
for (event, command, pattern, timeout) in plugin.register_hooks_with_manager(&hooks_config) {
|
||||
hook_mgr.register_hook(event, command, pattern, timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. **Plugin Hook Loading** (`plugins/src/lib.rs`):
|
||||
- `Plugin::load_hooks_config()` reads and parses `hooks/hooks.json`
|
||||
- `Plugin::register_hooks_with_manager()` processes the config and performs variable substitution
|
||||
|
||||
3. **Hook Registration** (`hooks/src/lib.rs`):
|
||||
- `HookManager::register_hook()` stores hooks internally
|
||||
- `HookManager::execute()` filters and executes matching hooks
|
||||
|
||||
### Execution Flow
|
||||
|
||||
```
|
||||
Tool Call Request
|
||||
↓
|
||||
Permission Check
|
||||
↓
|
||||
HookManager::execute(PreToolUse)
|
||||
↓
|
||||
Check file-based hook (.owlen/hooks/PreToolUse)
|
||||
↓
|
||||
Filter plugin hooks by event and pattern
|
||||
↓
|
||||
Execute each matching hook
|
||||
↓
|
||||
If any hook denies → Block operation
|
||||
↓
|
||||
If all allow → Execute tool
|
||||
↓
|
||||
HookManager::execute(PostToolUse)
|
||||
```
|
||||
|
||||
## Example: Validation Hook
|
||||
|
||||
Create a plugin with a validation hook:
|
||||
|
||||
**Directory structure:**
|
||||
```
|
||||
~/.config/owlen/plugins/validation/
|
||||
├── plugin.json
|
||||
└── hooks/
|
||||
├── hooks.json
|
||||
└── validate.py
|
||||
```
|
||||
|
||||
**plugin.json:**
|
||||
```json
|
||||
{
|
||||
"name": "validation",
|
||||
"version": "1.0.0",
|
||||
"description": "Validation hooks for file operations"
|
||||
}
|
||||
```
|
||||
|
||||
**hooks/hooks.json:**
|
||||
```json
|
||||
{
|
||||
"description": "Validate file operations",
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/validate.py",
|
||||
"timeout": 5000
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**hooks/validate.py:**
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import sys
|
||||
|
||||
# Read event from stdin
|
||||
event = json.load(sys.stdin)
|
||||
|
||||
tool = event.get('tool')
|
||||
args = event.get('args', {})
|
||||
path = args.get('path', '')
|
||||
|
||||
# Deny operations on system files
|
||||
if path.startswith('/etc/') or path.startswith('/sys/'):
|
||||
print(f"Blocked: Cannot modify system file {path}", file=sys.stderr)
|
||||
sys.exit(2) # Deny
|
||||
|
||||
# Allow all other operations
|
||||
sys.exit(0) # Allow
|
||||
```
|
||||
|
||||
**Make executable:**
|
||||
```bash
|
||||
chmod +x ~/.config/owlen/plugins/validation/hooks/validate.py
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
### Unit Tests
|
||||
|
||||
Test hook registration and execution:
|
||||
|
||||
```rust
|
||||
#[tokio::test]
|
||||
async fn test_plugin_hooks() -> Result<()> {
|
||||
let mut hook_mgr = HookManager::new(".");
|
||||
|
||||
hook_mgr.register_hook(
|
||||
"PreToolUse".to_string(),
|
||||
"echo 'validated' && exit 0".to_string(),
|
||||
Some("Edit|Write".to_string()),
|
||||
Some(5000),
|
||||
);
|
||||
|
||||
let event = HookEvent::PreToolUse {
|
||||
tool: "Edit".to_string(),
|
||||
args: serde_json::json!({}),
|
||||
};
|
||||
|
||||
let result = hook_mgr.execute(&event, Some(5000)).await?;
|
||||
assert_eq!(result, HookResult::Allow);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
### Integration Tests
|
||||
|
||||
Test the full plugin loading and hook execution:
|
||||
|
||||
```rust
|
||||
#[tokio::test]
|
||||
async fn test_plugin_hooks_integration() -> Result<()> {
|
||||
// Create plugin with hooks
|
||||
let plugin_dir = create_test_plugin_with_hooks()?;
|
||||
|
||||
// Load plugin
|
||||
let mut plugin_manager = PluginManager::with_dirs(vec![plugin_dir]);
|
||||
plugin_manager.load_all()?;
|
||||
|
||||
// Register hooks
|
||||
let mut hook_mgr = HookManager::new(".");
|
||||
for plugin in plugin_manager.plugins() {
|
||||
if let Ok(Some(config)) = plugin.load_hooks_config() {
|
||||
for (event, cmd, pattern, timeout) in plugin.register_hooks_with_manager(&config) {
|
||||
hook_mgr.register_hook(event, cmd, pattern, timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test hook execution
|
||||
let event = HookEvent::PreToolUse {
|
||||
tool: "Edit".to_string(),
|
||||
args: serde_json::json!({}),
|
||||
};
|
||||
|
||||
let result = hook_mgr.execute(&event, Some(5000)).await?;
|
||||
assert_eq!(result, HookResult::Allow);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Modified Crates
|
||||
|
||||
1. **plugins** (`crates/platform/plugins/src/lib.rs`):
|
||||
- Added `PluginHooksConfig`, `HookMatcher`, `HookDefinition` structs
|
||||
- Added `Plugin::load_hooks_config()` method
|
||||
- Added `Plugin::register_hooks_with_manager()` method
|
||||
|
||||
2. **hooks** (`crates/platform/hooks/src/lib.rs`):
|
||||
- Refactored to store registered hooks internally
|
||||
- Added `HookManager::register_hook()` method
|
||||
- Updated `HookManager::execute()` to handle both file-based and registered hooks
|
||||
- Added pattern matching support using regex
|
||||
- Added `regex` dependency
|
||||
|
||||
3. **owlen** (`crates/app/cli/src/main.rs`):
|
||||
- Integrated plugin hook loading during startup
|
||||
- Registered plugin hooks with HookManager
|
||||
|
||||
### Dependencies Added
|
||||
|
||||
- **hooks/Cargo.toml**: Added `regex = "1.10"`
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Modularity**: Hooks can be packaged with plugins and distributed independently
|
||||
2. **Reusability**: Plugins can be shared across projects
|
||||
3. **Flexibility**: Each plugin can define multiple hooks with different patterns
|
||||
4. **Compatibility**: Works alongside existing file-based hooks in `.owlen/hooks/`
|
||||
5. **Variable Substitution**: `${CLAUDE_PLUGIN_ROOT}` makes scripts portable
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. **Prompt-based hooks**: Use LLM for validation instead of shell commands
|
||||
2. **Hook priorities**: Control execution order of hooks
|
||||
3. **Hook metadata**: Description, author, version for each hook
|
||||
4. **Hook debugging**: Better error messages and logging
|
||||
5. **Async hooks**: Support for long-running hooks that don't block
|
||||
103
README.md
103
README.md
@@ -1,103 +0,0 @@
|
||||
# OWLEN
|
||||
|
||||
> Terminal-native assistant for running local language models with a comfortable TUI.
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
## What Is OWLEN?
|
||||
|
||||
OWLEN is a Rust-powered, terminal-first interface for interacting with local large
|
||||
language models. It provides a responsive chat workflow that runs against
|
||||
[Ollama](https://ollama.com/) with a focus on developer productivity, vim-style navigation,
|
||||
and seamless session management—all without leaving your terminal.
|
||||
|
||||
## Alpha Status
|
||||
|
||||
This project is currently in **alpha** and under active development. Core features are functional, but expect occasional bugs and breaking changes. Feedback, bug reports, and contributions are very welcome!
|
||||
|
||||
## Screenshots
|
||||
|
||||

|
||||
|
||||
The OWLEN interface features a clean, multi-panel layout with vim-inspired navigation. See more screenshots in the [`images/`](images/) directory.
|
||||
|
||||
## Features
|
||||
|
||||
- **Vim-style Navigation**: Normal, editing, visual, and command modes.
|
||||
- **Streaming Responses**: Real-time token streaming from Ollama.
|
||||
- **Advanced Text Editing**: Multi-line input, history, and clipboard support.
|
||||
- **Session Management**: Save, load, and manage conversations.
|
||||
- **Theming System**: 10 built-in themes and support for custom themes.
|
||||
- **Modular Architecture**: Extensible provider system (currently Ollama).
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
- Rust 1.75+ and Cargo.
|
||||
- A running Ollama instance.
|
||||
- A terminal that supports 256 colors.
|
||||
|
||||
### Installation
|
||||
|
||||
#### Linux & macOS
|
||||
The recommended way to install on Linux and macOS is to clone the repository and install using `cargo`.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Owlibou/owlen.git
|
||||
cd owlen
|
||||
cargo install --path crates/owlen-cli
|
||||
```
|
||||
**Note for macOS**: While this method works, official binary releases for macOS are planned for the future.
|
||||
|
||||
#### Windows
|
||||
The Windows build has not been thoroughly tested yet. Installation is possible via the same `cargo install` method, but it is considered experimental at this time.
|
||||
|
||||
### Running OWLEN
|
||||
|
||||
Make sure Ollama is running, then launch the application:
|
||||
```bash
|
||||
owlen
|
||||
```
|
||||
If you built from source without installing, you can run it with:
|
||||
```bash
|
||||
./target/release/owlen
|
||||
```
|
||||
|
||||
## Using the TUI
|
||||
|
||||
OWLEN uses a modal, vim-inspired interface. Press `?` in Normal mode to view the help screen with all keybindings.
|
||||
|
||||
- **Normal Mode**: Navigate with `h/j/k/l`, `w/b`, `gg/G`.
|
||||
- **Editing Mode**: Enter with `i` or `a`. Send messages with `Enter`.
|
||||
- **Command Mode**: Enter with `:`. Access commands like `:quit`, `:save`, `:theme`.
|
||||
|
||||
## Documentation
|
||||
|
||||
For more detailed information, please refer to the following documents:
|
||||
|
||||
- **[CONTRIBUTING.md](CONTRIBUTING.md)**: Guidelines for contributing to the project.
|
||||
- **[CHANGELOG.md](CHANGELOG.md)**: A log of changes for each version.
|
||||
- **[docs/architecture.md](docs/architecture.md)**: An overview of the project's architecture.
|
||||
- **[docs/troubleshooting.md](docs/troubleshooting.md)**: Help with common issues.
|
||||
- **[docs/provider-implementation.md](docs/provider-implementation.md)**: A guide for adding new providers.
|
||||
|
||||
## Configuration
|
||||
|
||||
OWLEN stores its configuration in `~/.config/owlen/config.toml`. This file is created on the first run and can be customized. You can also add custom themes in `~/.config/owlen/themes/`.
|
||||
|
||||
See the [themes/README.md](themes/README.md) for more details on theming.
|
||||
|
||||
## Roadmap
|
||||
|
||||
We are actively working on enhancing the code client, adding more providers (OpenAI, Anthropic), and improving the overall user experience. See the [Roadmap section in the old README](https://github.com/Owlibou/owlen/blob/main/README.md?plain=1#L295) for more details.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are highly welcome! Please see our **[Contributing Guide](CONTRIBUTING.md)** for details on how to get started, including our code style, commit conventions, and pull request process.
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the GNU Affero General Public License v3.0. See the [LICENSE](LICENSE) file for details.
|
||||
19
SECURITY.md
19
SECURITY.md
@@ -1,19 +0,0 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
We are currently in a pre-release phase, so only the latest version is actively supported. As we move towards a 1.0 release, this policy will be updated with specific version support.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| < 1.0 | :white_check_mark: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
The Owlen team and community take all security vulnerabilities seriously. Thank you for improving the security of our project. We appreciate your efforts and responsible disclosure and will make every effort to acknowledge your contributions.
|
||||
|
||||
To report a security vulnerability, please email the project lead at [security@owlibou.com](mailto:security@owlibou.com) with a detailed description of the issue, the steps to reproduce it, and any affected versions.
|
||||
|
||||
You will receive a response from us within 48 hours. If the issue is confirmed, we will release a patch as soon as possible, depending on the complexity of the issue.
|
||||
|
||||
Please do not report security vulnerabilities through public GitHub issues.
|
||||
262
TODO.md
Normal file
262
TODO.md
Normal file
@@ -0,0 +1,262 @@
|
||||
# Owlen Project Improvement Roadmap
|
||||
|
||||
Generated from codebase analysis on 2025-11-01
|
||||
|
||||
## Overall Assessment
|
||||
|
||||
**Grade:** A (90/100)
|
||||
**Status:** Production-ready with minor enhancements needed
|
||||
**Architecture:** Excellent domain-driven design with clean separation of concerns
|
||||
|
||||
---
|
||||
|
||||
## 🔴 Critical Issues (Do First)
|
||||
|
||||
- [x] **Fix Integration Test Failure** (`crates/app/cli/tests/chat_stream.rs`) ✅ **COMPLETED**
|
||||
- Fixed mock server to accept requests with tools parameter
|
||||
- Test now passes successfully
|
||||
- Location: `crates/app/cli/tests/chat_stream.rs`
|
||||
|
||||
- [x] **Remove Side Effects from Library Code** (`crates/core/agent/src/lib.rs:348-349`) ✅ **COMPLETED**
|
||||
- Replaced `println!` with `tracing` crate
|
||||
- Added `tracing = "0.1"` dependency to `agent-core`
|
||||
- Changed to structured logging: `tracing::debug!` for tool calls, `tracing::warn!` for errors
|
||||
- Users can now control verbosity and route logs appropriately
|
||||
- Location: `crates/core/agent/src/lib.rs:348, 352, 361`
|
||||
|
||||
---
|
||||
|
||||
## 🟡 High-Priority Improvements
|
||||
|
||||
### Permission System ✅
|
||||
|
||||
- [x] **Implement Proper Permission Selection in TUI** ✅ **COMPLETED**
|
||||
- Added interactive permission popup with keyboard navigation
|
||||
- Implemented "Allow once", "Always allow", "Deny", and "Explain" options
|
||||
- Integrated permission requests into agent loop with async channels
|
||||
- Added runtime permission rule updates for "Always allow"
|
||||
- Permission popups pause execution and wait for user input
|
||||
- Location: `crates/app/ui/src/app.rs`, `crates/app/ui/src/components/permission_popup.rs`
|
||||
|
||||
### Documentation
|
||||
|
||||
- [ ] **Add User-Facing README.md**
|
||||
- Quick start guide
|
||||
- Installation instructions
|
||||
- Usage examples
|
||||
- Feature overview
|
||||
- Links to detailed docs
|
||||
- Priority: HIGH
|
||||
|
||||
- [ ] **Add Architecture Documentation**
|
||||
- Crate dependency graph diagram
|
||||
- Agent loop flow diagram
|
||||
- Permission system flow diagram
|
||||
- Plugin/hook integration points diagram
|
||||
- Priority: MEDIUM
|
||||
|
||||
### Feature Integration
|
||||
|
||||
- [ ] **Integrate Plugin System**
|
||||
- Wire plugin loading into `crates/app/cli/src/main.rs`
|
||||
- Load plugins at startup
|
||||
- Test with example plugins
|
||||
- Priority: HIGH
|
||||
|
||||
- [ ] **Integrate MCP Client into Agent**
|
||||
- Add MCP tools to agent's tool registry
|
||||
- Enable external tool servers (databases, APIs, etc.)
|
||||
- Document MCP server setup
|
||||
- Priority: HIGH
|
||||
|
||||
- [ ] **Implement Real Web Search Provider**
|
||||
- Add provider for DuckDuckGo, Brave Search, or SearXNG
|
||||
- Make the web tool functional
|
||||
- Add configuration for provider selection
|
||||
- Priority: MEDIUM
|
||||
|
||||
### Error Handling & Reliability
|
||||
|
||||
- [ ] **Add Retry Logic for Transient Failures**
|
||||
- Exponential backoff for Ollama API calls
|
||||
- Configurable retry policies (max attempts, timeout)
|
||||
- Handle network failures gracefully
|
||||
- Priority: MEDIUM
|
||||
|
||||
- [ ] **Enhance Error Messages**
|
||||
- Add actionable suggestions for common errors
|
||||
- Example: "Ollama not running? Try: `ollama serve`"
|
||||
- Example: "Model not found? Try: `ollama pull qwen3:8b`"
|
||||
- Priority: MEDIUM
|
||||
|
||||
---
|
||||
|
||||
## 🟢 Medium-Priority Enhancements
|
||||
|
||||
### Testing
|
||||
|
||||
- [ ] **Add UI Component Testing**
|
||||
- Snapshot tests for TUI components
|
||||
- Integration tests for user interactions
|
||||
- Use `ratatui` testing utilities
|
||||
- Priority: MEDIUM
|
||||
|
||||
- [ ] **Add More Edge Case Tests**
|
||||
- Glob patterns with special characters
|
||||
- Edit operations with Unicode
|
||||
- Very large file handling
|
||||
- Concurrent tool execution
|
||||
- Priority: MEDIUM
|
||||
|
||||
- [ ] **Code Coverage Reporting**
|
||||
- Integrate `tarpaulin` or `cargo-llvm-cov`
|
||||
- Set minimum coverage thresholds (aim for 80%+)
|
||||
- Track coverage trends over time
|
||||
- Priority: LOW
|
||||
|
||||
### Documentation
|
||||
|
||||
- [ ] **Module-Level Documentation**
|
||||
- Add `//!` docs to key modules
|
||||
- Explain design decisions and patterns
|
||||
- Document internal APIs
|
||||
- Priority: MEDIUM
|
||||
|
||||
- [ ] **Create Examples Directory**
|
||||
- Simple CLI usage examples
|
||||
- Custom plugin development guide
|
||||
- Hook script examples
|
||||
- MCP server integration examples
|
||||
- Configuration templates
|
||||
- Priority: MEDIUM
|
||||
|
||||
### Code Quality
|
||||
|
||||
- [ ] **Fix Dead Code Warning** (`ui/src/app.rs:38`)
|
||||
- Either use `settings` field or remove it
|
||||
- Remove `#[allow(dead_code)]`
|
||||
- Priority: LOW
|
||||
|
||||
- [ ] **Improve Error Recovery**
|
||||
- Checkpoint auto-save on crashes
|
||||
- Graceful degradation when tools fail
|
||||
- Better handling of partial tool results
|
||||
- Priority: MEDIUM
|
||||
|
||||
---
|
||||
|
||||
## 🔵 Low-Priority Nice-to-Haves
|
||||
|
||||
### Project Infrastructure
|
||||
|
||||
- [ ] **CI/CD Pipeline (GitHub Actions)**
|
||||
- Automated testing on push
|
||||
- Clippy linting
|
||||
- Format checking with `rustfmt`
|
||||
- Security audits with `cargo-audit`
|
||||
- Cross-platform builds (Linux, macOS, Windows)
|
||||
- Priority: LOW
|
||||
|
||||
- [ ] **Performance Benchmarking**
|
||||
- Add benchmark suite using `criterion` crate
|
||||
- Track performance for glob, grep, large file ops
|
||||
- Track agent loop iteration performance
|
||||
- Priority: LOW
|
||||
|
||||
### Code Organization
|
||||
|
||||
- [ ] **Extract Reusable Crates**
|
||||
- Publish `mcp-client` as standalone library
|
||||
- Publish `llm-ollama` as standalone library
|
||||
- Enable reuse by other projects
|
||||
- Consider publishing to crates.io
|
||||
- Priority: LOW
|
||||
|
||||
---
|
||||
|
||||
## 💡 Feature Enhancement Ideas
|
||||
|
||||
### Session Management
|
||||
|
||||
- [ ] **Session Persistence**
|
||||
- Auto-save sessions across restarts
|
||||
- Resume previous conversations
|
||||
- Session history browser in TUI
|
||||
- Export/import session transcripts
|
||||
|
||||
### Multi-Provider Support
|
||||
|
||||
- [ ] **Multi-Model Support**
|
||||
- Support Anthropic Claude API
|
||||
- Support OpenAI API
|
||||
- Provider abstraction layer
|
||||
- Fallback chains for reliability
|
||||
|
||||
### Enhanced Permissions
|
||||
|
||||
- [ ] **Advanced Permission System**
|
||||
- Time-based permissions (expire after N minutes)
|
||||
- Scope-based permissions (allow within specific directories)
|
||||
- Permission profiles (dev, prod, strict)
|
||||
- Team permission policies
|
||||
|
||||
### Collaboration
|
||||
|
||||
- [ ] **Collaborative Features**
|
||||
- Export sessions as shareable transcripts
|
||||
- Import/export checkpoints
|
||||
- Shared permission policies for teams
|
||||
- Session replay functionality
|
||||
|
||||
### Observability
|
||||
|
||||
- [ ] **Enhanced Observability**
|
||||
- Token usage tracking per tool call
|
||||
- Cost estimation dashboard
|
||||
- Performance metrics export (JSON/CSV)
|
||||
- OpenTelemetry integration
|
||||
- Real-time stats in TUI
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Wins (Can Be Done Today)
|
||||
|
||||
- [ ] Add `README.md` to repository root
|
||||
- [ ] Fix dead code warning in `ui/src/app.rs:38`
|
||||
- [ ] Add `tracing` crate and replace `println!` calls
|
||||
- [ ] Create `.github/workflows/ci.yml` for basic CI
|
||||
- [ ] Add module-level docs to `agent-core` and `config-agent`
|
||||
|
||||
---
|
||||
|
||||
## 🌟 Long-Term Vision
|
||||
|
||||
- **Plugin Marketplace:** Curated registry of community plugins
|
||||
- **Interactive Tutorial:** Built-in tutorial mode for new users
|
||||
- **VS Code Extension:** Editor integration for inline assistance
|
||||
- **Collaborative Agents:** Multi-agent workflows with role assignment
|
||||
- **Knowledge Base Integration:** RAG capabilities for project-specific knowledge
|
||||
- **Web Dashboard:** Browser-based interface for session management
|
||||
- **Cloud Sync:** Sync configs and sessions across devices
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- **Test Status:** 28+ tests, most passing. 1 integration test failure (mock server issue)
|
||||
- **Test Coverage:** Strong coverage for core functionality (permissions, checkpoints, hooks)
|
||||
- **Architecture:** Clean domain-driven workspace with 15 crates across 4 domains
|
||||
- **Code Quality:** Excellent error handling, consistent patterns, minimal technical debt
|
||||
- **Innovation Highlights:** Checkpoint/rewind system, three-tiered permissions, shell-based hooks
|
||||
|
||||
---
|
||||
|
||||
## Priority Legend
|
||||
|
||||
- **HIGH:** Should be done soon, blocks other features or affects quality
|
||||
- **MEDIUM:** Important but not urgent, improves user experience
|
||||
- **LOW:** Nice to have, can be deferred
|
||||
|
||||
---
|
||||
|
||||
Last Updated: 2025-11-01
|
||||
8
conductor/archive/stabilize_core_20251226/metadata.json
Normal file
8
conductor/archive/stabilize_core_20251226/metadata.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"track_id": "stabilize_core_20251226",
|
||||
"type": "feature",
|
||||
"status": "new",
|
||||
"created_at": "2025-12-26T10:00:00Z",
|
||||
"updated_at": "2025-12-26T10:00:00Z",
|
||||
"description": "Establish a comprehensive test suite for the core agent logic and ensure basic documentation for all crates."
|
||||
}
|
||||
17
conductor/archive/stabilize_core_20251226/plan.md
Normal file
17
conductor/archive/stabilize_core_20251226/plan.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Plan: Core Stabilization & Documentation
|
||||
|
||||
## Phase 1: Core Agent & Platform Testing [checkpoint: 495f63f]
|
||||
|
||||
- [x] Task: Write unit tests for `crates/core/agent/src/lib.rs` f5a5724
|
||||
- [x] Task: Write unit tests for `crates/platform/permissions/src/lib.rs` 94c89ce
|
||||
- [x] Task: Write unit tests for `crates/platform/config/src/lib.rs` b4a4a38
|
||||
- [x] Task: Conductor - User Manual Verification 'Core Agent & Platform Testing' (Protocol in workflow.md)
|
||||
|
||||
## Phase 2: Documentation Audit & Standardization [checkpoint: 6486dd9]
|
||||
|
||||
- [x] Task: Create/Update README.md for all crates in `crates/app/` f39c7a7
|
||||
- [x] Task: Create/Update README.md for all crates in `crates/llm/` f7aac07
|
||||
- [x] Task: Create/Update README.md for all crates in `crates/platform/` f9970074
|
||||
- [x] Task: Create/Update README.md for all crates in `crates/tools/` a764fd6b
|
||||
- [x] Task: Add doc-comments to all public functions in `crates/core/agent/` b555256d
|
||||
- [x] Task: Conductor - User Manual Verification 'Documentation Audit & Standardization' (Protocol in workflow.md)
|
||||
14
conductor/archive/stabilize_core_20251226/spec.md
Normal file
14
conductor/archive/stabilize_core_20251226/spec.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Specification: Core Stabilization & Documentation
|
||||
|
||||
## Goal
|
||||
To increase the reliability and maintainability of the Owlen codebase by establishing a robust testing foundation and comprehensive documentation for all existing crates.
|
||||
|
||||
## Scope
|
||||
- **Crates Covered:** All crates in the workspace (`app/*`, `core/*`, `llm/*`, `platform/*`, `tools/*`, `integration/*`).
|
||||
- **Testing:** Unit tests for core logic, focusing on the `core/agent` and `platform/*` crates.
|
||||
- **Documentation:** `README.md` for each crate and doc-comments for all public APIs.
|
||||
|
||||
## Deliverables
|
||||
- Increased test coverage (targeting >80%) for core crates.
|
||||
- Comprehensive API documentation.
|
||||
- Standardized `README.md` files for all crates.
|
||||
28
conductor/code_styleguides/markdown.md
Normal file
28
conductor/code_styleguides/markdown.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Markdown Style Guide
|
||||
|
||||
## General
|
||||
- **Line Wrapping:** Wrap lines at 80-100 characters for readability, unless it breaks a link or code block.
|
||||
- **Headers:**
|
||||
- Use ATX-style headers (`#`, `##`, etc.).
|
||||
- Leave one blank line before and after headers.
|
||||
- **Lists:**
|
||||
- Use hyphens (`-`) for unordered lists.
|
||||
- Use numbers (`1.`, `2.`) for ordered lists.
|
||||
- Indent nested lists by 2 or 4 spaces.
|
||||
|
||||
## Code Blocks
|
||||
- **Fenced Code Blocks:** Use triple backticks (```) for code blocks.
|
||||
- **Language Tags:** Always specify the language for syntax highlighting (e.g., ```rust).
|
||||
|
||||
## Links & Images
|
||||
- **Reference Links:** Prefer inline links `[text](url)` for short links.
|
||||
- **Images:** Provide descriptive alt text for accessibility: ``.
|
||||
|
||||
## Emphasis
|
||||
- **Bold:** Use double asterisks (`**text**`).
|
||||
- **Italic:** Use single asterisks (`*text*`) or underscores (`_text_`).
|
||||
- **Code:** Use single backticks (`` `text` ``) for inline code.
|
||||
|
||||
## Structure
|
||||
- **Table of Contents:** Include a TOC for long documents.
|
||||
- **Sections:** Use logical hierarchy for sections and subsections.
|
||||
37
conductor/code_styleguides/rust.md
Normal file
37
conductor/code_styleguides/rust.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Rust Style Guide
|
||||
|
||||
## General
|
||||
- **Formatting:** Always use `rustfmt` with default settings.
|
||||
- **Linting:** Use `clippy` to catch common mistakes and improve code quality. Address all warnings.
|
||||
- **Edition:** Use the latest stable edition (currently 2024).
|
||||
|
||||
## Naming Conventions
|
||||
- **Crates:** `snake_case` (e.g., `my_crate`)
|
||||
- **Modules:** `snake_case` (e.g., `my_module`)
|
||||
- **Types (Structs, Enums, Traits):** `UpperCamelCase` (e.g., `MyStruct`)
|
||||
- **Functions & Methods:** `snake_case` (e.g., `my_function`)
|
||||
- **Variables:** `snake_case` (e.g., `my_variable`)
|
||||
- **Constants:** `SCREAMING_SNAKE_CASE` (e.g., `MAX_SIZE`)
|
||||
- **Generics:** `UpperCamelCase`, usually single letters (e.g., `T`, `U`) or descriptive names (e.g., `Input`, `Output`).
|
||||
|
||||
## Code Structure
|
||||
- **Imports:** Group imports by crate. Use `std` first, then external crates, then internal modules.
|
||||
- **Visibility:** Minimizing visibility is preferred. Use `pub(crate)` or `pub(super)` where appropriate.
|
||||
- **Error Handling:**
|
||||
- Prefer `Result<T, E>` over `panic!`.
|
||||
- Use the `?` operator for error propagation.
|
||||
- Use `anyhow` for application-level error handling and `thiserror` for library-level errors.
|
||||
|
||||
## Documentation
|
||||
- **Public API:** Document all public items using `///` comments.
|
||||
- **Module Level:** Include module-level documentation using `//!` at the top of the file.
|
||||
- **Examples:** Include examples in documentation where helpful.
|
||||
|
||||
## Testing
|
||||
- **Unit Tests:** Place unit tests in a `tests` module within the same file, annotated with `#[cfg(test)]`.
|
||||
- **Integration Tests:** Place integration tests in the `tests/` directory at the crate root.
|
||||
|
||||
## Idioms
|
||||
- **Pattern Matching:** Use pattern matching (`match`, `if let`) extensively.
|
||||
- **Ownership & Borrowing:** Follow Rust's ownership rules strictly. Avoid `clone()` unless necessary.
|
||||
- **Iterators:** Prefer iterators and combinators (`map`, `filter`, `fold`) over explicit loops.
|
||||
22
conductor/product-guidelines.md
Normal file
22
conductor/product-guidelines.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# Product Guidelines
|
||||
|
||||
## Prose Style
|
||||
- **Professional & Direct:** Use a professional tone that is helpful but concise.
|
||||
- **Clarity over Verbosity:** Explain complex actions briefly without being overly chatty.
|
||||
- **Technical Accuracy:** Use precise terminology when referring to code or system operations.
|
||||
|
||||
## Technical Excellence
|
||||
- **Idiomatic Rust:** Follow standard Rust conventions (`rustfmt`, `clippy`).
|
||||
- **Safety First:** Prioritize memory safety and robust error handling. Use `Result` and `Option` effectively.
|
||||
- **Performance:** Ensure that file operations and LLM interactions are as efficient as possible.
|
||||
- **Modularity:** Maintain high cohesion and low coupling between crates.
|
||||
|
||||
## Security & Privacy
|
||||
- **Minimal Privilege:** Only request permissions for necessary operations.
|
||||
- **Secret Handling:** Never log or store API keys or sensitive data in plain text.
|
||||
- **Transparency:** Clearly inform the user before executing potentially destructive commands.
|
||||
|
||||
## UI/UX Design (CLI/TUI)
|
||||
- **Unix Philosophy:** Support piping and non-interactive modes where applicable.
|
||||
- **Visual Feedback:** Use progress indicators for long-running tasks.
|
||||
- **Accessibility:** Ensure the TUI is readable and navigable with standard terminal settings.
|
||||
21
conductor/product.md
Normal file
21
conductor/product.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Product Guide
|
||||
|
||||
## Initial Concept
|
||||
A robust, modular, and high-performance AI coding assistant for the terminal, built in Rust. It aims to streamline software development workflows by integrating directly with the codebase and version control systems.
|
||||
|
||||
## Target Audience
|
||||
- **Software Developers:** The primary users who need assistance with coding tasks, refactoring, and understanding complex codebases.
|
||||
- **DevOps Engineers:** For handling infrastructure-as-code and script automation via natural language.
|
||||
|
||||
## Core Value Proposition
|
||||
- **Performance & Safety:** Leverages Rust's memory safety and speed for a responsive CLI experience.
|
||||
- **Model Agnostic:** Supports multiple LLM backends (Anthropic, OpenAI, Ollama) giving users flexibility.
|
||||
- **Deep Integration:** Deeply integrates with the local development environment (filesystem, git, shell).
|
||||
- **Extensibility:** A plugin architecture to extend functionality with custom commands and agents.
|
||||
|
||||
## Key Features
|
||||
- **Natural Language Interface:** Interact with the agent using plain English to perform complex tasks.
|
||||
- **Codebase Awareness:** The agent can read and analyze the project structure and file contents to provide context-aware assistance.
|
||||
- **Multi-LLM Support:** Configurable providers including Anthropic, OpenAI, and local models via Ollama.
|
||||
- **Rich TUI:** A text-based user interface for a better user experience in the terminal.
|
||||
- **Tool Ecosystem:** A suite of built-in tools for file manipulation, shell execution, and more.
|
||||
1
conductor/setup_state.json
Normal file
1
conductor/setup_state.json
Normal file
@@ -0,0 +1 @@
|
||||
{"last_successful_step": "3.3_initial_track_generated"}
|
||||
28
conductor/tech-stack.md
Normal file
28
conductor/tech-stack.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Tech Stack
|
||||
|
||||
## Core Technologies
|
||||
- **Language:** Rust (Edition 2024, v1.91+)
|
||||
- **Architecture:** Modular Workspace with specialized crates for UI, Core Agent, LLM Providers, Platform Services, and Tools.
|
||||
- **Dependency Management:** Cargo (Rust's package manager).
|
||||
|
||||
## Crates & Components
|
||||
- **Frontends:**
|
||||
- `crates/app/cli`: Command-line interface.
|
||||
- `crates/app/ui`: Terminal User Interface (TUI).
|
||||
- **Core Agent:**
|
||||
- `crates/core/agent`: The primary orchestration engine for the AI agent.
|
||||
- **LLM Providers:**
|
||||
- `crates/llm/anthropic`: Integration with Anthropic's Claude models.
|
||||
- `crates/llm/openai`: Integration with OpenAI's models.
|
||||
- `crates/llm/ollama`: Integration with local models via Ollama.
|
||||
- **Platform Services:**
|
||||
- `crates/platform/auth`: Authentication logic.
|
||||
- `crates/platform/config`: Configuration management.
|
||||
- `crates/platform/credentials`: Secure credential storage and retrieval.
|
||||
- `crates/platform/hooks`: Plugin hook system.
|
||||
- `crates/platform/permissions`: Permission and safety system.
|
||||
- `crates/platform/plugins`: Plugin management.
|
||||
- **Functional Tools:**
|
||||
- Specialized tools in `crates/tools/` for `bash` execution, `fs` (filesystem) operations, `web` search/fetch, `notebook` interaction, `plan` management, and more.
|
||||
- **Integration:**
|
||||
- `crates/integration/mcp-client`: Client for the Model Context Protocol (MCP).
|
||||
5
conductor/tracks.md
Normal file
5
conductor/tracks.md
Normal file
@@ -0,0 +1,5 @@
|
||||
|
||||
---
|
||||
|
||||
## [~] Track: Owlen Evolution - From TUI to Agentic Workstation
|
||||
*Link: [./conductor/tracks/owlen_evolution_20251226/](./conductor/tracks/owlen_evolution_20251226/)*
|
||||
8
conductor/tracks/owlen_evolution_20251226/metadata.json
Normal file
8
conductor/tracks/owlen_evolution_20251226/metadata.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"track_id": "owlen_evolution_20251226",
|
||||
"type": "feature",
|
||||
"status": "new",
|
||||
"created_at": "2025-12-26T12:00:00Z",
|
||||
"updated_at": "2025-12-26T12:00:00Z",
|
||||
"description": "Transform Owlen from a blocking TUI into a non-blocking, agentic workstation."
|
||||
}
|
||||
55
conductor/tracks/owlen_evolution_20251226/plan.md
Normal file
55
conductor/tracks/owlen_evolution_20251226/plan.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# Implementation Plan - Owlen Evolution
|
||||
|
||||
## Phase 1: Asynchronous Foundation (The "Non-Blocking" Fix) [checkpoint: aed3879]
|
||||
- [x] Task: Create `Message` enum and Central Message Hub using `tokio::sync::mpsc` b0e65e4
|
||||
- Define the `Message` enum to handle UI events, Agent responses, and System notifications.
|
||||
- Create the channel infrastructure in `main.rs`.
|
||||
- [x] Task: Refactor `main.rs` into UI and Engine Loops 9648ddd
|
||||
- Separate the TUI rendering loop into its own async task or thread.
|
||||
- Create the Engine loop (Tokio task) to handle `Message` processing.
|
||||
- [x] Task: Switch LLM interaction to Streaming-only c54962b
|
||||
- Update the LLM client to use streaming responses.
|
||||
- Ensure the UI updates incrementally as tokens arrive.
|
||||
- [x] Task: Introduce `Arc<Mutex<AppState>>` for shared state 2bccb11
|
||||
- Create `AppState` struct to hold conversation history, current mode, etc.
|
||||
- Share it between UI and Engine loops safely.
|
||||
- [x] Task: Conductor - User Manual Verification 'Phase 1: Asynchronous Foundation (The "Non-Blocking" Fix)' (Protocol in workflow.md)
|
||||
|
||||
## Phase 2: The Agentic Orchestrator (Middleware) [checkpoint: 8d1d7ba]
|
||||
- [x] Task: Create `AgentManager` struct 1e7c7cd
|
||||
- Implement the struct to manage the agent's lifecycle and state.
|
||||
- [x] Task: Implement the "Reasoning Loop" (Thought -> Action -> Observation) 5c82a0e
|
||||
- Build the loop logic to process user input, generate thoughts/actions, and handle results.
|
||||
- Implement Sliding Window context management.
|
||||
- Implement Context Summarization logic.
|
||||
- [x] Task: Develop Tool Registry System 1d7c584
|
||||
- Define the `Tool` trait.
|
||||
- Implement a registry to store and retrieve available tools.
|
||||
- Implement logic to inject tool JSON schemas into the System Prompt.
|
||||
- [x] Task: Add Sub-Agent Support b6ad2f0
|
||||
- Allow the Orchestrator to spawn sub-tasks if needed (basic implementation).
|
||||
- [x] Task: Conductor - User Manual Verification 'Phase 2: The Agentic Orchestrator (Middleware)' (Protocol in workflow.md)
|
||||
|
||||
## Phase 3: Permission & Mode Engine
|
||||
- [x] Task: Define `AppMode` enum 37a36dd
|
||||
- Add `Normal`, `Plan`, `AcceptAll` variants.
|
||||
- Integrate `AppMode` into `AppState`.
|
||||
- [x] Task: Implement Permission Interceptor 159f2d3
|
||||
- Create logic to intercept tool calls based on `AppMode`.
|
||||
- Implement the pause/resume mechanism for the Agent Loop.
|
||||
- [x] Task: Implement UI for Permission Requests af1a61a
|
||||
- Add a "Status Bar Prompt" component to the TUI.
|
||||
- Connect the prompt to the Permission Interceptor via the Message Hub.
|
||||
- [ ] Task: Build "Plan Mode" logic
|
||||
- Implement the specific logic for batching actions in Plan Mode.
|
||||
- [ ] Task: Conductor - User Manual Verification 'Phase 3: Permission & Mode Engine' (Protocol in workflow.md)
|
||||
|
||||
## Phase 4: Extension & Integration (The "Gemini-CLI" Layer)
|
||||
- [ ] Task: Create Dynamic Extension Loader
|
||||
- Implement scanning of `~/.config/owlen/plugins/`.
|
||||
- Implement reading of `config.yaml` for tool configuration.
|
||||
- [ ] Task: Implement JSON-RPC Interface
|
||||
- Create a standard interface for communicating with external tool binaries/scripts.
|
||||
- [ ] Task: Integrate External Tools into Registry
|
||||
- Map external tools to the `Tool` trait using the JSON-RPC bridge.
|
||||
- [ ] Task: Conductor - User Manual Verification 'Phase 4: Extension & Integration (The "Gemini-CLI" Layer)' (Protocol in workflow.md)
|
||||
45
conductor/tracks/owlen_evolution_20251226/spec.md
Normal file
45
conductor/tracks/owlen_evolution_20251226/spec.md
Normal file
@@ -0,0 +1,45 @@
|
||||
# Specification: Owlen Evolution – From TUI to Agentic Workstation
|
||||
|
||||
## Overview
|
||||
Transform Owlen from a blocking TUI into a non-blocking, agentic workstation. This involves decoupling the UI from the LLM logic, implementing a reasoning loop (Thought-Action-Observation), a robust permission system, and an extensible plugin architecture.
|
||||
|
||||
## Functional Requirements
|
||||
|
||||
### 1. Asynchronous Foundation
|
||||
- **Non-blocking UI:** Separate the Ratatui UI rendering loop from the LLM/Engine logic using `tokio::sync::mpsc`.
|
||||
- **Streaming Response:** LLM interactions must be streaming-only to prevent UI freezes during long generations.
|
||||
- **Central Message Hub:** Use a many-to-one or many-to-many communication pattern (via `mpsc`) to synchronize state between the background engine and the UI.
|
||||
|
||||
### 2. Agentic Orchestrator
|
||||
- **Reasoning Loop:** Implement a core loop that follows the "Thought -> Action -> Observation" pattern.
|
||||
- **Context Management:**
|
||||
- **Sliding Window:** Maintain only the most recent N interactions in the immediate context.
|
||||
- **Summarization:** Use a secondary LLM call to periodically summarize older parts of the conversation to retain long-term state without hitting token limits.
|
||||
- **Tool Registry:** Define a `Tool` trait and a system to automatically inject tool definitions (JSON Schema) into system prompts.
|
||||
|
||||
### 3. Permission & Mode Engine
|
||||
- **Modes:** Support `Normal` (default), `Plan` (propose all actions first), and `AcceptAll` (autonomous execution).
|
||||
- **Permission Interceptor:** A mechanism to pause the agent loop when a tool requires approval.
|
||||
- **UI Integration:** Requests for permissions must be displayed in the **Status Bar** to avoid obscuring the main conversation.
|
||||
|
||||
### 4. Extension & Integration
|
||||
- **Hybrid Extension Loader:**
|
||||
- Scan a default directory (e.g., `~/.config/owlen/plugins/`) for executable extensions.
|
||||
- Allow manual configuration and overrides via `config.yaml`.
|
||||
- **JSON-RPC Interface:** Use a standardized JSON-RPC interface for communication with external extensions.
|
||||
|
||||
## Non-Functional Requirements
|
||||
- **Performance:** UI must remain responsive (60 FPS target for rendering) even during heavy LLM tasks.
|
||||
- **Safety:** Explicit user consent required for "Write" or "Execute" operations by default.
|
||||
- **Maintainability:** Clear separation of concerns between `crates/app/ui` and `crates/core/agent`.
|
||||
|
||||
## Acceptance Criteria
|
||||
- [ ] TUI remains responsive (can scroll/exit) while the model is "thinking" or "generating".
|
||||
- [ ] Agent can successfully call a registered tool and process its output.
|
||||
- [ ] User can approve or deny a tool execution via a status bar prompt.
|
||||
- [ ] Context window manages long conversations via summarization without crashing.
|
||||
- [ ] External scripts can be loaded as tools and invoked by the agent.
|
||||
|
||||
## Out of Scope
|
||||
- Implementation of complex multi-agent swarms (keeping to a single orchestrator with sub-task capability).
|
||||
- Web-based UI (staying purely within TUI).
|
||||
333
conductor/workflow.md
Normal file
333
conductor/workflow.md
Normal file
@@ -0,0 +1,333 @@
|
||||
# Project Workflow
|
||||
|
||||
## Guiding Principles
|
||||
|
||||
1. **The Plan is the Source of Truth:** All work must be tracked in `plan.md`
|
||||
2. **The Tech Stack is Deliberate:** Changes to the tech stack must be documented in `tech-stack.md` *before* implementation
|
||||
3. **Test-Driven Development:** Write unit tests before implementing functionality
|
||||
4. **High Code Coverage:** Aim for >80% code coverage for all modules
|
||||
5. **User Experience First:** Every decision should prioritize user experience
|
||||
6. **Non-Interactive & CI-Aware:** Prefer non-interactive commands. Use `CI=true` for watch-mode tools (tests, linters) to ensure single execution.
|
||||
|
||||
## Task Workflow
|
||||
|
||||
All tasks follow a strict lifecycle:
|
||||
|
||||
### Standard Task Workflow
|
||||
|
||||
1. **Select Task:** Choose the next available task from `plan.md` in sequential order
|
||||
|
||||
2. **Mark In Progress:** Before beginning work, edit `plan.md` and change the task from `[ ]` to `[~]`
|
||||
|
||||
3. **Write Failing Tests (Red Phase):**
|
||||
- Create a new test file for the feature or bug fix.
|
||||
- Write one or more unit tests that clearly define the expected behavior and acceptance criteria for the task.
|
||||
- **CRITICAL:** Run the tests and confirm that they fail as expected. This is the "Red" phase of TDD. Do not proceed until you have failing tests.
|
||||
|
||||
4. **Implement to Pass Tests (Green Phase):**
|
||||
- Write the minimum amount of application code necessary to make the failing tests pass.
|
||||
- Run the test suite again and confirm that all tests now pass. This is the "Green" phase.
|
||||
|
||||
5. **Refactor (Optional but Recommended):**
|
||||
- With the safety of passing tests, refactor the implementation code and the test code to improve clarity, remove duplication, and enhance performance without changing the external behavior.
|
||||
- Rerun tests to ensure they still pass after refactoring.
|
||||
|
||||
6. **Verify Coverage:** Run coverage reports using the project's chosen tools. For example, in a Python project, this might look like:
|
||||
```bash
|
||||
pytest --cov=app --cov-report=html
|
||||
```
|
||||
Target: >80% coverage for new code. The specific tools and commands will vary by language and framework.
|
||||
|
||||
7. **Document Deviations:** If implementation differs from tech stack:
|
||||
- **STOP** implementation
|
||||
- Update `tech-stack.md` with new design
|
||||
- Add dated note explaining the change
|
||||
- Resume implementation
|
||||
|
||||
8. **Commit Code Changes:**
|
||||
- Stage all code changes related to the task.
|
||||
- Propose a clear, concise commit message e.g, `feat(ui): Create basic HTML structure for calculator`.
|
||||
- Perform the commit.
|
||||
|
||||
9. **Attach Task Summary with Git Notes:**
|
||||
- **Step 9.1: Get Commit Hash:** Obtain the hash of the *just-completed commit* (`git log -1 --format="%H"`).
|
||||
- **Step 9.2: Draft Note Content:** Create a detailed summary for the completed task. This should include the task name, a summary of changes, a list of all created/modified files, and the core "why" for the change.
|
||||
- **Step 9.3: Attach Note:** Use the `git notes` command to attach the summary to the commit.
|
||||
```bash
|
||||
# The note content from the previous step is passed via the -m flag.
|
||||
git notes add -m "<note content>" <commit_hash>
|
||||
```
|
||||
|
||||
10. **Get and Record Task Commit SHA:**
|
||||
- **Step 10.1: Update Plan:** Read `plan.md`, find the line for the completed task, update its status from `[~]` to `[x]`, and append the first 7 characters of the *just-completed commit's* commit hash.
|
||||
- **Step 10.2: Write Plan:** Write the updated content back to `plan.md`.
|
||||
|
||||
11. **Commit Plan Update:**
|
||||
- **Action:** Stage the modified `plan.md` file.
|
||||
- **Action:** Commit this change with a descriptive message (e.g., `conductor(plan): Mark task 'Create user model' as complete`).
|
||||
|
||||
### Phase Completion Verification and Checkpointing Protocol
|
||||
|
||||
**Trigger:** This protocol is executed immediately after a task is completed that also concludes a phase in `plan.md`.
|
||||
|
||||
1. **Announce Protocol Start:** Inform the user that the phase is complete and the verification and checkpointing protocol has begun.
|
||||
|
||||
2. **Ensure Test Coverage for Phase Changes:**
|
||||
- **Step 2.1: Determine Phase Scope:** To identify the files changed in this phase, you must first find the starting point. Read `plan.md` to find the Git commit SHA of the *previous* phase's checkpoint. If no previous checkpoint exists, the scope is all changes since the first commit.
|
||||
- **Step 2.2: List Changed Files:** Execute `git diff --name-only <previous_checkpoint_sha> HEAD` to get a precise list of all files modified during this phase.
|
||||
- **Step 2.3: Verify and Create Tests:** For each file in the list:
|
||||
- **CRITICAL:** First, check its extension. Exclude non-code files (e.g., `.json`, `.md`, `.yaml`).
|
||||
- For each remaining code file, verify a corresponding test file exists.
|
||||
- If a test file is missing, you **must** create one. Before writing the test, **first, analyze other test files in the repository to determine the correct naming convention and testing style.** The new tests **must** validate the functionality described in this phase's tasks (`plan.md`).
|
||||
|
||||
3. **Execute Automated Tests with Proactive Debugging:**
|
||||
- Before execution, you **must** announce the exact shell command you will use to run the tests.
|
||||
- **Example Announcement:** "I will now run the automated test suite to verify the phase. **Command:** `CI=true npm test`"
|
||||
- Execute the announced command.
|
||||
- If tests fail, you **must** inform the user and begin debugging. You may attempt to propose a fix a **maximum of two times**. If the tests still fail after your second proposed fix, you **must stop**, report the persistent failure, and ask the user for guidance.
|
||||
|
||||
4. **Propose a Detailed, Actionable Manual Verification Plan:**
|
||||
- **CRITICAL:** To generate the plan, first analyze `product.md`, `product-guidelines.md`, and `plan.md` to determine the user-facing goals of the completed phase.
|
||||
- You **must** generate a step-by-step plan that walks the user through the verification process, including any necessary commands and specific, expected outcomes.
|
||||
- The plan you present to the user **must** follow this format:
|
||||
|
||||
**For a Frontend Change:**
|
||||
```
|
||||
The automated tests have passed. For manual verification, please follow these steps:
|
||||
|
||||
**Manual Verification Steps:**
|
||||
1. **Start the development server with the command:** `npm run dev`
|
||||
2. **Open your browser to:** `http://localhost:3000`
|
||||
3. **Confirm that you see:** The new user profile page, with the user's name and email displayed correctly.
|
||||
```
|
||||
|
||||
**For a Backend Change:**
|
||||
```
|
||||
The automated tests have passed. For manual verification, please follow these steps:
|
||||
|
||||
**Manual Verification Steps:**
|
||||
1. **Ensure the server is running.**
|
||||
2. **Execute the following command in your terminal:** `curl -X POST http://localhost:8080/api/v1/users -d '{"name": "test"}'`
|
||||
3. **Confirm that you receive:** A JSON response with a status of `201 Created`.
|
||||
```
|
||||
|
||||
5. **Await Explicit User Feedback:**
|
||||
- After presenting the detailed plan, ask the user for confirmation: "**Does this meet your expectations? Please confirm with yes or provide feedback on what needs to be changed.**"
|
||||
- **PAUSE** and await the user's response. Do not proceed without an explicit yes or confirmation.
|
||||
|
||||
6. **Create Checkpoint Commit:**
|
||||
- Stage all changes. If no changes occurred in this step, proceed with an empty commit.
|
||||
- Perform the commit with a clear and concise message (e.g., `conductor(checkpoint): Checkpoint end of Phase X`).
|
||||
|
||||
7. **Attach Auditable Verification Report using Git Notes:**
|
||||
- **Step 8.1: Draft Note Content:** Create a detailed verification report including the automated test command, the manual verification steps, and the user's confirmation.
|
||||
- **Step 8.2: Attach Note:** Use the `git notes` command and the full commit hash from the previous step to attach the full report to the checkpoint commit.
|
||||
|
||||
8. **Get and Record Phase Checkpoint SHA:**
|
||||
- **Step 7.1: Get Commit Hash:** Obtain the hash of the *just-created checkpoint commit* (`git log -1 --format="%H"`).
|
||||
- **Step 7.2: Update Plan:** Read `plan.md`, find the heading for the completed phase, and append the first 7 characters of the commit hash in the format `[checkpoint: <sha>]`.
|
||||
- **Step 7.3: Write Plan:** Write the updated content back to `plan.md`.
|
||||
|
||||
9. **Commit Plan Update:**
|
||||
- **Action:** Stage the modified `plan.md` file.
|
||||
- **Action:** Commit this change with a descriptive message following the format `conductor(plan): Mark phase '<PHASE NAME>' as complete`.
|
||||
|
||||
10. **Announce Completion:** Inform the user that the phase is complete and the checkpoint has been created, with the detailed verification report attached as a git note.
|
||||
|
||||
### Quality Gates
|
||||
|
||||
Before marking any task complete, verify:
|
||||
|
||||
- [ ] All tests pass
|
||||
- [ ] Code coverage meets requirements (>80%)
|
||||
- [ ] Code follows project's code style guidelines (as defined in `code_styleguides/`)
|
||||
- [ ] All public functions/methods are documented (e.g., docstrings, JSDoc, GoDoc)
|
||||
- [ ] Type safety is enforced (e.g., type hints, TypeScript types, Go types)
|
||||
- [ ] No linting or static analysis errors (using the project's configured tools)
|
||||
- [ ] Works correctly on mobile (if applicable)
|
||||
- [ ] Documentation updated if needed
|
||||
- [ ] No security vulnerabilities introduced
|
||||
|
||||
## Development Commands
|
||||
|
||||
**AI AGENT INSTRUCTION: This section should be adapted to the project's specific language, framework, and build tools.**
|
||||
|
||||
### Setup
|
||||
```bash
|
||||
# Example: Commands to set up the development environment (e.g., install dependencies, configure database)
|
||||
# e.g., for a Node.js project: npm install
|
||||
# e.g., for a Go project: go mod tidy
|
||||
```
|
||||
|
||||
### Daily Development
|
||||
```bash
|
||||
# Example: Commands for common daily tasks (e.g., start dev server, run tests, lint, format)
|
||||
# e.g., for a Node.js project: npm run dev, npm test, npm run lint
|
||||
# e.g., for a Go project: go run main.go, go test ./..., go fmt ./...
|
||||
```
|
||||
|
||||
### Before Committing
|
||||
```bash
|
||||
# Example: Commands to run all pre-commit checks (e.g., format, lint, type check, run tests)
|
||||
# e.g., for a Node.js project: npm run check
|
||||
# e.g., for a Go project: make check (if a Makefile exists)
|
||||
```
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
### Unit Testing
|
||||
- Every module must have corresponding tests.
|
||||
- Use appropriate test setup/teardown mechanisms (e.g., fixtures, beforeEach/afterEach).
|
||||
- Mock external dependencies.
|
||||
- Test both success and failure cases.
|
||||
|
||||
### Integration Testing
|
||||
- Test complete user flows
|
||||
- Verify database transactions
|
||||
- Test authentication and authorization
|
||||
- Check form submissions
|
||||
|
||||
### Mobile Testing
|
||||
- Test on actual iPhone when possible
|
||||
- Use Safari developer tools
|
||||
- Test touch interactions
|
||||
- Verify responsive layouts
|
||||
- Check performance on 3G/4G
|
||||
|
||||
## Code Review Process
|
||||
|
||||
### Self-Review Checklist
|
||||
Before requesting review:
|
||||
|
||||
1. **Functionality**
|
||||
- Feature works as specified
|
||||
- Edge cases handled
|
||||
- Error messages are user-friendly
|
||||
|
||||
2. **Code Quality**
|
||||
- Follows style guide
|
||||
- DRY principle applied
|
||||
- Clear variable/function names
|
||||
- Appropriate comments
|
||||
|
||||
3. **Testing**
|
||||
- Unit tests comprehensive
|
||||
- Integration tests pass
|
||||
- Coverage adequate (>80%)
|
||||
|
||||
4. **Security**
|
||||
- No hardcoded secrets
|
||||
- Input validation present
|
||||
- SQL injection prevented
|
||||
- XSS protection in place
|
||||
|
||||
5. **Performance**
|
||||
- Database queries optimized
|
||||
- Images optimized
|
||||
- Caching implemented where needed
|
||||
|
||||
6. **Mobile Experience**
|
||||
- Touch targets adequate (44x44px)
|
||||
- Text readable without zooming
|
||||
- Performance acceptable on mobile
|
||||
- Interactions feel native
|
||||
|
||||
## Commit Guidelines
|
||||
|
||||
### Message Format
|
||||
```
|
||||
<type>(<scope>): <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer]
|
||||
```
|
||||
|
||||
### Types
|
||||
- `feat`: New feature
|
||||
- `fix`: Bug fix
|
||||
- `docs`: Documentation only
|
||||
- `style`: Formatting, missing semicolons, etc.
|
||||
- `refactor`: Code change that neither fixes a bug nor adds a feature
|
||||
- `test`: Adding missing tests
|
||||
- `chore`: Maintenance tasks
|
||||
|
||||
### Examples
|
||||
```bash
|
||||
git commit -m "feat(auth): Add remember me functionality"
|
||||
git commit -m "fix(posts): Correct excerpt generation for short posts"
|
||||
git commit -m "test(comments): Add tests for emoji reaction limits"
|
||||
git commit -m "style(mobile): Improve button touch targets"
|
||||
```
|
||||
|
||||
## Definition of Done
|
||||
|
||||
A task is complete when:
|
||||
|
||||
1. All code implemented to specification
|
||||
2. Unit tests written and passing
|
||||
3. Code coverage meets project requirements
|
||||
4. Documentation complete (if applicable)
|
||||
5. Code passes all configured linting and static analysis checks
|
||||
6. Works beautifully on mobile (if applicable)
|
||||
7. Implementation notes added to `plan.md`
|
||||
8. Changes committed with proper message
|
||||
9. Git note with task summary attached to the commit
|
||||
|
||||
## Emergency Procedures
|
||||
|
||||
### Critical Bug in Production
|
||||
1. Create hotfix branch from main
|
||||
2. Write failing test for bug
|
||||
3. Implement minimal fix
|
||||
4. Test thoroughly including mobile
|
||||
5. Deploy immediately
|
||||
6. Document in plan.md
|
||||
|
||||
### Data Loss
|
||||
1. Stop all write operations
|
||||
2. Restore from latest backup
|
||||
3. Verify data integrity
|
||||
4. Document incident
|
||||
5. Update backup procedures
|
||||
|
||||
### Security Breach
|
||||
1. Rotate all secrets immediately
|
||||
2. Review access logs
|
||||
3. Patch vulnerability
|
||||
4. Notify affected users (if any)
|
||||
5. Document and update security procedures
|
||||
|
||||
## Deployment Workflow
|
||||
|
||||
### Pre-Deployment Checklist
|
||||
- [ ] All tests passing
|
||||
- [ ] Coverage >80%
|
||||
- [ ] No linting errors
|
||||
- [ ] Mobile testing complete
|
||||
- [ ] Environment variables configured
|
||||
- [ ] Database migrations ready
|
||||
- [ ] Backup created
|
||||
|
||||
### Deployment Steps
|
||||
1. Merge feature branch to main
|
||||
2. Tag release with version
|
||||
3. Push to deployment service
|
||||
4. Run database migrations
|
||||
5. Verify deployment
|
||||
6. Test critical paths
|
||||
7. Monitor for errors
|
||||
|
||||
### Post-Deployment
|
||||
1. Monitor analytics
|
||||
2. Check error logs
|
||||
3. Gather user feedback
|
||||
4. Plan next iteration
|
||||
|
||||
## Continuous Improvement
|
||||
|
||||
- Review workflow weekly
|
||||
- Update based on pain points
|
||||
- Document lessons learned
|
||||
- Optimize for user happiness
|
||||
- Keep things simple and maintainable
|
||||
22
crates/app/cli/.gitignore
vendored
Normal file
22
crates/app/cli/.gitignore
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
/target
|
||||
### Rust template
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
|
||||
### rust-analyzer template
|
||||
# Can be generated by other build systems other than cargo (ex: bazelbuild/rust_rules)
|
||||
rust-project.json
|
||||
|
||||
|
||||
41
crates/app/cli/Cargo.toml
Normal file
41
crates/app/cli/Cargo.toml
Normal file
@@ -0,0 +1,41 @@
|
||||
[package]
|
||||
name = "owlen"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
tokio = { version = "1.39", features = ["macros", "rt-multi-thread"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
color-eyre = "0.6"
|
||||
agent-core = { path = "../../core/agent" }
|
||||
llm-core = { path = "../../llm/core" }
|
||||
llm-ollama = { path = "../../llm/ollama" }
|
||||
llm-anthropic = { path = "../../llm/anthropic" }
|
||||
llm-openai = { path = "../../llm/openai" }
|
||||
tools-fs = { path = "../../tools/fs" }
|
||||
tools-bash = { path = "../../tools/bash" }
|
||||
tools-slash = { path = "../../tools/slash" }
|
||||
tools-plan = { path = "../../tools/plan" }
|
||||
auth-manager = { path = "../../platform/auth" }
|
||||
config-agent = { package = "config-agent", path = "../../platform/config" }
|
||||
permissions = { path = "../../platform/permissions" }
|
||||
hooks = { path = "../../platform/hooks" }
|
||||
plugins = { path = "../../platform/plugins" }
|
||||
ui = { path = "../ui" }
|
||||
atty = "0.2"
|
||||
futures-util = "0.3.31"
|
||||
rpassword = "7"
|
||||
open = "5"
|
||||
futures = "0.3.31"
|
||||
async-trait = "0.1.89"
|
||||
|
||||
[dev-dependencies]
|
||||
assert_cmd = "2.0"
|
||||
predicates = "3.1"
|
||||
httpmock = "0.7"
|
||||
tokio = { version = "1.39", features = ["macros", "rt-multi-thread"] }
|
||||
tempfile = "3.23.0"
|
||||
29
crates/app/cli/README.md
Normal file
29
crates/app/cli/README.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Owlen CLI
|
||||
|
||||
The command-line interface for the Owlen AI agent.
|
||||
|
||||
## Features
|
||||
- **Interactive Chat:** Communicate with the AI agent directly from your terminal.
|
||||
- **Tool Integration:** Built-in support for filesystem operations, bash execution, and more.
|
||||
- **Provider Management:** Easily switch between different LLM providers (Ollama, Anthropic, OpenAI).
|
||||
- **Session Management:** Persist conversation history and resume previous sessions.
|
||||
- **Secure Authentication:** Managed authentication flows for major AI providers.
|
||||
|
||||
## Usage
|
||||
|
||||
### Direct Invocation
|
||||
```bash
|
||||
# Start an interactive chat session
|
||||
owlen
|
||||
|
||||
# Ask a single question
|
||||
owlen "How do I list files in Rust?"
|
||||
```
|
||||
|
||||
### Commands
|
||||
- `owlen config`: View or modify agent configuration.
|
||||
- `owlen login <provider>`: Authenticate with a specific LLM provider.
|
||||
- `owlen session`: Manage chat sessions.
|
||||
|
||||
## Configuration
|
||||
Owlen uses a global configuration file located at `~/.config/owlen/config.toml`. You can also provide project-specific settings via an `.owlen.toml` file in your project root.
|
||||
584
crates/app/cli/src/agent_manager.rs
Normal file
584
crates/app/cli/src/agent_manager.rs
Normal file
@@ -0,0 +1,584 @@
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
use agent_core::state::{AppState, AppMode};
|
||||
use agent_core::{PlanStep, AccumulatedPlanStatus};
|
||||
use llm_core::{LlmProvider, ChatMessage, ChatOptions};
|
||||
use color_eyre::eyre::Result;
|
||||
use agent_core::messages::{Message, AgentResponse};
|
||||
use futures::StreamExt;
|
||||
use ui::ProviderManager;
|
||||
|
||||
/// Client source - either a fixed client or dynamic via ProviderManager
|
||||
enum ClientSource {
|
||||
/// Fixed client (legacy mode)
|
||||
Fixed(Arc<dyn LlmProvider>),
|
||||
/// Dynamic via ProviderManager (supports provider/model switching)
|
||||
Dynamic(Arc<Mutex<ProviderManager>>),
|
||||
}
|
||||
|
||||
/// Manages the lifecycle and state of the agent
|
||||
pub struct AgentManager {
|
||||
client_source: ClientSource,
|
||||
state: Arc<Mutex<AppState>>,
|
||||
tx_ui: Option<mpsc::Sender<Message>>,
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
/// Create a new AgentManager with a fixed client (legacy mode)
|
||||
pub fn new(client: Arc<dyn LlmProvider>, state: Arc<Mutex<AppState>>) -> Self {
|
||||
Self {
|
||||
client_source: ClientSource::Fixed(client),
|
||||
state,
|
||||
tx_ui: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new AgentManager with a dynamic ProviderManager
|
||||
pub fn with_provider_manager(
|
||||
provider_manager: Arc<Mutex<ProviderManager>>,
|
||||
state: Arc<Mutex<AppState>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
client_source: ClientSource::Dynamic(provider_manager),
|
||||
state,
|
||||
tx_ui: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the UI message sender
|
||||
pub fn with_ui_sender(mut self, tx: mpsc::Sender<Message>) -> Self {
|
||||
self.tx_ui = Some(tx);
|
||||
self
|
||||
}
|
||||
|
||||
/// Get the current LLM client (resolves dynamic provider if needed)
|
||||
async fn get_client(&self) -> Result<Arc<dyn LlmProvider>> {
|
||||
match &self.client_source {
|
||||
ClientSource::Fixed(client) => Ok(Arc::clone(client)),
|
||||
ClientSource::Dynamic(manager) => {
|
||||
let mut guard = manager.lock().await;
|
||||
guard.get_provider()
|
||||
.map_err(|e| color_eyre::eyre::eyre!("Failed to get provider: {}", e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the current model name
|
||||
async fn get_model(&self) -> String {
|
||||
match &self.client_source {
|
||||
ClientSource::Fixed(client) => client.model().to_string(),
|
||||
ClientSource::Dynamic(manager) => {
|
||||
let guard = manager.lock().await;
|
||||
guard.current_model().to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a reference to the shared state
|
||||
#[allow(dead_code)]
|
||||
pub fn state(&self) -> &Arc<Mutex<AppState>> {
|
||||
&self.state
|
||||
}
|
||||
|
||||
/// Check if a tool execution is permitted
|
||||
pub async fn check_permission(&self, tool: &str, context: Option<&str>) -> Result<bool> {
|
||||
let mode = {
|
||||
let guard = self.state.lock().await;
|
||||
guard.mode
|
||||
};
|
||||
|
||||
match mode {
|
||||
AppMode::AcceptAll => Ok(true),
|
||||
AppMode::Normal | AppMode::Plan => {
|
||||
// Request permission from UI
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::PermissionRequest {
|
||||
tool: tool.to_string(),
|
||||
context: context.map(|s| s.to_string()),
|
||||
})).await;
|
||||
|
||||
// Wait for result
|
||||
let notify = {
|
||||
let guard = self.state.lock().await;
|
||||
guard.permission_notify.clone()
|
||||
};
|
||||
|
||||
notify.notified().await;
|
||||
|
||||
let result = {
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.last_permission_result.take().unwrap_or(false)
|
||||
};
|
||||
|
||||
Ok(result)
|
||||
} else {
|
||||
// No UI sender, default to deny for safety
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn a sub-agent for a specific task
|
||||
pub async fn spawn_sub_agent(&self, _task: &str) -> Result<String> {
|
||||
// Basic placeholder implementation for Sub-Agent support
|
||||
Ok("Sub-agent task completed (mock)".to_string())
|
||||
}
|
||||
|
||||
/// Execute approved steps from the accumulated plan
|
||||
async fn execute_approved_plan_steps(&self) -> Result<()> {
|
||||
// Take the approval and apply it to the plan
|
||||
let approval = {
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.take_plan_approval()
|
||||
};
|
||||
|
||||
if let Some(approval) = approval {
|
||||
// Apply approval to plan
|
||||
{
|
||||
let mut guard = self.state.lock().await;
|
||||
if let Some(plan) = guard.current_plan_mut() {
|
||||
approval.apply_to(plan);
|
||||
plan.start_execution();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get the approved steps
|
||||
let approved_steps: Vec<_> = {
|
||||
let guard = self.state.lock().await;
|
||||
if let Some(plan) = guard.current_plan() {
|
||||
plan.approved_steps()
|
||||
.into_iter()
|
||||
.map(|s| (s.id.clone(), s.tool.clone(), s.args.clone()))
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
|
||||
let total_steps = approved_steps.len();
|
||||
let mut executed = 0;
|
||||
let mut skipped = 0;
|
||||
|
||||
// Execute each approved step
|
||||
for (index, (id, tool_name, arguments)) in approved_steps.into_iter().enumerate() {
|
||||
// Notify UI of execution progress
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::PlanExecuting {
|
||||
step_id: id.clone(),
|
||||
step_index: index,
|
||||
total_steps,
|
||||
})).await;
|
||||
}
|
||||
|
||||
// Execute the tool
|
||||
let dummy_perms = permissions::PermissionManager::new(permissions::Mode::Code);
|
||||
let ctx = agent_core::ToolContext::new();
|
||||
|
||||
match agent_core::execute_tool(&tool_name, &arguments, &dummy_perms, &ctx).await {
|
||||
Ok(result) => {
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage::tool_result(&id, result));
|
||||
executed += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage::tool_result(&id, format!("Error: {}", e)));
|
||||
skipped += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mark plan as complete and notify UI
|
||||
{
|
||||
let mut guard = self.state.lock().await;
|
||||
if let Some(plan) = guard.current_plan_mut() {
|
||||
plan.complete();
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::PlanExecutionComplete {
|
||||
executed,
|
||||
skipped,
|
||||
})).await;
|
||||
}
|
||||
|
||||
// Clear the plan
|
||||
{
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.clear_plan();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute a single tool call (used by engine for plan step execution)
|
||||
pub async fn execute_single_tool(&self, tool_name: &str, args: &serde_json::Value) -> Result<String> {
|
||||
let dummy_perms = permissions::PermissionManager::new(permissions::Mode::Code);
|
||||
let ctx = agent_core::ToolContext::new();
|
||||
|
||||
let result = agent_core::execute_tool(tool_name, args, &dummy_perms, &ctx).await?;
|
||||
|
||||
// Notify UI of tool execution
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::ToolCall {
|
||||
name: tool_name.to_string(),
|
||||
args: args.to_string(),
|
||||
})).await;
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Execute the full reasoning loop until a final response is reached
|
||||
pub async fn run(&self, input: &str) -> Result<()> {
|
||||
let tools = agent_core::get_tool_definitions();
|
||||
|
||||
// 1. Add user message to history
|
||||
{
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage::user(input.to_string()));
|
||||
}
|
||||
|
||||
let max_iterations = 10;
|
||||
let mut iteration = 0;
|
||||
|
||||
loop {
|
||||
iteration += 1;
|
||||
if iteration > max_iterations {
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::Error("Max iterations reached".to_string()))).await;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// 2. Prepare context
|
||||
let messages = {
|
||||
let guard = self.state.lock().await;
|
||||
guard.messages.clone()
|
||||
};
|
||||
|
||||
// 3. Get current client (supports dynamic provider switching)
|
||||
let client = match self.get_client().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::Error(e.to_string()))).await;
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
let options = ChatOptions::new(client.model());
|
||||
|
||||
// 4. Call LLM with streaming
|
||||
let stream_result = client.chat_stream(&messages, &options, Some(&tools)).await;
|
||||
let mut stream = match stream_result {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::Error(e.to_string()))).await;
|
||||
}
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
let mut response_content = String::new();
|
||||
let mut tool_calls_builder = agent_core::ToolCallsBuilder::new();
|
||||
|
||||
while let Some(chunk_result) = stream.next().await {
|
||||
let chunk = match chunk_result {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::Error(e.to_string()))).await;
|
||||
}
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(content) = &chunk.content {
|
||||
response_content.push_str(content);
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::Token(content.clone()))).await;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(deltas) = &chunk.tool_calls {
|
||||
tool_calls_builder.add_deltas(deltas);
|
||||
}
|
||||
}
|
||||
|
||||
drop(stream);
|
||||
|
||||
let tool_calls = tool_calls_builder.build();
|
||||
|
||||
// Add assistant message to history
|
||||
{
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage {
|
||||
role: llm_core::Role::Assistant,
|
||||
content: if response_content.is_empty() { None } else { Some(response_content.clone()) },
|
||||
tool_calls: if tool_calls.is_empty() { None } else { Some(tool_calls.clone()) },
|
||||
tool_call_id: None,
|
||||
name: None,
|
||||
});
|
||||
}
|
||||
|
||||
let mode = {
|
||||
let guard = self.state.lock().await;
|
||||
guard.mode
|
||||
};
|
||||
|
||||
// Check if LLM finished (no tool calls)
|
||||
if tool_calls.is_empty() {
|
||||
// Check if we have an accumulated plan with steps
|
||||
let has_plan_steps = {
|
||||
let guard = self.state.lock().await;
|
||||
guard.accumulated_plan.as_ref().map(|p| !p.steps.is_empty()).unwrap_or(false)
|
||||
};
|
||||
|
||||
if mode == AppMode::Plan && has_plan_steps {
|
||||
// In Plan mode WITH steps: finalize and wait for user approval
|
||||
let (total_steps, status) = {
|
||||
let mut guard = self.state.lock().await;
|
||||
if let Some(plan) = guard.current_plan_mut() {
|
||||
plan.finalize();
|
||||
(plan.steps.len(), plan.status.clone())
|
||||
} else {
|
||||
(0, AccumulatedPlanStatus::Completed)
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::PlanComplete {
|
||||
total_steps,
|
||||
status,
|
||||
})).await;
|
||||
}
|
||||
|
||||
// Wait for user approval
|
||||
let notify = {
|
||||
let guard = self.state.lock().await;
|
||||
guard.plan_notify.clone()
|
||||
};
|
||||
notify.notified().await;
|
||||
|
||||
// Execute approved steps
|
||||
self.execute_approved_plan_steps().await?;
|
||||
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::Complete)).await;
|
||||
}
|
||||
} else {
|
||||
// Normal mode OR Plan mode with no steps: just complete
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::Complete)).await;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Handle Plan mode: accumulate steps instead of executing
|
||||
if mode == AppMode::Plan {
|
||||
// Ensure we have an active plan
|
||||
{
|
||||
let mut guard = self.state.lock().await;
|
||||
if guard.accumulated_plan.is_none() {
|
||||
guard.start_plan();
|
||||
}
|
||||
if let Some(plan) = guard.current_plan_mut() {
|
||||
plan.next_turn();
|
||||
}
|
||||
}
|
||||
|
||||
// Add each tool call as a plan step
|
||||
for call in &tool_calls {
|
||||
let step = PlanStep::new(
|
||||
call.id.clone(),
|
||||
iteration,
|
||||
call.function.name.clone(),
|
||||
call.function.arguments.clone(),
|
||||
).with_rationale(response_content.clone());
|
||||
|
||||
// Add to accumulated plan
|
||||
{
|
||||
let mut guard = self.state.lock().await;
|
||||
if let Some(plan) = guard.current_plan_mut() {
|
||||
plan.add_step(step.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// Notify UI of new step
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::PlanStepAdded(step))).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Feed mock results back to LLM so it can continue reasoning
|
||||
for call in &tool_calls {
|
||||
let mock_result = format!(
|
||||
"[Plan Mode] Step '{}' recorded for approval. Continue proposing steps or stop to finalize.",
|
||||
call.function.name
|
||||
);
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage::tool_result(&call.id, mock_result));
|
||||
}
|
||||
|
||||
// Continue loop - agent will propose more steps or complete
|
||||
continue;
|
||||
}
|
||||
|
||||
// Normal/AcceptAll mode: Execute tools immediately
|
||||
for call in tool_calls {
|
||||
let tool_name = call.function.name.clone();
|
||||
let arguments = call.function.arguments.clone();
|
||||
|
||||
if let Some(tx) = &self.tx_ui {
|
||||
let _ = tx.send(Message::AgentResponse(AgentResponse::ToolCall {
|
||||
name: tool_name.clone(),
|
||||
args: arguments.to_string(),
|
||||
})).await;
|
||||
}
|
||||
|
||||
// Check permission
|
||||
let context = match tool_name.as_str() {
|
||||
"read" | "write" | "edit" => arguments.get("path").and_then(|v| v.as_str()),
|
||||
"bash" => arguments.get("command").and_then(|v| v.as_str()),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let allowed = self.check_permission(&tool_name, context).await?;
|
||||
|
||||
if allowed {
|
||||
// Execute tool
|
||||
// We need a dummy PermissionManager that always allows because we already checked
|
||||
let dummy_perms = permissions::PermissionManager::new(permissions::Mode::Code);
|
||||
let ctx = agent_core::ToolContext::new(); // TODO: Use real context
|
||||
|
||||
match agent_core::execute_tool(&tool_name, &arguments, &dummy_perms, &ctx).await {
|
||||
Ok(result) => {
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage::tool_result(&call.id, result));
|
||||
}
|
||||
Err(e) => {
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage::tool_result(&call.id, format!("Error: {}", e)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage::tool_result(&call.id, "Permission denied by user".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute the reasoning loop: User Input -> LLM -> Thought/Action -> Result -> LLM
|
||||
pub async fn step(&self, input: &str) -> Result<String> {
|
||||
// 1. Add user message to history
|
||||
{
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage::user(input.to_string()));
|
||||
}
|
||||
|
||||
// 2. Prepare context
|
||||
let messages = {
|
||||
let guard = self.state.lock().await;
|
||||
guard.messages.clone()
|
||||
};
|
||||
|
||||
// 3. Get current client
|
||||
let client = self.get_client().await?;
|
||||
let options = ChatOptions::new(client.model());
|
||||
let response = client.chat(&messages, &options, None).await?;
|
||||
|
||||
// 4. Process response
|
||||
if let Some(content) = response.content {
|
||||
let mut guard = self.state.lock().await;
|
||||
guard.add_message(ChatMessage::assistant(content.clone()));
|
||||
return Ok(content);
|
||||
}
|
||||
|
||||
Ok(String::new())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use llm_core::{Tool, ChunkStream, ChatResponse};
|
||||
use async_trait::async_trait;
|
||||
use agent_core::messages::UserAction;
|
||||
|
||||
struct MockProvider;
|
||||
#[async_trait]
|
||||
impl LlmProvider for MockProvider {
|
||||
fn name(&self) -> &str { "mock" }
|
||||
fn model(&self) -> &str { "mock" }
|
||||
async fn chat_stream(
|
||||
&self,
|
||||
_messages: &[ChatMessage],
|
||||
_options: &ChatOptions,
|
||||
_tools: Option<&[Tool]>,
|
||||
) -> Result<ChunkStream, llm_core::LlmError> {
|
||||
unimplemented!()
|
||||
}
|
||||
async fn chat(
|
||||
&self,
|
||||
_messages: &[ChatMessage],
|
||||
_options: &ChatOptions,
|
||||
_tools: Option<&[Tool]>,
|
||||
) -> Result<ChatResponse, llm_core::LlmError> {
|
||||
Ok(ChatResponse {
|
||||
content: Some("Mock Response".to_string()),
|
||||
tool_calls: None,
|
||||
usage: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_reasoning_loop_basic() {
|
||||
let client = Arc::new(MockProvider);
|
||||
let state = Arc::new(Mutex::new(AppState::new()));
|
||||
let manager = AgentManager::new(client, state);
|
||||
|
||||
let response = manager.step("Hello").await.unwrap();
|
||||
assert_eq!(response, "Mock Response");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sub_agent_spawn() {
|
||||
let client = Arc::new(MockProvider);
|
||||
let state = Arc::new(Mutex::new(AppState::new()));
|
||||
let manager = AgentManager::new(client, state);
|
||||
|
||||
let result = manager.spawn_sub_agent("Do something").await.unwrap();
|
||||
assert_eq!(result, "Sub-agent task completed (mock)");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_permission_request() {
|
||||
let client = Arc::new(MockProvider);
|
||||
let state = Arc::new(Mutex::new(AppState::new()));
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
|
||||
let manager = AgentManager::new(client, state.clone()).with_ui_sender(tx);
|
||||
|
||||
let state_clone = state.clone();
|
||||
tokio::spawn(async move {
|
||||
// Simulate UI receiving request and granting permission
|
||||
if let Some(Message::AgentResponse(AgentResponse::PermissionRequest { .. })) = rx.recv().await {
|
||||
let mut guard = state_clone.lock().await;
|
||||
guard.set_permission_result(true);
|
||||
}
|
||||
});
|
||||
|
||||
let allowed = manager.check_permission("bash", Some("ls")).await.unwrap();
|
||||
assert!(allowed);
|
||||
}
|
||||
}
|
||||
382
crates/app/cli/src/commands.rs
Normal file
382
crates/app/cli/src/commands.rs
Normal file
@@ -0,0 +1,382 @@
|
||||
//! Built-in commands for CLI and TUI
|
||||
//!
|
||||
//! Provides handlers for /help, /mcp, /hooks, /clear, and other built-in commands.
|
||||
|
||||
use ui::{CommandInfo, CommandOutput, OutputFormat, TreeNode, ListItem};
|
||||
use permissions::PermissionManager;
|
||||
use hooks::HookManager;
|
||||
use plugins::PluginManager;
|
||||
use agent_core::SessionStats;
|
||||
|
||||
/// Result of executing a built-in command
|
||||
pub enum CommandResult {
|
||||
/// Command produced output to display
|
||||
Output(CommandOutput),
|
||||
/// Command was handled but produced no output (e.g., /clear)
|
||||
Handled,
|
||||
/// Command was not recognized
|
||||
NotFound,
|
||||
/// Command needs to exit the session
|
||||
Exit,
|
||||
}
|
||||
|
||||
/// Built-in command handler
|
||||
pub struct BuiltinCommands<'a> {
|
||||
plugin_manager: Option<&'a PluginManager>,
|
||||
hook_manager: Option<&'a HookManager>,
|
||||
permission_manager: Option<&'a PermissionManager>,
|
||||
stats: Option<&'a SessionStats>,
|
||||
}
|
||||
|
||||
impl<'a> BuiltinCommands<'a> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
plugin_manager: None,
|
||||
hook_manager: None,
|
||||
permission_manager: None,
|
||||
stats: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_plugins(mut self, pm: &'a PluginManager) -> Self {
|
||||
self.plugin_manager = Some(pm);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_hooks(mut self, hm: &'a HookManager) -> Self {
|
||||
self.hook_manager = Some(hm);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_permissions(mut self, perms: &'a PermissionManager) -> Self {
|
||||
self.permission_manager = Some(perms);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_stats(mut self, stats: &'a SessionStats) -> Self {
|
||||
self.stats = Some(stats);
|
||||
self
|
||||
}
|
||||
|
||||
/// Execute a built-in command
|
||||
pub fn execute(&self, command: &str) -> CommandResult {
|
||||
let parts: Vec<&str> = command.split_whitespace().collect();
|
||||
let cmd = parts.first().map(|s| s.trim_start_matches('/'));
|
||||
|
||||
match cmd {
|
||||
Some("help") | Some("?") => CommandResult::Output(self.help()),
|
||||
Some("mcp") => CommandResult::Output(self.mcp()),
|
||||
Some("hooks") => CommandResult::Output(self.hooks()),
|
||||
Some("plugins") => CommandResult::Output(self.plugins()),
|
||||
Some("status") => CommandResult::Output(self.status()),
|
||||
Some("permissions") | Some("perms") => CommandResult::Output(self.permissions()),
|
||||
Some("clear") => CommandResult::Handled,
|
||||
Some("exit") | Some("quit") | Some("q") => CommandResult::Exit,
|
||||
_ => CommandResult::NotFound,
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate help output
|
||||
fn help(&self) -> CommandOutput {
|
||||
let mut commands = vec![
|
||||
// Built-in commands
|
||||
CommandInfo::new("help", "Show available commands", "builtin"),
|
||||
CommandInfo::new("clear", "Clear the screen", "builtin"),
|
||||
CommandInfo::new("status", "Show session status", "builtin"),
|
||||
CommandInfo::new("permissions", "Show permission settings", "builtin"),
|
||||
CommandInfo::new("mcp", "List MCP servers and tools", "builtin"),
|
||||
CommandInfo::new("hooks", "Show loaded hooks", "builtin"),
|
||||
CommandInfo::new("plugins", "Show loaded plugins", "builtin"),
|
||||
CommandInfo::new("checkpoint", "Save session state", "builtin"),
|
||||
CommandInfo::new("checkpoints", "List saved checkpoints", "builtin"),
|
||||
CommandInfo::new("rewind", "Restore from checkpoint", "builtin"),
|
||||
CommandInfo::new("compact", "Compact conversation context", "builtin"),
|
||||
CommandInfo::new("exit", "Exit the session", "builtin"),
|
||||
];
|
||||
|
||||
// Add plugin commands
|
||||
if let Some(pm) = self.plugin_manager {
|
||||
for plugin in pm.plugins() {
|
||||
for cmd_name in plugin.all_command_names() {
|
||||
commands.push(CommandInfo::new(
|
||||
&cmd_name,
|
||||
&format!("Plugin command from {}", plugin.manifest.name),
|
||||
&format!("plugin:{}", plugin.manifest.name),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CommandOutput::help_table(&commands)
|
||||
}
|
||||
|
||||
/// Generate MCP servers output
|
||||
fn mcp(&self) -> CommandOutput {
|
||||
let mut servers: Vec<(String, Vec<String>)> = vec![];
|
||||
|
||||
// Get MCP servers from plugins
|
||||
if let Some(pm) = self.plugin_manager {
|
||||
for plugin in pm.plugins() {
|
||||
// Check for .mcp.json in plugin directory
|
||||
let mcp_path = plugin.base_path.join(".mcp.json");
|
||||
if mcp_path.exists() {
|
||||
if let Ok(content) = std::fs::read_to_string(&mcp_path) {
|
||||
if let Ok(config) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
if let Some(mcpservers) = config.get("mcpServers").and_then(|v| v.as_object()) {
|
||||
for (name, _) in mcpservers {
|
||||
servers.push((
|
||||
format!("{} ({})", name, plugin.manifest.name),
|
||||
vec!["(connect to discover tools)".to_string()],
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if servers.is_empty() {
|
||||
CommandOutput::new(OutputFormat::Text {
|
||||
content: "No MCP servers configured.\n\nAdd MCP servers in plugin .mcp.json files.".to_string(),
|
||||
})
|
||||
} else {
|
||||
CommandOutput::mcp_tree(&servers)
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate hooks output
|
||||
fn hooks(&self) -> CommandOutput {
|
||||
let mut hooks_list: Vec<(String, String, bool)> = vec![];
|
||||
|
||||
// Check for file-based hooks in .owlen/hooks/
|
||||
let hook_events = ["PreToolUse", "PostToolUse", "SessionStart", "SessionEnd",
|
||||
"UserPromptSubmit", "PreCompact", "Stop", "SubagentStop"];
|
||||
|
||||
for event in hook_events {
|
||||
let path = format!(".owlen/hooks/{}", event);
|
||||
let exists = std::path::Path::new(&path).exists();
|
||||
if exists {
|
||||
hooks_list.push((event.to_string(), path, true));
|
||||
}
|
||||
}
|
||||
|
||||
// Get hooks from plugins
|
||||
if let Some(pm) = self.plugin_manager {
|
||||
for plugin in pm.plugins() {
|
||||
if let Some(hooks_config) = plugin.load_hooks_config().ok().flatten() {
|
||||
// hooks_config.hooks is HashMap<String, Vec<HookMatcher>>
|
||||
for (event_name, matchers) in &hooks_config.hooks {
|
||||
for matcher in matchers {
|
||||
for hook_def in &matcher.hooks {
|
||||
let cmd = hook_def.command.as_deref()
|
||||
.or(hook_def.prompt.as_deref())
|
||||
.unwrap_or("(no command)");
|
||||
hooks_list.push((
|
||||
event_name.clone(),
|
||||
format!("{}: {}", plugin.manifest.name, cmd),
|
||||
true,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if hooks_list.is_empty() {
|
||||
CommandOutput::new(OutputFormat::Text {
|
||||
content: "No hooks configured.\n\nAdd hooks in .owlen/hooks/ or plugin hooks.json files.".to_string(),
|
||||
})
|
||||
} else {
|
||||
CommandOutput::hooks_list(&hooks_list)
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate plugins output
|
||||
fn plugins(&self) -> CommandOutput {
|
||||
if let Some(pm) = self.plugin_manager {
|
||||
let plugins = pm.plugins();
|
||||
if plugins.is_empty() {
|
||||
return CommandOutput::new(OutputFormat::Text {
|
||||
content: "No plugins loaded.\n\nPlace plugins in:\n - ~/.config/owlen/plugins (user)\n - .owlen/plugins (project)".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// Build tree of plugins and their components
|
||||
let children: Vec<TreeNode> = plugins.iter().map(|p| {
|
||||
let mut plugin_children = vec![];
|
||||
|
||||
let commands = p.all_command_names();
|
||||
if !commands.is_empty() {
|
||||
plugin_children.push(TreeNode::new("Commands").with_children(
|
||||
commands.iter().map(|c| TreeNode::new(format!("/{}", c))).collect()
|
||||
));
|
||||
}
|
||||
|
||||
let agents = p.all_agent_names();
|
||||
if !agents.is_empty() {
|
||||
plugin_children.push(TreeNode::new("Agents").with_children(
|
||||
agents.iter().map(|a| TreeNode::new(a)).collect()
|
||||
));
|
||||
}
|
||||
|
||||
let skills = p.all_skill_names();
|
||||
if !skills.is_empty() {
|
||||
plugin_children.push(TreeNode::new("Skills").with_children(
|
||||
skills.iter().map(|s| TreeNode::new(s)).collect()
|
||||
));
|
||||
}
|
||||
|
||||
TreeNode::new(format!("{} v{}", p.manifest.name, p.manifest.version))
|
||||
.with_children(plugin_children)
|
||||
}).collect();
|
||||
|
||||
CommandOutput::new(OutputFormat::Tree {
|
||||
root: TreeNode::new("Loaded Plugins").with_children(children),
|
||||
})
|
||||
} else {
|
||||
CommandOutput::new(OutputFormat::Text {
|
||||
content: "Plugin manager not available.".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate status output
|
||||
fn status(&self) -> CommandOutput {
|
||||
let mut items = vec![];
|
||||
|
||||
if let Some(stats) = self.stats {
|
||||
items.push(ListItem {
|
||||
text: format!("Messages: {}", stats.total_messages),
|
||||
marker: Some("📊".to_string()),
|
||||
style: None,
|
||||
});
|
||||
items.push(ListItem {
|
||||
text: format!("Tool Calls: {}", stats.total_tool_calls),
|
||||
marker: Some("🔧".to_string()),
|
||||
style: None,
|
||||
});
|
||||
items.push(ListItem {
|
||||
text: format!("Est. Tokens: ~{}", stats.estimated_tokens),
|
||||
marker: Some("📝".to_string()),
|
||||
style: None,
|
||||
});
|
||||
let uptime = stats.start_time.elapsed().unwrap_or_default();
|
||||
items.push(ListItem {
|
||||
text: format!("Uptime: {}", SessionStats::format_duration(uptime)),
|
||||
marker: Some("⏱️".to_string()),
|
||||
style: None,
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(perms) = self.permission_manager {
|
||||
items.push(ListItem {
|
||||
text: format!("Mode: {:?}", perms.mode()),
|
||||
marker: Some("🔒".to_string()),
|
||||
style: None,
|
||||
});
|
||||
}
|
||||
|
||||
if items.is_empty() {
|
||||
CommandOutput::new(OutputFormat::Text {
|
||||
content: "Session status not available.".to_string(),
|
||||
})
|
||||
} else {
|
||||
CommandOutput::new(OutputFormat::List { items })
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate permissions output
|
||||
fn permissions(&self) -> CommandOutput {
|
||||
if let Some(perms) = self.permission_manager {
|
||||
let mode = perms.mode();
|
||||
let mode_str = format!("{:?}", mode);
|
||||
|
||||
let mut items = vec![
|
||||
ListItem {
|
||||
text: format!("Current Mode: {}", mode_str),
|
||||
marker: Some("🔒".to_string()),
|
||||
style: None,
|
||||
},
|
||||
];
|
||||
|
||||
// Add tool permissions summary
|
||||
let (read_status, write_status, bash_status) = match mode {
|
||||
permissions::Mode::Plan => ("✅ Allowed", "❓ Ask", "❓ Ask"),
|
||||
permissions::Mode::AcceptEdits => ("✅ Allowed", "✅ Allowed", "❓ Ask"),
|
||||
permissions::Mode::Code => ("✅ Allowed", "✅ Allowed", "✅ Allowed"),
|
||||
};
|
||||
|
||||
items.push(ListItem {
|
||||
text: format!("Read/Grep/Glob: {}", read_status),
|
||||
marker: None,
|
||||
style: None,
|
||||
});
|
||||
items.push(ListItem {
|
||||
text: format!("Write/Edit: {}", write_status),
|
||||
marker: None,
|
||||
style: None,
|
||||
});
|
||||
items.push(ListItem {
|
||||
text: format!("Bash: {}", bash_status),
|
||||
marker: None,
|
||||
style: None,
|
||||
});
|
||||
|
||||
CommandOutput::new(OutputFormat::List { items })
|
||||
} else {
|
||||
CommandOutput::new(OutputFormat::Text {
|
||||
content: "Permission manager not available.".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BuiltinCommands<'_> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_help_command() {
|
||||
let handler = BuiltinCommands::new();
|
||||
match handler.execute("/help") {
|
||||
CommandResult::Output(output) => {
|
||||
match output.format {
|
||||
OutputFormat::Table { headers, rows } => {
|
||||
assert!(!headers.is_empty());
|
||||
assert!(!rows.is_empty());
|
||||
}
|
||||
_ => panic!("Expected Table format"),
|
||||
}
|
||||
}
|
||||
_ => panic!("Expected Output result"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_exit_command() {
|
||||
let handler = BuiltinCommands::new();
|
||||
assert!(matches!(handler.execute("/exit"), CommandResult::Exit));
|
||||
assert!(matches!(handler.execute("/quit"), CommandResult::Exit));
|
||||
assert!(matches!(handler.execute("/q"), CommandResult::Exit));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clear_command() {
|
||||
let handler = BuiltinCommands::new();
|
||||
assert!(matches!(handler.execute("/clear"), CommandResult::Handled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unknown_command() {
|
||||
let handler = BuiltinCommands::new();
|
||||
assert!(matches!(handler.execute("/unknown"), CommandResult::NotFound));
|
||||
}
|
||||
}
|
||||
329
crates/app/cli/src/engine.rs
Normal file
329
crates/app/cli/src/engine.rs
Normal file
@@ -0,0 +1,329 @@
|
||||
use agent_core::messages::{Message, UserAction, AgentResponse, SystemNotification};
|
||||
use agent_core::state::AppState;
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
use std::sync::Arc;
|
||||
use std::path::PathBuf;
|
||||
use llm_core::LlmProvider;
|
||||
use ui::ProviderManager;
|
||||
use tools_plan::PlanManager;
|
||||
use crate::agent_manager::AgentManager;
|
||||
|
||||
/// The main background task that handles logic, API calls, and state updates.
|
||||
/// Uses a shared ProviderManager for dynamic provider/model switching.
|
||||
pub async fn run_engine_loop_dynamic(
|
||||
mut rx: mpsc::Receiver<Message>,
|
||||
tx_ui: mpsc::Sender<Message>,
|
||||
provider_manager: Arc<Mutex<ProviderManager>>,
|
||||
state: Arc<Mutex<AppState>>,
|
||||
) {
|
||||
let agent_manager = Arc::new(
|
||||
AgentManager::with_provider_manager(provider_manager, state.clone())
|
||||
.with_ui_sender(tx_ui.clone())
|
||||
);
|
||||
|
||||
// Plan manager for persistence
|
||||
let plan_manager = PlanManager::new(PathBuf::from("."));
|
||||
|
||||
while let Some(msg) = rx.recv().await {
|
||||
match msg {
|
||||
Message::UserAction(UserAction::Input(text)) => {
|
||||
let agent_manager_clone = agent_manager.clone();
|
||||
let tx_clone = tx_ui.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = agent_manager_clone.run(&text).await {
|
||||
let _ = tx_clone.send(Message::AgentResponse(AgentResponse::Error(e.to_string()))).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
Message::UserAction(UserAction::PermissionResult(res)) => {
|
||||
let mut guard = state.lock().await;
|
||||
guard.set_permission_result(res);
|
||||
}
|
||||
Message::UserAction(UserAction::FinalizePlan) => {
|
||||
let mut guard = state.lock().await;
|
||||
if let Some(plan) = guard.current_plan_mut() {
|
||||
plan.finalize();
|
||||
let total_steps = plan.steps.len();
|
||||
let status = plan.status.clone();
|
||||
drop(guard);
|
||||
let _ = tx_ui.send(Message::AgentResponse(AgentResponse::PlanComplete {
|
||||
total_steps,
|
||||
status,
|
||||
})).await;
|
||||
}
|
||||
}
|
||||
Message::UserAction(UserAction::PlanApproval(approval)) => {
|
||||
let mut guard = state.lock().await;
|
||||
if let Some(plan) = guard.current_plan_mut() {
|
||||
// Apply approval decisions
|
||||
approval.apply_to(plan);
|
||||
plan.start_execution();
|
||||
|
||||
// Get approved steps for execution
|
||||
let approved_steps: Vec<_> = plan.steps.iter()
|
||||
.filter(|s| s.is_approved())
|
||||
.cloned()
|
||||
.collect();
|
||||
let total = approved_steps.len();
|
||||
let skipped = plan.steps.iter().filter(|s| s.is_rejected()).count();
|
||||
|
||||
drop(guard);
|
||||
|
||||
// Execute approved steps
|
||||
for (idx, step) in approved_steps.iter().enumerate() {
|
||||
let _ = tx_ui.send(Message::AgentResponse(AgentResponse::PlanExecuting {
|
||||
step_id: step.id.clone(),
|
||||
step_index: idx,
|
||||
total_steps: total,
|
||||
})).await;
|
||||
|
||||
// Execute the tool
|
||||
let agent_manager_clone = agent_manager.clone();
|
||||
let tx_clone = tx_ui.clone();
|
||||
let step_clone = step.clone();
|
||||
|
||||
// Execute tool and send result
|
||||
if let Err(e) = agent_manager_clone.execute_single_tool(&step_clone.tool, &step_clone.args).await {
|
||||
let _ = tx_clone.send(Message::AgentResponse(AgentResponse::Error(
|
||||
format!("Step {} failed: {}", idx + 1, e)
|
||||
))).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Mark plan as completed
|
||||
let mut guard = state.lock().await;
|
||||
if let Some(plan) = guard.current_plan_mut() {
|
||||
plan.complete();
|
||||
}
|
||||
drop(guard);
|
||||
|
||||
let _ = tx_ui.send(Message::AgentResponse(AgentResponse::PlanExecutionComplete {
|
||||
executed: total,
|
||||
skipped,
|
||||
})).await;
|
||||
}
|
||||
}
|
||||
Message::UserAction(UserAction::SavePlan(name)) => {
|
||||
let guard = state.lock().await;
|
||||
if let Some(plan) = guard.current_plan() {
|
||||
let mut plan_to_save = plan.clone();
|
||||
plan_to_save.name = Some(name.clone());
|
||||
drop(guard);
|
||||
|
||||
match plan_manager.save_accumulated_plan(&plan_to_save).await {
|
||||
Ok(path) => {
|
||||
let _ = tx_ui.send(Message::System(SystemNotification::PlanSaved {
|
||||
id: plan_to_save.id.clone(),
|
||||
path: path.display().to_string(),
|
||||
})).await;
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = tx_ui.send(Message::AgentResponse(AgentResponse::Error(
|
||||
format!("Failed to save plan: {}", e)
|
||||
))).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Message::UserAction(UserAction::LoadPlan(id)) => {
|
||||
match plan_manager.load_accumulated_plan(&id).await {
|
||||
Ok(plan) => {
|
||||
let name = plan.name.clone();
|
||||
let steps = plan.steps.len();
|
||||
let mut guard = state.lock().await;
|
||||
guard.accumulated_plan = Some(plan);
|
||||
drop(guard);
|
||||
|
||||
let _ = tx_ui.send(Message::System(SystemNotification::PlanLoaded {
|
||||
id,
|
||||
name,
|
||||
steps,
|
||||
})).await;
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = tx_ui.send(Message::AgentResponse(AgentResponse::Error(
|
||||
format!("Failed to load plan: {}", e)
|
||||
))).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Message::UserAction(UserAction::CancelPlan) => {
|
||||
let mut guard = state.lock().await;
|
||||
if let Some(plan) = guard.current_plan_mut() {
|
||||
plan.cancel();
|
||||
}
|
||||
guard.clear_plan();
|
||||
}
|
||||
Message::UserAction(UserAction::Exit) => {
|
||||
let mut guard = state.lock().await;
|
||||
guard.running = false;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Legacy engine loop with fixed client (for backward compatibility)
|
||||
pub async fn run_engine_loop(
|
||||
mut rx: mpsc::Receiver<Message>,
|
||||
tx_ui: mpsc::Sender<Message>,
|
||||
client: Arc<dyn LlmProvider>,
|
||||
state: Arc<Mutex<AppState>>,
|
||||
) {
|
||||
let agent_manager = Arc::new(AgentManager::new(client, state.clone()).with_ui_sender(tx_ui.clone()));
|
||||
|
||||
while let Some(msg) = rx.recv().await {
|
||||
match msg {
|
||||
Message::UserAction(UserAction::Input(text)) => {
|
||||
let agent_manager_clone = agent_manager.clone();
|
||||
let tx_clone = tx_ui.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = agent_manager_clone.run(&text).await {
|
||||
let _ = tx_clone.send(Message::AgentResponse(AgentResponse::Error(e.to_string()))).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
Message::UserAction(UserAction::PermissionResult(res)) => {
|
||||
let mut guard = state.lock().await;
|
||||
guard.set_permission_result(res);
|
||||
}
|
||||
Message::UserAction(UserAction::Exit) => {
|
||||
let mut guard = state.lock().await;
|
||||
guard.running = false;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use llm_core::{LlmError, Tool, ChunkStream, StreamChunk, ChatMessage, ChatOptions};
|
||||
use async_trait::async_trait;
|
||||
use futures::stream;
|
||||
|
||||
struct MockProvider;
|
||||
|
||||
#[async_trait]
|
||||
impl LlmProvider for MockProvider {
|
||||
fn name(&self) -> &str { "mock" }
|
||||
fn model(&self) -> &str { "mock-model" }
|
||||
|
||||
async fn chat_stream(
|
||||
&self,
|
||||
_messages: &[ChatMessage],
|
||||
_options: &ChatOptions,
|
||||
_tools: Option<&[Tool]>,
|
||||
) -> Result<ChunkStream, LlmError> {
|
||||
let chunks = vec![
|
||||
Ok(StreamChunk { content: Some("Hello".to_string()), tool_calls: None, done: false, usage: None }),
|
||||
Ok(StreamChunk { content: Some(" World".to_string()), tool_calls: None, done: true, usage: None }),
|
||||
];
|
||||
Ok(Box::pin(stream::iter(chunks)))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_engine_streaming() {
|
||||
let (tx_in, rx_in) = mpsc::channel(1);
|
||||
let (tx_out, mut rx_out) = mpsc::channel(10);
|
||||
|
||||
let client = Arc::new(MockProvider);
|
||||
let state = Arc::new(Mutex::new(AppState::new()));
|
||||
|
||||
// Spawn the engine loop
|
||||
tokio::spawn(async move {
|
||||
run_engine_loop(rx_in, tx_out, client, state).await;
|
||||
});
|
||||
|
||||
// Send a message
|
||||
tx_in.send(Message::UserAction(UserAction::Input("Hi".to_string()))).await.unwrap();
|
||||
|
||||
// Verify streaming responses
|
||||
let mut tokens = Vec::new();
|
||||
while let Some(msg) = rx_out.recv().await {
|
||||
match msg {
|
||||
Message::AgentResponse(AgentResponse::Token(s)) => tokens.push(s),
|
||||
Message::AgentResponse(AgentResponse::Complete) => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(tokens, vec!["Hello", " World"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_engine_permission_result() {
|
||||
let (tx_in, rx_in) = mpsc::channel(1);
|
||||
let (tx_out, _rx_out) = mpsc::channel(10);
|
||||
|
||||
let client = Arc::new(MockProvider);
|
||||
let state = Arc::new(Mutex::new(AppState::new()));
|
||||
let state_clone = state.clone();
|
||||
|
||||
// Spawn the engine loop
|
||||
tokio::spawn(async move {
|
||||
run_engine_loop(rx_in, tx_out, client, state_clone).await;
|
||||
});
|
||||
|
||||
// Send a PermissionResult
|
||||
tx_in.send(Message::UserAction(UserAction::PermissionResult(true))).await.unwrap();
|
||||
|
||||
// Give it a moment to process
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
|
||||
|
||||
let guard = state.lock().await;
|
||||
assert_eq!(guard.last_permission_result, Some(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_engine_plan_mode() {
|
||||
use agent_core::state::AppMode;
|
||||
|
||||
let (tx_in, rx_in) = mpsc::channel(1);
|
||||
let (tx_out, mut rx_out) = mpsc::channel(10);
|
||||
|
||||
let client = Arc::new(MockProvider);
|
||||
let state = Arc::new(Mutex::new(AppState::new()));
|
||||
|
||||
// Set Plan mode
|
||||
{
|
||||
let mut guard = state.lock().await;
|
||||
guard.mode = AppMode::Plan;
|
||||
}
|
||||
|
||||
let state_clone = state.clone();
|
||||
|
||||
// Spawn the engine loop
|
||||
tokio::spawn(async move {
|
||||
run_engine_loop(rx_in, tx_out, client, state_clone).await;
|
||||
});
|
||||
|
||||
// Send a message
|
||||
tx_in.send(Message::UserAction(UserAction::Input("Hi".to_string()))).await.unwrap();
|
||||
|
||||
// Verify we get responses (tokens and complete)
|
||||
let mut received_tokens = false;
|
||||
let mut received_complete = false;
|
||||
let timeout = tokio::time::timeout(tokio::time::Duration::from_secs(2), async {
|
||||
while let Some(msg) = rx_out.recv().await {
|
||||
match msg {
|
||||
Message::AgentResponse(AgentResponse::Token(_)) => received_tokens = true,
|
||||
Message::AgentResponse(AgentResponse::Complete) => {
|
||||
received_complete = true;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}).await;
|
||||
|
||||
assert!(timeout.is_ok(), "Should receive responses within timeout");
|
||||
assert!(received_tokens, "Should receive tokens");
|
||||
assert!(received_complete, "Should receive complete signal");
|
||||
}
|
||||
}
|
||||
1160
crates/app/cli/src/main.rs
Normal file
1160
crates/app/cli/src/main.rs
Normal file
File diff suppressed because it is too large
Load Diff
56
crates/app/cli/src/tool_registry.rs
Normal file
56
crates/app/cli/src/tool_registry.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
use std::collections::HashMap;
|
||||
use serde_json::Value;
|
||||
use llm_core::Tool;
|
||||
|
||||
/// Registry for tools available to the agent
|
||||
pub struct ToolRegistry {
|
||||
tools: HashMap<String, Tool>,
|
||||
}
|
||||
|
||||
impl ToolRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tools: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Register a tool
|
||||
pub fn register(&mut self, tool: Tool) {
|
||||
self.tools.insert(tool.function.name.clone(), tool);
|
||||
}
|
||||
|
||||
/// Get a tool by name
|
||||
pub fn get(&self, name: &str) -> Option<&Tool> {
|
||||
self.tools.get(name)
|
||||
}
|
||||
|
||||
/// Get all registered tools as a list (for LLM context)
|
||||
pub fn list_tools(&self) -> Vec<Tool> {
|
||||
self.tools.values().cloned().collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use llm_core::{ToolParameters, ToolFunction};
|
||||
|
||||
fn create_mock_tool(name: &str) -> Tool {
|
||||
Tool::function(
|
||||
name,
|
||||
"Description",
|
||||
ToolParameters::object(serde_json::json!({}), vec![])
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_registry() {
|
||||
let mut registry = ToolRegistry::new();
|
||||
let tool = create_mock_tool("test_tool");
|
||||
|
||||
registry.register(tool.clone());
|
||||
|
||||
assert!(registry.get("test_tool").is_some());
|
||||
assert_eq!(registry.list_tools().len(), 1);
|
||||
}
|
||||
}
|
||||
34
crates/app/cli/tests/chat_stream.rs
Normal file
34
crates/app/cli/tests/chat_stream.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use assert_cmd::Command;
|
||||
use httpmock::prelude::*;
|
||||
use predicates::prelude::PredicateBooleanExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn headless_streams_ndjson() {
|
||||
let server = MockServer::start_async().await;
|
||||
|
||||
let response = concat!(
|
||||
r#"{"message":{"role":"assistant","content":"Hel"}}"#,"\n",
|
||||
r#"{"message":{"role":"assistant","content":"lo"}}"#,"\n",
|
||||
r#"{"done":true}"#,"\n",
|
||||
);
|
||||
|
||||
// The CLI includes tools in the request, so we need to match any request to /api/chat
|
||||
// instead of matching exact body (which includes tool definitions)
|
||||
let _m = server.mock(|when, then| {
|
||||
when.method(POST)
|
||||
.path("/api/chat");
|
||||
then.status(200)
|
||||
.header("content-type", "application/x-ndjson")
|
||||
.body(response);
|
||||
});
|
||||
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("--ollama-url").arg(server.base_url())
|
||||
.arg("--model").arg("qwen2.5")
|
||||
.arg("--print")
|
||||
.arg("hello");
|
||||
|
||||
cmd.assert()
|
||||
.success()
|
||||
.stdout(predicates::str::contains("Hello").count(1).or(predicates::str::contains("Hel").and(predicates::str::contains("lo"))));
|
||||
}
|
||||
145
crates/app/cli/tests/headless.rs
Normal file
145
crates/app/cli/tests/headless.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
use assert_cmd::Command;
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn print_json_has_session_id_and_stats() {
|
||||
let mut cmd = Command::cargo_bin("owlen").unwrap();
|
||||
cmd.arg("--output-format")
|
||||
.arg("json")
|
||||
.arg("Say hello");
|
||||
|
||||
let output = cmd.assert().success();
|
||||
let stdout = String::from_utf8_lossy(&output.get_output().stdout);
|
||||
|
||||
// Parse JSON output
|
||||
let json: Value = serde_json::from_str(&stdout).expect("Output should be valid JSON");
|
||||
|
||||
// Verify session_id exists
|
||||
assert!(json.get("session_id").is_some(), "JSON output should have session_id");
|
||||
let session_id = json["session_id"].as_str().unwrap();
|
||||
assert!(!session_id.is_empty(), "session_id should not be empty");
|
||||
|
||||
// Verify stats exist
|
||||
assert!(json.get("stats").is_some(), "JSON output should have stats");
|
||||
let stats = &json["stats"];
|
||||
|
||||
// Check for token counts
|
||||
assert!(stats.get("total_tokens").is_some(), "stats should have total_tokens");
|
||||
|
||||
// Check for messages
|
||||
assert!(json.get("messages").is_some(), "JSON output should have messages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_json_sequence_is_well_formed() {
|
||||
let mut cmd = Command::cargo_bin("owlen").unwrap();
|
||||
cmd.arg("--output-format")
|
||||
.arg("stream-json")
|
||||
.arg("Say hello");
|
||||
|
||||
let output = cmd.assert().success();
|
||||
let stdout = String::from_utf8_lossy(&output.get_output().stdout);
|
||||
|
||||
// Stream-JSON is NDJSON - each line should be valid JSON
|
||||
let lines: Vec<&str> = stdout.lines().filter(|l| !l.is_empty()).collect();
|
||||
|
||||
assert!(!lines.is_empty(), "Stream-JSON should produce at least one event");
|
||||
|
||||
// Each line should be valid JSON
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
let json: Value = serde_json::from_str(line)
|
||||
.expect(&format!("Line {} should be valid JSON: {}", i, line));
|
||||
|
||||
// Each event should have a type
|
||||
assert!(json.get("type").is_some(), "Event should have a type field");
|
||||
}
|
||||
|
||||
// First event should be session_start
|
||||
let first: Value = serde_json::from_str(lines[0]).unwrap();
|
||||
assert_eq!(first["type"].as_str().unwrap(), "session_start");
|
||||
assert!(first.get("session_id").is_some());
|
||||
|
||||
// Last event should be session_end or complete
|
||||
let last: Value = serde_json::from_str(lines[lines.len() - 1]).unwrap();
|
||||
let last_type = last["type"].as_str().unwrap();
|
||||
assert!(
|
||||
last_type == "session_end" || last_type == "complete",
|
||||
"Last event should be session_end or complete, got: {}",
|
||||
last_type
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_format_is_default() {
|
||||
let mut cmd = Command::cargo_bin("owlen").unwrap();
|
||||
cmd.arg("Say hello");
|
||||
|
||||
let output = cmd.assert().success();
|
||||
let stdout = String::from_utf8_lossy(&output.get_output().stdout);
|
||||
|
||||
// Text format should not be JSON
|
||||
assert!(serde_json::from_str::<Value>(&stdout).is_err(),
|
||||
"Default output should be text, not JSON");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_format_with_tool_execution() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("test.txt");
|
||||
fs::write(&file, "hello world").unwrap();
|
||||
|
||||
let mut cmd = Command::cargo_bin("owlen").unwrap();
|
||||
cmd.arg("--mode")
|
||||
.arg("code")
|
||||
.arg("--output-format")
|
||||
.arg("json")
|
||||
.arg("read")
|
||||
.arg(file.to_str().unwrap());
|
||||
|
||||
let output = cmd.assert().success();
|
||||
let stdout = String::from_utf8_lossy(&output.get_output().stdout);
|
||||
|
||||
let json: Value = serde_json::from_str(&stdout).expect("Output should be valid JSON");
|
||||
|
||||
// Should have result
|
||||
assert!(json.get("result").is_some());
|
||||
|
||||
// Should have tool info
|
||||
assert!(json.get("tool").is_some());
|
||||
assert_eq!(json["tool"].as_str().unwrap(), "Read");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_json_includes_chunk_events() {
|
||||
let mut cmd = Command::cargo_bin("owlen").unwrap();
|
||||
cmd.arg("--output-format")
|
||||
.arg("stream-json")
|
||||
.arg("Say hello");
|
||||
|
||||
let output = cmd.assert().success();
|
||||
let stdout = String::from_utf8_lossy(&output.get_output().stdout);
|
||||
|
||||
let lines: Vec<&str> = stdout.lines().filter(|l| !l.is_empty()).collect();
|
||||
|
||||
// Should have chunk events between session_start and session_end
|
||||
let chunk_events: Vec<&str> = lines.iter()
|
||||
.filter(|line| {
|
||||
if let Ok(json) = serde_json::from_str::<Value>(line) {
|
||||
json["type"].as_str() == Some("chunk")
|
||||
} else {
|
||||
false
|
||||
}
|
||||
})
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
assert!(!chunk_events.is_empty(), "Should have at least one chunk event");
|
||||
|
||||
// Each chunk should have content
|
||||
for chunk_line in chunk_events {
|
||||
let chunk: Value = serde_json::from_str(chunk_line).unwrap();
|
||||
assert!(chunk.get("content").is_some(), "Chunk should have content");
|
||||
}
|
||||
}
|
||||
255
crates/app/cli/tests/permissions.rs
Normal file
255
crates/app/cli/tests/permissions.rs
Normal file
@@ -0,0 +1,255 @@
|
||||
use assert_cmd::Command;
|
||||
use std::fs;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn plan_mode_allows_read_operations() {
|
||||
// Create a temp file to read
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("test.txt");
|
||||
fs::write(&file, "hello world").unwrap();
|
||||
|
||||
// Read operation should work in plan mode (default)
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("read").arg(file.to_str().unwrap());
|
||||
cmd.assert().success().stdout("hello world\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_mode_allows_glob_operations() {
|
||||
let dir = tempdir().unwrap();
|
||||
fs::write(dir.path().join("a.txt"), "test").unwrap();
|
||||
fs::write(dir.path().join("b.txt"), "test").unwrap();
|
||||
|
||||
let pattern = format!("{}/*.txt", dir.path().display());
|
||||
|
||||
// Glob operation should work in plan mode (default)
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("glob").arg(&pattern);
|
||||
cmd.assert().success();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_mode_allows_grep_operations() {
|
||||
let dir = tempdir().unwrap();
|
||||
fs::write(dir.path().join("test.txt"), "hello world\nfoo bar").unwrap();
|
||||
|
||||
// Grep operation should work in plan mode (default)
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("grep").arg(dir.path().to_str().unwrap()).arg("hello");
|
||||
cmd.assert().success();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_override_via_cli_flag() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("test.txt");
|
||||
fs::write(&file, "content").unwrap();
|
||||
|
||||
// Test with --mode code (should also allow read)
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("--mode")
|
||||
.arg("code")
|
||||
.arg("read")
|
||||
.arg(file.to_str().unwrap());
|
||||
cmd.assert().success().stdout("content\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_mode_blocks_write_operations() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("new.txt");
|
||||
|
||||
// Write operation should be blocked in plan mode (default)
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("write").arg(file.to_str().unwrap()).arg("content");
|
||||
cmd.assert().failure();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_mode_blocks_edit_operations() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("test.txt");
|
||||
fs::write(&file, "old content").unwrap();
|
||||
|
||||
// Edit operation should be blocked in plan mode (default)
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("edit")
|
||||
.arg(file.to_str().unwrap())
|
||||
.arg("old")
|
||||
.arg("new");
|
||||
cmd.assert().failure();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accept_edits_mode_allows_write() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("new.txt");
|
||||
|
||||
// Write operation should work in acceptEdits mode
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("--mode")
|
||||
.arg("acceptEdits")
|
||||
.arg("write")
|
||||
.arg(file.to_str().unwrap())
|
||||
.arg("new content");
|
||||
cmd.assert().success();
|
||||
|
||||
// Verify file was written
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), "new content");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accept_edits_mode_allows_edit() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("test.txt");
|
||||
fs::write(&file, "line 1\nline 2\nline 3").unwrap();
|
||||
|
||||
// Edit operation should work in acceptEdits mode
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("--mode")
|
||||
.arg("acceptEdits")
|
||||
.arg("edit")
|
||||
.arg(file.to_str().unwrap())
|
||||
.arg("line 2")
|
||||
.arg("modified line");
|
||||
cmd.assert().success();
|
||||
|
||||
// Verify file was edited
|
||||
assert_eq!(
|
||||
fs::read_to_string(&file).unwrap(),
|
||||
"line 1\nmodified line\nline 3"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_allows_all_operations() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("test.txt");
|
||||
|
||||
// Write in code mode
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("--mode")
|
||||
.arg("code")
|
||||
.arg("write")
|
||||
.arg(file.to_str().unwrap())
|
||||
.arg("initial content");
|
||||
cmd.assert().success();
|
||||
|
||||
// Edit in code mode
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("--mode")
|
||||
.arg("code")
|
||||
.arg("edit")
|
||||
.arg(file.to_str().unwrap())
|
||||
.arg("initial")
|
||||
.arg("modified");
|
||||
cmd.assert().success();
|
||||
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), "modified content");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_mode_blocks_bash_operations() {
|
||||
// Bash operation should be blocked in plan mode (default)
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("bash").arg("echo hello");
|
||||
cmd.assert().failure();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_allows_bash() {
|
||||
// Bash operation should work in code mode
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("--mode").arg("code").arg("bash").arg("echo hello");
|
||||
cmd.assert().success().stdout("hello\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bash_command_timeout_works() {
|
||||
// Test that timeout works
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.arg("--mode")
|
||||
.arg("code")
|
||||
.arg("bash")
|
||||
.arg("sleep 10")
|
||||
.arg("--timeout")
|
||||
.arg("1000");
|
||||
cmd.assert().failure();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slash_command_works() {
|
||||
// Create .owlen/commands directory in temp dir
|
||||
let dir = tempdir().unwrap();
|
||||
let commands_dir = dir.path().join(".owlen/commands");
|
||||
fs::create_dir_all(&commands_dir).unwrap();
|
||||
|
||||
// Create a test slash command
|
||||
let command_content = r#"---
|
||||
description: "Test command"
|
||||
---
|
||||
Hello from slash command!
|
||||
Args: $ARGUMENTS
|
||||
First: $1
|
||||
"#;
|
||||
let command_file = commands_dir.join("test.md");
|
||||
fs::write(&command_file, command_content).unwrap();
|
||||
|
||||
// Execute slash command with args from the temp directory
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.current_dir(dir.path())
|
||||
.arg("--mode")
|
||||
.arg("code")
|
||||
.arg("slash")
|
||||
.arg("test")
|
||||
.arg("arg1");
|
||||
|
||||
cmd.assert()
|
||||
.success()
|
||||
.stdout(predicates::str::contains("Hello from slash command!"))
|
||||
.stdout(predicates::str::contains("Args: arg1"))
|
||||
.stdout(predicates::str::contains("First: arg1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slash_command_file_refs() {
|
||||
let dir = tempdir().unwrap();
|
||||
let commands_dir = dir.path().join(".owlen/commands");
|
||||
fs::create_dir_all(&commands_dir).unwrap();
|
||||
|
||||
// Create a file to reference
|
||||
let data_file = dir.path().join("data.txt");
|
||||
fs::write(&data_file, "Referenced content").unwrap();
|
||||
|
||||
// Create slash command with file reference
|
||||
let command_content = format!("File content: @{}", data_file.display());
|
||||
fs::write(commands_dir.join("reftest.md"), command_content).unwrap();
|
||||
|
||||
// Execute slash command
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.current_dir(dir.path())
|
||||
.arg("--mode")
|
||||
.arg("code")
|
||||
.arg("slash")
|
||||
.arg("reftest");
|
||||
|
||||
cmd.assert()
|
||||
.success()
|
||||
.stdout(predicates::str::contains("Referenced content"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slash_command_not_found() {
|
||||
let dir = tempdir().unwrap();
|
||||
|
||||
// Try to execute non-existent slash command
|
||||
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("owlen"));
|
||||
cmd.current_dir(dir.path())
|
||||
.arg("--mode")
|
||||
.arg("code")
|
||||
.arg("slash")
|
||||
.arg("nonexistent");
|
||||
|
||||
cmd.assert().failure();
|
||||
}
|
||||
31
crates/app/ui/Cargo.toml
Normal file
31
crates/app/ui/Cargo.toml
Normal file
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "ui"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
color-eyre = "0.6"
|
||||
crossterm = { version = "0.28", features = ["event-stream"] }
|
||||
ratatui = "0.28"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
futures = "0.3"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
unicode-width = "0.2"
|
||||
textwrap = "0.16"
|
||||
syntect = { version = "5.0", default-features = false, features = ["default-syntaxes", "default-themes", "regex-onig"] }
|
||||
pulldown-cmark = "0.11"
|
||||
|
||||
# Internal dependencies
|
||||
agent-core = { path = "../../core/agent" }
|
||||
auth-manager = { path = "../../platform/auth" }
|
||||
permissions = { path = "../../platform/permissions" }
|
||||
llm-core = { path = "../../llm/core" }
|
||||
llm-anthropic = { path = "../../llm/anthropic" }
|
||||
llm-ollama = { path = "../../llm/ollama" }
|
||||
llm-openai = { path = "../../llm/openai" }
|
||||
config-agent = { path = "../../platform/config" }
|
||||
tools-todo = { path = "../../tools/todo" }
|
||||
tools-plan = { path = "../../tools/plan" }
|
||||
18
crates/app/ui/README.md
Normal file
18
crates/app/ui/README.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Owlen UI
|
||||
|
||||
A Terminal User Interface (TUI) for the Owlen AI agent, built with Ratatui.
|
||||
|
||||
## Features
|
||||
- **Rich Text Rendering:** Markdown support with syntax highlighting for code blocks.
|
||||
- **Interactive Components:** Intuitive panels for chat, tool execution, and session status.
|
||||
- **Real-time Streaming:** Smooth display of agent output as it's generated.
|
||||
- **Task Visualization:** Dedicated view for tracking the agent's progress through a task list.
|
||||
|
||||
## Architecture
|
||||
The UI is built using an event-driven architecture integrated with the `agent-core` event stream. It leverages `ratatui` for terminal rendering and `crossterm` for event handling.
|
||||
|
||||
## Components
|
||||
- `ChatPanel`: Displays the conversation history.
|
||||
- `TaskPanel`: Shows the current implementation plan and task status.
|
||||
- `ToolPanel`: Visualizes active tool executions and their output.
|
||||
- `ModelPicker`: Allows selecting between available LLM providers and models.
|
||||
1927
crates/app/ui/src/app.rs
Normal file
1927
crates/app/ui/src/app.rs
Normal file
File diff suppressed because it is too large
Load Diff
226
crates/app/ui/src/completions.rs
Normal file
226
crates/app/ui/src/completions.rs
Normal file
@@ -0,0 +1,226 @@
|
||||
//! Command completion engine for the TUI
|
||||
//!
|
||||
//! Provides Tab-completion for slash commands, file paths, and tool names.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// A single completion suggestion
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Completion {
|
||||
/// The text to insert
|
||||
pub text: String,
|
||||
/// Description of what this completion does
|
||||
pub description: String,
|
||||
/// Source of the completion (e.g., "builtin", "plugin:name")
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
/// Information about a command for completion purposes
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CommandInfo {
|
||||
/// Command name (without leading /)
|
||||
pub name: String,
|
||||
/// Command description
|
||||
pub description: String,
|
||||
/// Source of the command
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
impl CommandInfo {
|
||||
pub fn new(name: &str, description: &str, source: &str) -> Self {
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
description: description.to_string(),
|
||||
source: source.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Completion engine for the TUI
|
||||
pub struct CompletionEngine {
|
||||
/// Available commands
|
||||
commands: Vec<CommandInfo>,
|
||||
}
|
||||
|
||||
impl Default for CompletionEngine {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl CompletionEngine {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
commands: Self::builtin_commands(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get built-in commands
|
||||
fn builtin_commands() -> Vec<CommandInfo> {
|
||||
vec![
|
||||
CommandInfo::new("help", "Show available commands and help", "builtin"),
|
||||
CommandInfo::new("clear", "Clear the screen", "builtin"),
|
||||
CommandInfo::new("mcp", "List MCP servers and their tools", "builtin"),
|
||||
CommandInfo::new("hooks", "Show loaded hooks", "builtin"),
|
||||
CommandInfo::new("compact", "Compact conversation context", "builtin"),
|
||||
CommandInfo::new("mode", "Switch permission mode (plan/edit/code)", "builtin"),
|
||||
CommandInfo::new("provider", "Switch LLM provider", "builtin"),
|
||||
CommandInfo::new("model", "Switch LLM model", "builtin"),
|
||||
CommandInfo::new("checkpoint", "Create a checkpoint", "builtin"),
|
||||
CommandInfo::new("rewind", "Rewind to a checkpoint", "builtin"),
|
||||
]
|
||||
}
|
||||
|
||||
/// Add commands from plugins
|
||||
pub fn add_plugin_commands(&mut self, plugin_name: &str, commands: Vec<CommandInfo>) {
|
||||
for mut cmd in commands {
|
||||
cmd.source = format!("plugin:{}", plugin_name);
|
||||
self.commands.push(cmd);
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a single command
|
||||
pub fn add_command(&mut self, command: CommandInfo) {
|
||||
self.commands.push(command);
|
||||
}
|
||||
|
||||
/// Get completions for the given input
|
||||
pub fn complete(&self, input: &str) -> Vec<Completion> {
|
||||
if input.starts_with('/') {
|
||||
self.complete_command(&input[1..])
|
||||
} else if input.starts_with('@') {
|
||||
self.complete_file_path(&input[1..])
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
/// Complete a slash command
|
||||
fn complete_command(&self, partial: &str) -> Vec<Completion> {
|
||||
let partial_lower = partial.to_lowercase();
|
||||
|
||||
self.commands
|
||||
.iter()
|
||||
.filter(|cmd| {
|
||||
// Match if name starts with partial, or contains partial (fuzzy)
|
||||
cmd.name.to_lowercase().starts_with(&partial_lower)
|
||||
|| (partial.len() >= 2 && cmd.name.to_lowercase().contains(&partial_lower))
|
||||
})
|
||||
.map(|cmd| Completion {
|
||||
text: format!("/{}", cmd.name),
|
||||
description: cmd.description.clone(),
|
||||
source: cmd.source.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Complete a file path
|
||||
fn complete_file_path(&self, partial: &str) -> Vec<Completion> {
|
||||
let path = Path::new(partial);
|
||||
|
||||
// Get the directory to search and the prefix to match
|
||||
let (dir, prefix) = if partial.ends_with('/') || partial.is_empty() {
|
||||
(partial, "")
|
||||
} else {
|
||||
let parent = path.parent().map(|p| p.to_str().unwrap_or("")).unwrap_or("");
|
||||
let file_name = path.file_name().and_then(|f| f.to_str()).unwrap_or("");
|
||||
(parent, file_name)
|
||||
};
|
||||
|
||||
// Search directory
|
||||
let search_dir = if dir.is_empty() { "." } else { dir };
|
||||
|
||||
match std::fs::read_dir(search_dir) {
|
||||
Ok(entries) => {
|
||||
entries
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter(|entry| {
|
||||
let name = entry.file_name();
|
||||
let name_str = name.to_string_lossy();
|
||||
// Skip hidden files unless user started typing with .
|
||||
if !prefix.starts_with('.') && name_str.starts_with('.') {
|
||||
return false;
|
||||
}
|
||||
name_str.to_lowercase().starts_with(&prefix.to_lowercase())
|
||||
})
|
||||
.map(|entry| {
|
||||
let name = entry.file_name();
|
||||
let name_str = name.to_string_lossy();
|
||||
let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
|
||||
|
||||
let full_path = if dir.is_empty() {
|
||||
name_str.to_string()
|
||||
} else if dir.ends_with('/') {
|
||||
format!("{}{}", dir, name_str)
|
||||
} else {
|
||||
format!("{}/{}", dir, name_str)
|
||||
};
|
||||
|
||||
Completion {
|
||||
text: format!("@{}{}", full_path, if is_dir { "/" } else { "" }),
|
||||
description: if is_dir { "Directory".to_string() } else { "File".to_string() },
|
||||
source: "filesystem".to_string(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Err(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all commands (for /help display)
|
||||
pub fn all_commands(&self) -> &[CommandInfo] {
|
||||
&self.commands
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_command_completion_exact() {
|
||||
let engine = CompletionEngine::new();
|
||||
let completions = engine.complete("/help");
|
||||
assert!(!completions.is_empty());
|
||||
assert!(completions.iter().any(|c| c.text == "/help"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_command_completion_partial() {
|
||||
let engine = CompletionEngine::new();
|
||||
let completions = engine.complete("/hel");
|
||||
assert!(!completions.is_empty());
|
||||
assert!(completions.iter().any(|c| c.text == "/help"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_command_completion_fuzzy() {
|
||||
let engine = CompletionEngine::new();
|
||||
// "cle" should match "clear"
|
||||
let completions = engine.complete("/cle");
|
||||
assert!(!completions.is_empty());
|
||||
assert!(completions.iter().any(|c| c.text == "/clear"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_command_info() {
|
||||
let info = CommandInfo::new("test", "A test command", "builtin");
|
||||
assert_eq!(info.name, "test");
|
||||
assert_eq!(info.description, "A test command");
|
||||
assert_eq!(info.source, "builtin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_add_plugin_commands() {
|
||||
let mut engine = CompletionEngine::new();
|
||||
let plugin_cmds = vec![
|
||||
CommandInfo::new("custom", "A custom command", ""),
|
||||
];
|
||||
engine.add_plugin_commands("my-plugin", plugin_cmds);
|
||||
|
||||
let completions = engine.complete("/custom");
|
||||
assert!(!completions.is_empty());
|
||||
assert!(completions.iter().any(|c| c.source == "plugin:my-plugin"));
|
||||
}
|
||||
}
|
||||
377
crates/app/ui/src/components/autocomplete.rs
Normal file
377
crates/app/ui/src/components/autocomplete.rs
Normal file
@@ -0,0 +1,377 @@
|
||||
//! Command autocomplete dropdown component
|
||||
//!
|
||||
//! Displays inline autocomplete suggestions when user types `/`.
|
||||
//! Supports fuzzy filtering as user types.
|
||||
|
||||
use crate::theme::Theme;
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::Style,
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Clear, Paragraph},
|
||||
Frame,
|
||||
};
|
||||
|
||||
/// An autocomplete option
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AutocompleteOption {
|
||||
/// The trigger text (command name without /)
|
||||
pub trigger: String,
|
||||
/// Display text (e.g., "/model [name]")
|
||||
pub display: String,
|
||||
/// Short description
|
||||
pub description: String,
|
||||
/// Has submenu/subcommands
|
||||
pub has_submenu: bool,
|
||||
}
|
||||
|
||||
impl AutocompleteOption {
|
||||
pub fn new(trigger: &str, description: &str) -> Self {
|
||||
Self {
|
||||
trigger: trigger.to_string(),
|
||||
display: format!("/{}", trigger),
|
||||
description: description.to_string(),
|
||||
has_submenu: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_args(trigger: &str, args: &str, description: &str) -> Self {
|
||||
Self {
|
||||
trigger: trigger.to_string(),
|
||||
display: format!("/{} {}", trigger, args),
|
||||
description: description.to_string(),
|
||||
has_submenu: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_submenu(trigger: &str, description: &str) -> Self {
|
||||
Self {
|
||||
trigger: trigger.to_string(),
|
||||
display: format!("/{}", trigger),
|
||||
description: description.to_string(),
|
||||
has_submenu: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Default command options
|
||||
fn default_options() -> Vec<AutocompleteOption> {
|
||||
vec![
|
||||
AutocompleteOption::new("help", "Show help"),
|
||||
AutocompleteOption::new("status", "Session info"),
|
||||
AutocompleteOption::with_args("model", "[name]", "Switch model"),
|
||||
AutocompleteOption::with_args("provider", "[name]", "Switch provider"),
|
||||
AutocompleteOption::new("history", "View history"),
|
||||
AutocompleteOption::new("checkpoint", "Save state"),
|
||||
AutocompleteOption::new("checkpoints", "List checkpoints"),
|
||||
AutocompleteOption::with_args("rewind", "[id]", "Restore"),
|
||||
AutocompleteOption::new("cost", "Token usage"),
|
||||
AutocompleteOption::new("clear", "Clear chat"),
|
||||
AutocompleteOption::new("compact", "Compact context"),
|
||||
AutocompleteOption::new("permissions", "Permission mode"),
|
||||
AutocompleteOption::new("themes", "List themes"),
|
||||
AutocompleteOption::with_args("theme", "[name]", "Switch theme"),
|
||||
AutocompleteOption::new("exit", "Exit"),
|
||||
]
|
||||
}
|
||||
|
||||
/// Autocomplete dropdown component
|
||||
pub struct Autocomplete {
|
||||
options: Vec<AutocompleteOption>,
|
||||
filtered: Vec<usize>, // indices into options
|
||||
selected: usize,
|
||||
visible: bool,
|
||||
theme: Theme,
|
||||
}
|
||||
|
||||
impl Autocomplete {
|
||||
pub fn new(theme: Theme) -> Self {
|
||||
let options = default_options();
|
||||
let filtered: Vec<usize> = (0..options.len()).collect();
|
||||
|
||||
Self {
|
||||
options,
|
||||
filtered,
|
||||
selected: 0,
|
||||
visible: false,
|
||||
theme,
|
||||
}
|
||||
}
|
||||
|
||||
/// Show autocomplete and reset filter
|
||||
pub fn show(&mut self) {
|
||||
self.visible = true;
|
||||
self.filtered = (0..self.options.len()).collect();
|
||||
self.selected = 0;
|
||||
}
|
||||
|
||||
/// Hide autocomplete
|
||||
pub fn hide(&mut self) {
|
||||
self.visible = false;
|
||||
}
|
||||
|
||||
/// Check if visible
|
||||
pub fn is_visible(&self) -> bool {
|
||||
self.visible
|
||||
}
|
||||
|
||||
/// Update filter based on current input (text after /)
|
||||
pub fn update_filter(&mut self, query: &str) {
|
||||
if query.is_empty() {
|
||||
self.filtered = (0..self.options.len()).collect();
|
||||
} else {
|
||||
let query_lower = query.to_lowercase();
|
||||
self.filtered = self.options
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, opt)| {
|
||||
// Fuzzy match: check if query chars appear in order
|
||||
fuzzy_match(&opt.trigger.to_lowercase(), &query_lower)
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
}
|
||||
|
||||
// Reset selection if it's out of bounds
|
||||
if self.selected >= self.filtered.len() {
|
||||
self.selected = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Select next option
|
||||
pub fn select_next(&mut self) {
|
||||
if !self.filtered.is_empty() {
|
||||
self.selected = (self.selected + 1) % self.filtered.len();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select previous option
|
||||
pub fn select_prev(&mut self) {
|
||||
if !self.filtered.is_empty() {
|
||||
self.selected = if self.selected == 0 {
|
||||
self.filtered.len() - 1
|
||||
} else {
|
||||
self.selected - 1
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the currently selected option's trigger
|
||||
pub fn confirm(&self) -> Option<String> {
|
||||
if self.filtered.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let idx = self.filtered[self.selected];
|
||||
Some(format!("/{}", self.options[idx].trigger))
|
||||
}
|
||||
|
||||
/// Handle key input, returns Some(command) if confirmed
|
||||
///
|
||||
/// Key behavior:
|
||||
/// - Tab: Confirm selection and insert into input
|
||||
/// - Down/Up: Navigate options
|
||||
/// - Enter: Pass through to submit (NotHandled)
|
||||
/// - Esc: Cancel autocomplete
|
||||
pub fn handle_key(&mut self, key: KeyEvent) -> AutocompleteResult {
|
||||
if !self.visible {
|
||||
return AutocompleteResult::NotHandled;
|
||||
}
|
||||
|
||||
match key.code {
|
||||
KeyCode::Tab => {
|
||||
// Tab confirms and inserts the selected command
|
||||
if let Some(cmd) = self.confirm() {
|
||||
self.hide();
|
||||
AutocompleteResult::Confirmed(cmd)
|
||||
} else {
|
||||
AutocompleteResult::Handled
|
||||
}
|
||||
}
|
||||
KeyCode::Down => {
|
||||
self.select_next();
|
||||
AutocompleteResult::Handled
|
||||
}
|
||||
KeyCode::BackTab | KeyCode::Up => {
|
||||
self.select_prev();
|
||||
AutocompleteResult::Handled
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
// Enter should submit the message, not confirm autocomplete
|
||||
// Hide autocomplete and let Enter pass through
|
||||
self.hide();
|
||||
AutocompleteResult::NotHandled
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
self.hide();
|
||||
AutocompleteResult::Cancelled
|
||||
}
|
||||
_ => AutocompleteResult::NotHandled,
|
||||
}
|
||||
}
|
||||
|
||||
/// Update theme
|
||||
pub fn set_theme(&mut self, theme: Theme) {
|
||||
self.theme = theme;
|
||||
}
|
||||
|
||||
/// Add custom options (from plugins)
|
||||
pub fn add_options(&mut self, options: Vec<AutocompleteOption>) {
|
||||
self.options.extend(options);
|
||||
// Re-filter with all options
|
||||
self.filtered = (0..self.options.len()).collect();
|
||||
}
|
||||
|
||||
/// Render the autocomplete dropdown above the input line
|
||||
pub fn render(&self, frame: &mut Frame, input_area: Rect) {
|
||||
if !self.visible || self.filtered.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Calculate dropdown dimensions
|
||||
let max_visible = 8.min(self.filtered.len());
|
||||
let width = 40.min(input_area.width.saturating_sub(4));
|
||||
let height = (max_visible + 2) as u16; // +2 for borders
|
||||
|
||||
// Position above input, left-aligned with some padding
|
||||
let x = input_area.x + 2;
|
||||
let y = input_area.y.saturating_sub(height);
|
||||
|
||||
let dropdown_area = Rect::new(x, y, width, height);
|
||||
|
||||
// Clear area behind dropdown
|
||||
frame.render_widget(Clear, dropdown_area);
|
||||
|
||||
// Build option lines
|
||||
let mut lines: Vec<Line> = Vec::new();
|
||||
|
||||
for (display_idx, &opt_idx) in self.filtered.iter().take(max_visible).enumerate() {
|
||||
let opt = &self.options[opt_idx];
|
||||
let is_selected = display_idx == self.selected;
|
||||
|
||||
let style = if is_selected {
|
||||
self.theme.selected
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
|
||||
let mut spans = vec![
|
||||
Span::styled(" ", style),
|
||||
Span::styled("/", if is_selected { style } else { self.theme.cmd_slash }),
|
||||
Span::styled(&opt.trigger, if is_selected { style } else { self.theme.cmd_name }),
|
||||
];
|
||||
|
||||
// Submenu indicator
|
||||
if opt.has_submenu {
|
||||
spans.push(Span::styled(" >", if is_selected { style } else { self.theme.cmd_desc }));
|
||||
}
|
||||
|
||||
// Pad to fixed width for consistent selection highlighting
|
||||
let current_len: usize = spans.iter().map(|s| s.content.len()).sum();
|
||||
let padding = (width as usize).saturating_sub(current_len + 1);
|
||||
spans.push(Span::styled(" ".repeat(padding), style));
|
||||
|
||||
lines.push(Line::from(spans));
|
||||
}
|
||||
|
||||
// Show overflow indicator if needed
|
||||
if self.filtered.len() > max_visible {
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" ... +{} more", self.filtered.len() - max_visible),
|
||||
self.theme.cmd_desc,
|
||||
)));
|
||||
}
|
||||
|
||||
let block = Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(self.theme.palette.border))
|
||||
.style(self.theme.overlay_bg);
|
||||
|
||||
let paragraph = Paragraph::new(lines).block(block);
|
||||
|
||||
frame.render_widget(paragraph, dropdown_area);
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of handling autocomplete key
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AutocompleteResult {
|
||||
/// Key was not handled by autocomplete
|
||||
NotHandled,
|
||||
/// Key was handled, no action needed
|
||||
Handled,
|
||||
/// User confirmed selection, returns command string
|
||||
Confirmed(String),
|
||||
/// User cancelled autocomplete
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// Simple fuzzy match: check if query chars appear in order in text
|
||||
fn fuzzy_match(text: &str, query: &str) -> bool {
|
||||
let mut text_chars = text.chars().peekable();
|
||||
|
||||
for query_char in query.chars() {
|
||||
loop {
|
||||
match text_chars.next() {
|
||||
Some(c) if c == query_char => break,
|
||||
Some(_) => continue,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_fuzzy_match() {
|
||||
assert!(fuzzy_match("help", "h"));
|
||||
assert!(fuzzy_match("help", "he"));
|
||||
assert!(fuzzy_match("help", "hel"));
|
||||
assert!(fuzzy_match("help", "help"));
|
||||
assert!(fuzzy_match("help", "hp")); // fuzzy: h...p
|
||||
assert!(!fuzzy_match("help", "x"));
|
||||
assert!(!fuzzy_match("help", "helping")); // query longer than text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_autocomplete_filter() {
|
||||
let theme = Theme::default();
|
||||
let mut ac = Autocomplete::new(theme);
|
||||
|
||||
ac.update_filter("he");
|
||||
assert!(ac.filtered.len() < ac.options.len());
|
||||
|
||||
// Should match "help"
|
||||
assert!(ac.filtered.iter().any(|&i| ac.options[i].trigger == "help"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_autocomplete_navigation() {
|
||||
let theme = Theme::default();
|
||||
let mut ac = Autocomplete::new(theme);
|
||||
ac.show();
|
||||
|
||||
assert_eq!(ac.selected, 0);
|
||||
ac.select_next();
|
||||
assert_eq!(ac.selected, 1);
|
||||
ac.select_prev();
|
||||
assert_eq!(ac.selected, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_autocomplete_confirm() {
|
||||
let theme = Theme::default();
|
||||
let mut ac = Autocomplete::new(theme);
|
||||
ac.show();
|
||||
|
||||
let cmd = ac.confirm();
|
||||
assert!(cmd.is_some());
|
||||
assert!(cmd.unwrap().starts_with("/"));
|
||||
}
|
||||
}
|
||||
488
crates/app/ui/src/components/chat_panel.rs
Normal file
488
crates/app/ui/src/components/chat_panel.rs
Normal file
@@ -0,0 +1,488 @@
|
||||
//! Borderless chat panel component
|
||||
//!
|
||||
//! Displays chat messages with proper indentation, timestamps,
|
||||
//! and streaming indicators. Uses whitespace instead of borders.
|
||||
|
||||
use crate::theme::Theme;
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span, Text},
|
||||
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
||||
Frame,
|
||||
};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// Chat message types
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ChatMessage {
|
||||
User(String),
|
||||
Assistant(String),
|
||||
ToolCall { name: String, args: String },
|
||||
ToolResult { success: bool, output: String },
|
||||
System(String),
|
||||
}
|
||||
|
||||
impl ChatMessage {
|
||||
/// Get a timestamp for when the message was created (for display)
|
||||
pub fn timestamp_display() -> String {
|
||||
let now = SystemTime::now();
|
||||
let secs = now
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
let hours = (secs / 3600) % 24;
|
||||
let mins = (secs / 60) % 60;
|
||||
format!("{:02}:{:02}", hours, mins)
|
||||
}
|
||||
}
|
||||
|
||||
/// Message with metadata for display
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DisplayMessage {
|
||||
pub message: ChatMessage,
|
||||
pub timestamp: String,
|
||||
pub focused: bool,
|
||||
}
|
||||
|
||||
impl DisplayMessage {
|
||||
pub fn new(message: ChatMessage) -> Self {
|
||||
Self {
|
||||
message,
|
||||
timestamp: ChatMessage::timestamp_display(),
|
||||
focused: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Borderless chat panel
|
||||
pub struct ChatPanel {
|
||||
messages: Vec<DisplayMessage>,
|
||||
scroll_offset: usize,
|
||||
auto_scroll: bool,
|
||||
total_lines: usize,
|
||||
focused_index: Option<usize>,
|
||||
is_streaming: bool,
|
||||
theme: Theme,
|
||||
}
|
||||
|
||||
impl ChatPanel {
|
||||
/// Create new borderless chat panel
|
||||
pub fn new(theme: Theme) -> Self {
|
||||
Self {
|
||||
messages: Vec::new(),
|
||||
scroll_offset: 0,
|
||||
auto_scroll: true,
|
||||
total_lines: 0,
|
||||
focused_index: None,
|
||||
is_streaming: false,
|
||||
theme,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a new message
|
||||
pub fn add_message(&mut self, message: ChatMessage) {
|
||||
self.messages.push(DisplayMessage::new(message));
|
||||
self.auto_scroll = true;
|
||||
self.is_streaming = false;
|
||||
}
|
||||
|
||||
/// Append content to the last assistant message, or create a new one
|
||||
pub fn append_to_assistant(&mut self, content: &str) {
|
||||
if let Some(DisplayMessage {
|
||||
message: ChatMessage::Assistant(last_content),
|
||||
..
|
||||
}) = self.messages.last_mut()
|
||||
{
|
||||
last_content.push_str(content);
|
||||
} else {
|
||||
self.messages.push(DisplayMessage::new(ChatMessage::Assistant(
|
||||
content.to_string(),
|
||||
)));
|
||||
}
|
||||
self.auto_scroll = true;
|
||||
self.is_streaming = true;
|
||||
}
|
||||
|
||||
/// Set streaming state
|
||||
pub fn set_streaming(&mut self, streaming: bool) {
|
||||
self.is_streaming = streaming;
|
||||
}
|
||||
|
||||
/// Scroll up
|
||||
pub fn scroll_up(&mut self, amount: usize) {
|
||||
self.scroll_offset = self.scroll_offset.saturating_sub(amount);
|
||||
self.auto_scroll = false;
|
||||
}
|
||||
|
||||
/// Scroll down
|
||||
pub fn scroll_down(&mut self, amount: usize) {
|
||||
self.scroll_offset = self.scroll_offset.saturating_add(amount);
|
||||
let near_bottom_threshold = 5;
|
||||
if self.total_lines > 0 {
|
||||
let max_scroll = self.total_lines.saturating_sub(1);
|
||||
if self.scroll_offset.saturating_add(near_bottom_threshold) >= max_scroll {
|
||||
self.auto_scroll = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Scroll to bottom
|
||||
pub fn scroll_to_bottom(&mut self) {
|
||||
self.scroll_offset = self.total_lines.saturating_sub(1);
|
||||
self.auto_scroll = true;
|
||||
}
|
||||
|
||||
/// Scroll to top
|
||||
pub fn scroll_to_top(&mut self) {
|
||||
self.scroll_offset = 0;
|
||||
self.auto_scroll = false;
|
||||
}
|
||||
|
||||
/// Page up
|
||||
pub fn page_up(&mut self, page_size: usize) {
|
||||
self.scroll_up(page_size.saturating_sub(2));
|
||||
}
|
||||
|
||||
/// Page down
|
||||
pub fn page_down(&mut self, page_size: usize) {
|
||||
self.scroll_down(page_size.saturating_sub(2));
|
||||
}
|
||||
|
||||
/// Focus next message
|
||||
pub fn focus_next(&mut self) {
|
||||
if self.messages.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.focused_index = Some(match self.focused_index {
|
||||
Some(i) if i + 1 < self.messages.len() => i + 1,
|
||||
Some(_) => 0,
|
||||
None => 0,
|
||||
});
|
||||
}
|
||||
|
||||
/// Focus previous message
|
||||
pub fn focus_previous(&mut self) {
|
||||
if self.messages.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.focused_index = Some(match self.focused_index {
|
||||
Some(0) => self.messages.len() - 1,
|
||||
Some(i) => i - 1,
|
||||
None => self.messages.len() - 1,
|
||||
});
|
||||
}
|
||||
|
||||
/// Clear focus
|
||||
pub fn clear_focus(&mut self) {
|
||||
self.focused_index = None;
|
||||
}
|
||||
|
||||
/// Get focused message index
|
||||
pub fn focused_index(&self) -> Option<usize> {
|
||||
self.focused_index
|
||||
}
|
||||
|
||||
/// Get focused message
|
||||
pub fn focused_message(&self) -> Option<&ChatMessage> {
|
||||
self.focused_index
|
||||
.and_then(|i| self.messages.get(i))
|
||||
.map(|m| &m.message)
|
||||
}
|
||||
|
||||
/// Update scroll position before rendering
|
||||
pub fn update_scroll(&mut self, area: Rect) {
|
||||
self.total_lines = self.count_total_lines(area);
|
||||
|
||||
if self.auto_scroll {
|
||||
let visible_height = area.height as usize;
|
||||
let max_scroll = self.total_lines.saturating_sub(visible_height);
|
||||
self.scroll_offset = max_scroll;
|
||||
} else {
|
||||
let visible_height = area.height as usize;
|
||||
let max_scroll = self.total_lines.saturating_sub(visible_height);
|
||||
self.scroll_offset = self.scroll_offset.min(max_scroll);
|
||||
}
|
||||
}
|
||||
|
||||
/// Count total lines for scroll calculation
|
||||
/// Must match exactly what render() produces:
|
||||
/// - User: 1 (role line) + N (content) + 1 (empty) = N + 2
|
||||
/// - Assistant: 1 (role line) + N (content) + 1 (empty) = N + 2
|
||||
/// - ToolCall: 1 (call line) + 1 (empty) = 2
|
||||
/// - ToolResult: 1 (result line) + 1 (empty) = 2
|
||||
/// - System: N (content lines) + 1 (empty) = N + 1
|
||||
fn count_total_lines(&self, area: Rect) -> usize {
|
||||
let mut line_count = 0;
|
||||
let wrap_width = area.width.saturating_sub(4) as usize;
|
||||
|
||||
for msg in &self.messages {
|
||||
line_count += match &msg.message {
|
||||
ChatMessage::User(content) => {
|
||||
let wrapped = textwrap::wrap(content, wrap_width);
|
||||
// 1 role line + N content lines + 1 empty line
|
||||
1 + wrapped.len() + 1
|
||||
}
|
||||
ChatMessage::Assistant(content) => {
|
||||
let wrapped = textwrap::wrap(content, wrap_width);
|
||||
// 1 role line + N content lines + 1 empty line
|
||||
1 + wrapped.len() + 1
|
||||
}
|
||||
ChatMessage::ToolCall { .. } => 2,
|
||||
ChatMessage::ToolResult { .. } => 2,
|
||||
ChatMessage::System(content) => {
|
||||
// N content lines + 1 empty line (no role line for system)
|
||||
content.lines().count() + 1
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
line_count
|
||||
}
|
||||
|
||||
/// Render the borderless chat panel
|
||||
///
|
||||
/// Message display format (no symbols, clean typography):
|
||||
/// - Role: bold, appropriate color
|
||||
/// - Timestamp: dim, same line as role
|
||||
/// - Content: 2-space indent, normal weight
|
||||
/// - Blank line between messages
|
||||
pub fn render(&self, frame: &mut Frame, area: Rect) {
|
||||
let mut text_lines = Vec::new();
|
||||
let wrap_width = area.width.saturating_sub(4) as usize;
|
||||
|
||||
for (idx, display_msg) in self.messages.iter().enumerate() {
|
||||
let is_focused = self.focused_index == Some(idx);
|
||||
let is_last = idx == self.messages.len() - 1;
|
||||
|
||||
match &display_msg.message {
|
||||
ChatMessage::User(content) => {
|
||||
// Role line: "You" bold + timestamp dim
|
||||
text_lines.push(Line::from(vec![
|
||||
Span::styled(" ", Style::default()),
|
||||
Span::styled("You", self.theme.user_message),
|
||||
Span::styled(
|
||||
format!(" {}", display_msg.timestamp),
|
||||
self.theme.timestamp,
|
||||
),
|
||||
]));
|
||||
|
||||
// Message content with 2-space indent
|
||||
let wrapped = textwrap::wrap(content, wrap_width);
|
||||
for line in wrapped {
|
||||
let style = if is_focused {
|
||||
self.theme.user_message.add_modifier(Modifier::REVERSED)
|
||||
} else {
|
||||
self.theme.user_message.remove_modifier(Modifier::BOLD)
|
||||
};
|
||||
text_lines.push(Line::from(Span::styled(
|
||||
format!(" {}", line),
|
||||
style,
|
||||
)));
|
||||
}
|
||||
|
||||
// Focus hints
|
||||
if is_focused {
|
||||
text_lines.push(Line::from(Span::styled(
|
||||
" [y]copy [e]edit [r]retry",
|
||||
self.theme.status_dim,
|
||||
)));
|
||||
}
|
||||
|
||||
text_lines.push(Line::from(""));
|
||||
}
|
||||
|
||||
ChatMessage::Assistant(content) => {
|
||||
// Role line: streaming indicator (if active) + "Assistant" bold + timestamp
|
||||
let mut role_spans = vec![Span::styled(" ", Style::default())];
|
||||
|
||||
// Streaming indicator (subtle, no symbol)
|
||||
if is_last && self.is_streaming {
|
||||
role_spans.push(Span::styled(
|
||||
"... ",
|
||||
Style::default().fg(self.theme.palette.success),
|
||||
));
|
||||
}
|
||||
|
||||
role_spans.push(Span::styled(
|
||||
"Assistant",
|
||||
self.theme.assistant_message.add_modifier(Modifier::BOLD),
|
||||
));
|
||||
|
||||
role_spans.push(Span::styled(
|
||||
format!(" {}", display_msg.timestamp),
|
||||
self.theme.timestamp,
|
||||
));
|
||||
|
||||
text_lines.push(Line::from(role_spans));
|
||||
|
||||
// Content
|
||||
let wrapped = textwrap::wrap(content, wrap_width);
|
||||
for line in wrapped {
|
||||
let style = if is_focused {
|
||||
self.theme.assistant_message.add_modifier(Modifier::REVERSED)
|
||||
} else {
|
||||
self.theme.assistant_message
|
||||
};
|
||||
text_lines.push(Line::from(Span::styled(
|
||||
format!(" {}", line),
|
||||
style,
|
||||
)));
|
||||
}
|
||||
|
||||
// Focus hints
|
||||
if is_focused {
|
||||
text_lines.push(Line::from(Span::styled(
|
||||
" [y]copy [r]retry",
|
||||
self.theme.status_dim,
|
||||
)));
|
||||
}
|
||||
|
||||
text_lines.push(Line::from(""));
|
||||
}
|
||||
|
||||
ChatMessage::ToolCall { name, args } => {
|
||||
// Tool calls: name in tool color, args dimmed
|
||||
text_lines.push(Line::from(vec![
|
||||
Span::styled(" ", Style::default()),
|
||||
Span::styled(format!("{} ", name), self.theme.tool_call),
|
||||
Span::styled(
|
||||
truncate_str(args, 60),
|
||||
self.theme.tool_call.add_modifier(Modifier::DIM),
|
||||
),
|
||||
]));
|
||||
text_lines.push(Line::from(""));
|
||||
}
|
||||
|
||||
ChatMessage::ToolResult { success, output } => {
|
||||
// Tool results: status prefix + output
|
||||
let (prefix, style) = if *success {
|
||||
("ok ", self.theme.tool_result_success)
|
||||
} else {
|
||||
("err ", self.theme.tool_result_error)
|
||||
};
|
||||
|
||||
text_lines.push(Line::from(vec![
|
||||
Span::styled(" ", Style::default()),
|
||||
Span::styled(prefix, style),
|
||||
Span::styled(
|
||||
truncate_str(output, 100),
|
||||
style.remove_modifier(Modifier::BOLD),
|
||||
),
|
||||
]));
|
||||
text_lines. | ||||