diff --git a/.cargo/config.toml b/.cargo/config.toml index 9f19e62fc..3ae350905 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -5,9 +5,3 @@ [build] target-dir = "target" incremental = true - -# tree-sitter (via pulsing-forge) needs BSD endian macros when built against -# glibc 2.17 (manylinux2014). Its build.rs sets _DEFAULT_SOURCE, which glibc -# 2.17 ignores, leaving le16toh/be16toh undefined at link/load time. -[env] -CFLAGS = { value = "-D_GNU_SOURCE", condition = { platform = "linux" } } diff --git a/.github/actions/setup-build-env/action.yml b/.github/actions/setup-build-env/action.yml index 89b12e722..709e8535e 100644 --- a/.github/actions/setup-build-env/action.yml +++ b/.github/actions/setup-build-env/action.yml @@ -50,23 +50,12 @@ runs: ${{ runner.os }}-cargo-${{ inputs.rust-toolchain }}- ${{ runner.os }}-cargo- - uses: cargo-bins/cargo-binstall@main - - name: Install Linux GUI build dependencies + - name: Install Linux native build dependencies if: runner.os == 'Linux' shell: bash run: | sudo apt-get update -qq sudo apt-get install -y -qq --no-install-recommends \ - libxcb1-dev \ - libxkbcommon-dev \ - libxkbcommon-x11-dev \ - libx11-dev \ - libxi-dev \ - libxrandr-dev \ - libxcursor-dev \ - libxinerama-dev \ - libgl1-mesa-dev \ - libfontconfig1-dev \ - libfreetype6-dev \ libffi-dev \ pkg-config diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb6106961..98fcff2d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,10 @@ env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + jobs: # ============================================ # 代码规范检查(快速反馈) @@ -32,7 +36,7 @@ jobs: run: cargo fmt --all -- --check - name: Rust clippy - run: cargo clippy --workspace --exclude pulsing-py --exclude pulsing-bench-py --all-targets -- -D warnings + run: cargo clippy --locked --workspace --exclude pulsing-py --all-targets -- -D warnings - name: Python lint (ruff) run: ruff check python/ @@ -61,10 +65,10 @@ jobs: uses: Swatinem/rust-cache@v2 - name: Build - run: cargo build --workspace --exclude pulsing-py --exclude pulsing-bench-py --all-targets + run: cargo build --locked --workspace --exclude pulsing-py --all-targets - name: Test - run: cargo test --workspace --exclude pulsing-py --exclude pulsing-bench-py --all-targets + run: cargo test --locked --workspace --exclude pulsing-py --all-targets # ============================================ # Rust 覆盖率收集 @@ -91,7 +95,7 @@ jobs: export CARGO_TARGET_DIR=$CARGO_LLVM_COV_TARGET_DIR export CARGO_INCREMENTAL=1 cargo llvm-cov clean --workspace - cargo test --workspace --exclude pulsing-py --exclude pulsing-bench-py + cargo test --locked --workspace --exclude pulsing-py cargo llvm-cov --no-run --lcov --output-path coverage.lcov - name: Upload coverage report @@ -176,23 +180,15 @@ jobs: dist/pulsing-*.tar.gz # ============================================ - # 构建 Linux aarch64 Wheel(使用 QEMU 仿真原生构建) + # 构建 Linux aarch64 Wheel(原生 ARM64 runner) # ============================================ build-linux-aarch64: name: Build (Linux aarch64 wheel + binary) - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - uses: actions/checkout@v4 - - name: Set up QEMU - uses: docker/setup-qemu-action@v3 - with: - platforms: arm64 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - - - name: Build wheel + binary in QEMU + - name: Build wheel + binary on ARM64 run: | docker run --rm --platform linux/arm64 \ -v ${{ github.workspace }}:/workspace -w /workspace \ @@ -292,12 +288,12 @@ jobs: run: pytest tests/python -v # ============================================ - # Ubuntu aarch64 Python 测试(使用 QEMU 仿真) + # Ubuntu aarch64 Python 测试(原生 ARM64 runner) # ============================================ test-ubuntu-aarch64: name: Test Ubuntu aarch64 (Python ${{ matrix.python-version }}) needs: build-linux-aarch64 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm strategy: fail-fast: false matrix: @@ -306,18 +302,13 @@ jobs: steps: - uses: actions/checkout@v4 - - name: Set up QEMU - uses: docker/setup-qemu-action@v3 - with: - platforms: arm64 - - name: Download wheel uses: actions/download-artifact@v4 with: name: wheels-linux-aarch64 path: dist/ - - name: Test on Ubuntu aarch64 (QEMU) + - name: Test on Ubuntu aarch64 run: | docker run --rm --platform linux/arm64 \ -v ${{ github.workspace }}:/workspace -w /workspace \ diff --git a/.github/workflows/pypi.yml b/.github/workflows/pypi.yml index 103f4b725..8c43a8246 100644 --- a/.github/workflows/pypi.yml +++ b/.github/workflows/pypi.yml @@ -47,23 +47,15 @@ jobs: dist/pulsing-*.tar.gz # ============================================ - # Build Linux aarch64 wheels (使用 QEMU 仿真原生构建) + # Build Linux aarch64 wheels (native ARM64 runner) # ============================================ linux-aarch64: name: Build Linux aarch64 wheels - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - uses: actions/checkout@v4 - - name: Set up QEMU - uses: docker/setup-qemu-action@v3 - with: - platforms: arm64 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - - - name: Build wheel + binary in QEMU + - name: Build wheel + binary on ARM64 run: | docker run --rm --platform linux/arm64 \ -v ${{ github.workspace }}:/workspace -w /workspace \ diff --git a/.gitignore b/.gitignore index a8e133b01..494cc3bc2 100644 --- a/.gitignore +++ b/.gitignore @@ -127,7 +127,7 @@ dist/pulsing-*.zip # npc workspace local state (per-project; run `npc init` in your app repo) .pulsing/ -# Vendored Codex reference tree (refresh: scripts/sync-codex-forge.sh) +# Local vendor trees vendor/ .cursor/ .claude/ diff --git a/Cargo.lock b/Cargo.lock index 41bec5c2e..c45e9034b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,28 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "ab_glyph" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" -dependencies = [ - "ab_glyph_rasterizer", - "owned_ttf_parser", -] - -[[package]] -name = "ab_glyph_rasterizer" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - [[package]] name = "adler32" version = "1.2.0" @@ -39,16 +17,15 @@ dependencies = [ "cfg-if", "getrandom 0.3.4", "once_cell", - "serde", "version_check", "zerocopy", ] [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] @@ -59,55 +36,15 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" -[[package]] -name = "android-activity" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" -dependencies = [ - "android-properties", - "bitflags 2.13.0", - "cc", - "jni", - "libc", - "log", - "ndk", - "ndk-context", - "ndk-sys 0.6.0+11769913", - "num_enum", - "thiserror 2.0.18", -] - -[[package]] -name = "android-properties" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" - [[package]] name = "android_system_properties" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" dependencies = [ "libc", ] -[[package]] -name = "anstream" -version = "0.6.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" -dependencies = [ - "anstyle", - "anstyle-parse 0.2.7", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - [[package]] name = "anstream" version = "1.0.0" @@ -115,7 +52,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" dependencies = [ "anstyle", - "anstyle-parse 1.0.0", + "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", @@ -129,15 +66,6 @@ version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" -[[package]] -name = "anstyle-parse" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" -dependencies = [ - "utf8parse", -] - [[package]] name = "anstyle-parse" version = "1.0.0" @@ -169,66 +97,25 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.100" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "ar_archive_writer" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4087686b4b0a3427190bae57a1d9a478dbb2d40c5dc1bd6e2b6d797913bdd348" +checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" dependencies = [ "object", ] -[[package]] -name = "arboard" -version = "3.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" -dependencies = [ - "clipboard-win", - "image", - "log", - "objc2 0.6.4", - "objc2-app-kit 0.3.2", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation 0.3.2", - "parking_lot", - "percent-encoding", - "windows-sys 0.60.2", - "x11rb", -] - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "as-raw-xcb-connection" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" - [[package]] name = "ascii" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" -[[package]] -name = "ash" -version = "0.38.0+1.3.281" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" -dependencies = [ - "libloading 0.8.9", -] - [[package]] name = "async-channel" version = "2.5.0" @@ -260,18 +147,18 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "async-trait" -version = "0.1.89" +version = "0.1.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -300,7 +187,7 @@ dependencies = [ "manyhow", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -316,20 +203,20 @@ dependencies = [ "proc-macro2", "quote", "quote-use", - "syn", + "syn 2.0.119", ] [[package]] name = "autocfg" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.15.2" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a88aab2464f1f25453baa7a07c84c5b7684e274054ba06817f382357f77a288" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "untrusted 0.7.1", @@ -338,14 +225,15 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.35.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b45afffdee1e7c9126814751f88dddc747f41d91da16c9551a0f1e8a11e788a1" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", "dunce", "fs_extra", + "pkg-config", ] [[package]] @@ -370,7 +258,7 @@ dependencies = [ "rustversion", "serde", "sync_wrapper", - "tower 0.5.2", + "tower 0.5.3", "tower-layer", "tower-service", ] @@ -397,15 +285,15 @@ dependencies = [ [[package]] name = "base64" -version = "0.13.1" +version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "base64" -version = "0.22.1" +version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] name = "better_io" @@ -422,21 +310,6 @@ dependencies = [ "serde", ] -[[package]] -name = "bit-set" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" - [[package]] name = "bitflags" version = "1.3.2" @@ -445,12 +318,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.13.0" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" -dependencies = [ - "serde_core", -] +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "bitflagset" @@ -473,12 +343,6 @@ dependencies = [ "digest", ] -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - [[package]] name = "block-buffer" version = "0.10.4" @@ -488,20 +352,11 @@ dependencies = [ "generic-array", ] -[[package]] -name = "block2" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" -dependencies = [ - "objc2 0.5.2", -] - [[package]] name = "bstr" -version = "1.12.3" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" dependencies = [ "memchr", "regex-automata", @@ -510,47 +365,21 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.19.0" +version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" [[package]] name = "bytemuck" -version = "1.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" -dependencies = [ - "bytemuck_derive", -] - -[[package]] -name = "bytemuck_derive" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "byteorder-lite" -version = "0.1.0" +version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" [[package]] name = "bytes" -version = "1.10.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "bzip2" @@ -561,45 +390,6 @@ dependencies = [ "libbz2-rs-sys", ] -[[package]] -name = "calloop" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" -dependencies = [ - "bitflags 2.13.0", - "log", - "polling", - "rustix 0.38.44", - "slab", - "thiserror 1.0.69", -] - -[[package]] -name = "calloop" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dbf9978365bac10f54d1d4b04f7ce4427e51f71d61f2fe15e3fed5166474df7" -dependencies = [ - "bitflags 2.13.0", - "polling", - "rustix 1.1.3", - "slab", - "tracing", -] - -[[package]] -name = "calloop-wayland-source" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" -dependencies = [ - "calloop 0.14.4", - "rustix 1.1.3", - "wayland-backend", - "wayland-client", -] - [[package]] name = "caseless" version = "0.2.2" @@ -620,9 +410,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.52" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd4932aefd12402b36c60956a4fe0035421f544799057659ff86f923657aada3" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" dependencies = [ "find-msvc-tools", "jobserver", @@ -632,39 +422,24 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "cfg_aliases" -version = "0.1.1" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - -[[package]] -name = "cgl" -version = "0.3.2" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" -dependencies = [ - "libc", -] +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cpufeatures 0.3.0", + "cpufeatures 0.3.1", "rand_core 0.10.1", ] @@ -675,18 +450,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", - "js-sys", "num-traits", - "serde", - "wasm-bindgen", - "windows-link 0.2.1", + "windows-link", ] [[package]] name = "clap" -version = "4.5.60" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", "clap_derive", @@ -694,11 +466,11 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.60" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ - "anstream 0.6.21", + "anstream", "anstyle", "clap_lex", "strsim", @@ -706,111 +478,63 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.55" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] name = "clap_lex" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] [[package]] name = "cmake" -version = "0.1.57" +version = "0.1.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" dependencies = [ "cc", ] -[[package]] -name = "codespan-reporting" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" -dependencies = [ - "termcolor", - "unicode-width 0.1.14", -] - [[package]] name = "collection_literals" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2550f75b8cfac212855f6b1885455df8eaee8fe8e246b647d69146142e016084" -[[package]] -name = "color_quant" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" - [[package]] name = "colorchoice" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" -[[package]] -name = "colored" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" -dependencies = [ - "lazy_static", - "windows-sys 0.59.0", -] - -[[package]] -name = "combine" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" -dependencies = [ - "bytes", - "memchr", -] - -[[package]] -name = "comfy-table" -version = "7.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47" -dependencies = [ - "crossterm 0.29.0", - "unicode-segmentation", - "unicode-width 0.2.2", -] - [[package]] name = "compact_str" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb1325a1cece981e8a296ab8f0f9b63ae357bd0784a9faaf548cc7b480707a" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" dependencies = [ "castaway", "cfg-if", "itoa", "rustversion", "ryu", - "serde", "static_assertions", ] @@ -823,19 +547,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "console" -version = "0.15.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" -dependencies = [ - "encode_unicode", - "libc", - "once_cell", - "unicode-width 0.2.2", - "windows-sys 0.59.0", -] - [[package]] name = "constant_time_eq" version = "0.4.2" @@ -852,46 +563,12 @@ dependencies = [ "libc", ] -[[package]] -name = "core-foundation" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "core-foundation-sys" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" -[[package]] -name = "core-graphics" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", - "core-graphics-types", - "foreign-types 0.5.0", - "libc", -] - -[[package]] -name = "core-graphics-types" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", - "libc", -] - [[package]] name = "cpufeatures" version = "0.2.17" @@ -903,110 +580,51 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ "libc", ] [[package]] name = "crc32fast" -version = "1.5.0" +version = "1.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" dependencies = [ "cfg-if", ] [[package]] name = "crossbeam-channel" -version = "0.5.15" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" dependencies = [ "crossbeam-utils", ] [[package]] -name = "crossbeam-deque" -version = "0.8.6" +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] -name = "crossbeam-epoch" -version = "0.9.18" +name = "crypto-common" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" - -[[package]] -name = "crossterm" -version = "0.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" -dependencies = [ - "bitflags 2.13.0", - "crossterm_winapi", - "mio", - "parking_lot", - "rustix 0.38.44", - "serde", - "signal-hook", - "signal-hook-mio", - "winapi", -] - -[[package]] -name = "crossterm" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" -dependencies = [ - "bitflags 2.13.0", - "crossterm_winapi", - "document-features", - "parking_lot", - "rustix 1.1.3", - "winapi", -] - -[[package]] -name = "crossterm_winapi" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" -dependencies = [ - "winapi", -] - -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", + "generic-array", + "typenum", ] [[package]] @@ -1018,95 +636,11 @@ dependencies = [ "memchr", ] -[[package]] -name = "cursor-icon" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" - -[[package]] -name = "darling" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" -dependencies = [ - "darling_core 0.20.11", - "darling_macro 0.20.11", -] - -[[package]] -name = "darling" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" -dependencies = [ - "darling_core 0.23.0", - "darling_macro 0.23.0", -] - -[[package]] -name = "darling_core" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn", -] - -[[package]] -name = "darling_core" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" -dependencies = [ - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn", -] - -[[package]] -name = "darling_macro" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" -dependencies = [ - "darling_core 0.20.11", - "quote", - "syn", -] - -[[package]] -name = "darling_macro" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" -dependencies = [ - "darling_core 0.23.0", - "quote", - "syn", -] - -[[package]] -name = "dary_heap" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06d2e3287df1c007e74221c49ca10a95d557349e54b3a75dc2fb14712c751f04" -dependencies = [ - "serde", -] - [[package]] name = "dashmap" -version = "6.1.0" +version = "6.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" dependencies = [ "cfg-if", "crossbeam-utils", @@ -1118,9 +652,9 @@ dependencies = [ [[package]] name = "defmt" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ "bitflags 1.3.2", "defmt-macros", @@ -1128,74 +662,40 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "deranged" -version = "0.5.5" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587" -dependencies = [ - "powerfmt", -] +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" [[package]] name = "derive-where" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d08b3a0bcc0d079199cd476b2cae8435016ec11d1c0986c6901c5ac223041534" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "derive_builder" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" -dependencies = [ - "derive_builder_macro", -] - -[[package]] -name = "derive_builder_core" -version = "0.20.2" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +checksum = "2e2b94854e8576378ccda7c8de8a66ed8b4e8acbd2c50ec3418ea6c8aaf4b567" dependencies = [ - "darling 0.20.11", "proc-macro2", "quote", - "syn", -] - -[[package]] -name = "derive_builder_macro" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" -dependencies = [ - "derive_builder_core", - "syn", + "syn 3.0.9", ] [[package]] @@ -1209,15 +709,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "dirs" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" -dependencies = [ - "dirs-sys", -] - [[package]] name = "dirs-next" version = "2.0.0" @@ -1228,18 +719,6 @@ dependencies = [ "dirs-sys-next", ] -[[package]] -name = "dirs-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" -dependencies = [ - "libc", - "option-ext", - "redox_users 0.5.2", - "windows-sys 0.61.2", -] - [[package]] name = "dirs-sys-next" version = "0.1.2" @@ -1247,44 +726,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" dependencies = [ "libc", - "redox_users 0.4.6", + "redox_users", "winapi", ] -[[package]] -name = "dispatch" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" - -[[package]] -name = "dispatch2" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" -dependencies = [ - "bitflags 2.13.0", - "objc2 0.6.4", -] - [[package]] name = "displaydoc" -version = "0.2.5" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn", -] - -[[package]] -name = "dlib" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" -dependencies = [ - "libloading 0.8.9", + "syn 3.0.9", ] [[package]] @@ -1295,31 +749,10 @@ checksum = "6e39034cee21a2f5bbb66ba0e3689819c4bb5d00382a282006e802a7ffa6c41d" dependencies = [ "cfg-if", "libc", - "socket2 0.6.4", + "socket2 0.6.5", "windows-sys 0.60.2", ] -[[package]] -name = "document-features" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" -dependencies = [ - "litrs", -] - -[[package]] -name = "downcast-rs" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" - -[[package]] -name = "dpi" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" - [[package]] name = "dtype_dispatch" version = "0.1.1" @@ -1339,280 +772,93 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] -name = "ecolor" -version = "0.31.1" +name = "either" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc4feb366740ded31a004a0e4452fbf84e80ef432ecf8314c485210229672fd1" -dependencies = [ - "bytemuck", - "emath", -] +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] -name = "eframe" -version = "0.31.1" +name = "endian-type" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0dfe0859f3fb1bc6424c57d41e10e9093fe938f426b691e42272c2f336d915c" -dependencies = [ - "ahash", - "bytemuck", - "document-features", - "egui", - "egui-wgpu", - "egui-winit", - "egui_glow", - "glow", - "glutin", - "glutin-winit", - "image", - "js-sys", - "log", - "objc2 0.5.2", - "objc2-app-kit 0.2.2", - "objc2-foundation 0.2.2", - "parking_lot", - "percent-encoding", - "profiling", - "raw-window-handle", - "static_assertions", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "web-time", - "winapi", - "windows-sys 0.59.0", - "winit", -] +checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d" [[package]] -name = "egui" -version = "0.31.1" +name = "env_filter" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25dd34cec49ab55d85ebf70139cb1ccd29c977ef6b6ba4fe85489d6877ee9ef3" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" dependencies = [ - "ahash", - "bitflags 2.13.0", - "emath", - "epaint", "log", - "nohash-hasher", - "profiling", + "regex", ] [[package]] -name = "egui-wgpu" -version = "0.31.1" +name = "env_logger" +version = "0.11.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d319dfef570f699b6e9114e235e862a2ddcf75f0d1a061de9e1328d92146d820" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" dependencies = [ - "ahash", - "bytemuck", - "document-features", - "egui", - "epaint", + "anstream", + "anstyle", + "env_filter", + "jiff", "log", - "profiling", - "thiserror 1.0.69", - "type-map", - "web-time", - "wgpu", - "winit", ] [[package]] -name = "egui-winit" -version = "0.31.1" +name = "equivalent" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d9dfbb78fe4eb9c3a39ad528b90ee5915c252e77bbab9d4ebc576541ab67e13" -dependencies = [ - "ahash", - "arboard", - "bytemuck", - "egui", - "log", - "profiling", - "raw-window-handle", - "smithay-clipboard", - "web-time", - "webbrowser", - "winit", -] +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] -name = "egui_glow" -version = "0.31.1" +name = "errno" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "910906e3f042ea6d2378ec12a6fd07698e14ddae68aed2d819ffe944a73aab9e" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ - "ahash", - "bytemuck", - "egui", - "glow", - "log", - "memoffset", - "profiling", - "wasm-bindgen", - "web-sys", - "winit", + "libc", + "windows-sys 0.61.2", ] [[package]] -name = "either" -version = "1.15.0" +name = "error-code" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" [[package]] -name = "emath" -version = "0.31.1" +name = "event-listener" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e4cadcff7a5353ba72b7fea76bf2122b5ebdbc68e8155aa56dfdea90083fe1b" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "bytemuck", + "parking", + "pin-project-lite", ] [[package]] -name = "encode_unicode" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" - -[[package]] -name = "encoding_rs" -version = "0.8.35" +name = "event-listener-strategy" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" dependencies = [ - "cfg-if", + "event-listener", + "pin-project-lite", ] [[package]] -name = "endian-type" -version = "0.1.2" +name = "exitcode" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d" +checksum = "de853764b47027c2e862a995c34978ffa63c1501f2e15f987ba11bd4f9bba193" [[package]] -name = "env_filter" -version = "1.0.0" +name = "fastrand" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f" -dependencies = [ - "log", - "regex", -] - -[[package]] -name = "env_logger" -version = "0.11.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0621c04f2196ac3f488dd583365b9c09be011a4ab8b9f37248ffcc8f6198b56a" -dependencies = [ - "anstream 1.0.0", - "anstyle", - "env_filter", - "jiff", - "log", -] - -[[package]] -name = "epaint" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fcc0f5a7c613afd2dee5e4b30c3e6acafb8ad6f0edb06068811f708a67c562" -dependencies = [ - "ab_glyph", - "ahash", - "bytemuck", - "ecolor", - "emath", - "epaint_default_fonts", - "log", - "nohash-hasher", - "parking_lot", - "profiling", -] - -[[package]] -name = "epaint_default_fonts" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7e7a64c02cf7a5b51e745a9e45f60660a286f151c238b9d397b3e923f5082f" - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "error-code" -version = "3.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59" - -[[package]] -name = "esaxx-rs" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6" -dependencies = [ - "cc", -] - -[[package]] -name = "event-listener" -version = "5.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" -dependencies = [ - "concurrent-queue", - "parking", - "pin-project-lite", -] - -[[package]] -name = "event-listener-strategy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" -dependencies = [ - "event-listener", - "pin-project-lite", -] - -[[package]] -name = "eventsource-stream" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74fef4569247a5f429d9156b9d0a2599914385dd189c539334c625d8099d90ab" -dependencies = [ - "futures-core", - "nom", - "pin-project-lite", -] - -[[package]] -name = "exitcode" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de853764b47027c2e862a995c34978ffa63c1501f2e15f987ba11bd4f9bba193" - -[[package]] -name = "fastrand" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "fd-lock" @@ -1621,45 +867,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78" dependencies = [ "cfg-if", - "rustix 1.1.3", + "rustix", "windows-sys 0.59.0", ] -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "filedescriptor" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" -dependencies = [ - "libc", - "thiserror 1.0.69", - "winapi", -] - [[package]] name = "find-msvc-tools" -version = "0.1.7" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f449e6c6c08c865631d4890cfacf252b3d396c9bcc83adb6623cdb02a8336c41" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "flate2" -version = "1.1.9" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ - "crc32fast", - "miniz_oxide", - "zlib-rs 0.6.6", + "zlib-rs 0.6.8", ] [[package]] @@ -1680,48 +904,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared 0.1.1", -] - -[[package]] -name = "foreign-types" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" -dependencies = [ - "foreign-types-macros", - "foreign-types-shared 0.3.1", -] - -[[package]] -name = "foreign-types-macros" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - -[[package]] -name = "foreign-types-shared" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" - [[package]] name = "form_urlencoded" version = "1.2.2" @@ -1739,9 +921,9 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "futures" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" dependencies = [ "futures-channel", "futures-core", @@ -1754,9 +936,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", "futures-sink", @@ -1764,15 +946,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-executor" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" dependencies = [ "futures-core", "futures-task", @@ -1781,44 +963,38 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" [[package]] name = "futures-macro" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] name = "futures-sink" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] name = "futures-task" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" - -[[package]] -name = "futures-timer" -version = "3.0.3" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-util" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-channel", "futures-core", @@ -1849,7 +1025,7 @@ checksum = "f2b6d1e2f75c16bfbcd0f95d84f99858a6e2f885c2287d1f5c3a96e8444a34b4" dependencies = [ "attribute-derive", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1871,8 +1047,8 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.3", - "windows-link 0.2.1", + "rustix", + "windows-link", ] [[package]] @@ -1881,14 +1057,14 @@ version = "0.2.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" dependencies = [ - "unicode-width 0.2.2", + "unicode-width", ] [[package]] name = "getrandom" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", "js-sys", @@ -1904,11 +1080,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", - "js-sys", "libc", "r-efi 5.3.0", "wasip2", - "wasm-bindgen", ] [[package]] @@ -1918,159 +1092,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", -] - -[[package]] -name = "gif" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" -dependencies = [ - "color_quant", - "weezl", -] - -[[package]] -name = "gl_generator" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" -dependencies = [ - "khronos_api", - "log", - "xml-rs", -] - -[[package]] -name = "glob" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" - -[[package]] -name = "glow" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" -dependencies = [ - "js-sys", - "slotmap", "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "glutin" -version = "0.32.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" -dependencies = [ - "bitflags 2.13.0", - "cfg_aliases 0.2.1", - "cgl", - "dispatch2", - "glutin_egl_sys", - "glutin_glx_sys", - "glutin_wgl_sys", - "libloading 0.8.9", - "objc2 0.6.4", - "objc2-app-kit 0.3.2", - "objc2-core-foundation", - "objc2-foundation 0.3.2", - "once_cell", - "raw-window-handle", - "windows-sys 0.52.0", - "x11-dl", -] - -[[package]] -name = "glutin-winit" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" -dependencies = [ - "cfg_aliases 0.2.1", - "glutin", - "raw-window-handle", - "winit", -] - -[[package]] -name = "glutin_egl_sys" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" -dependencies = [ - "gl_generator", - "windows-sys 0.52.0", -] - -[[package]] -name = "glutin_glx_sys" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" -dependencies = [ - "gl_generator", - "x11-dl", -] - -[[package]] -name = "glutin_wgl_sys" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" -dependencies = [ - "gl_generator", -] - -[[package]] -name = "gpu-alloc" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45cf04b2726f02df5508c6de726acdc90cdf97ac771a9a0ffd8ba10a6e696bf9" -dependencies = [ - "bitflags 2.13.0", - "gpu-alloc-types", -] - -[[package]] -name = "gpu-alloc-types" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2bbed164dd10ed526c2e4fe3e721ca4a71c61730e5aafac6844b417b3227058" -dependencies = [ - "bitflags 2.13.0", -] - -[[package]] -name = "gpu-descriptor" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca" -dependencies = [ - "bitflags 2.13.0", - "gpu-descriptor-types", - "hashbrown 0.15.5", ] [[package]] -name = "gpu-descriptor-types" -version = "0.2.0" +name = "glob" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91" -dependencies = [ - "bitflags 2.13.0", -] +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "h2" -version = "0.4.12" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -2078,7 +1117,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.14.0", + "indexmap 2.14.2", "slab", "tokio", "tokio-util", @@ -2142,9 +1181,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" [[package]] name = "hex" @@ -2158,30 +1197,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" -[[package]] -name = "hf-hub" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "629d8f3bbeda9d148036d6b0de0a3ab947abd08ce90626327fc3547a49d59d97" -dependencies = [ - "dirs", - "futures", - "http", - "indicatif", - "libc", - "log", - "native-tls", - "num_cpus", - "rand 0.9.2", - "reqwest 0.12.24", - "serde", - "serde_json", - "thiserror 2.0.18", - "tokio", - "ureq", - "windows-sys 0.60.2", -] - [[package]] name = "hmac" version = "0.12.1" @@ -2202,20 +1217,19 @@ dependencies = [ [[package]] name = "http" -version = "1.3.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" dependencies = [ "bytes", - "fnv", "itoa", ] [[package]] name = "http-body" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", "http", @@ -2223,9 +1237,9 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.3" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", @@ -2246,17 +1260,11 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" -[[package]] -name = "humantime" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" - [[package]] name = "hyper" -version = "1.7.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb3aa54a13a0dfe7fbe3a59e0c76093041720fdc77b110cc0fc260fafb4dc51e" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -2269,7 +1277,6 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -2277,19 +1284,18 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.7" +version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ "http", "hyper", "hyper-util", "rustls", - "rustls-pki-types", "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.4", + "webpki-roots", ] [[package]] @@ -2306,52 +1312,34 @@ dependencies = [ ] [[package]] -name = "hyper-tls" -version = "0.6.0" +name = "hyper-util" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ + "base64 0.23.1", "bytes", - "http-body-util", - "hyper", - "hyper-util", - "native-tls", - "tokio", - "tokio-native-tls", - "tower-service", -] - -[[package]] -name = "hyper-util" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "http", - "http-body", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", "hyper", "ipnet", "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.4", - "system-configuration 0.6.1", + "socket2 0.6.5", "tokio", "tower-service", "tracing", - "windows-registry", ] [[package]] name = "iana-time-zone" -version = "0.1.64" +version = "0.1.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -2359,7 +1347,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.62.2", + "windows-core", ] [[package]] @@ -2373,12 +1361,13 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", + "utf8_iter", "yoke", "zerofrom", "zerovec", @@ -2386,9 +1375,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -2399,9 +1388,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -2413,16 +1402,17 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ + "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", @@ -2433,15 +1423,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -2452,12 +1442,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - [[package]] name = "idna" version = "1.1.0" @@ -2471,42 +1455,14 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" dependencies = [ "icu_normalizer", "icu_properties", ] -[[package]] -name = "image" -version = "0.25.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db35664ce6b9810857a38a906215e75a9c879f0696556a39f59c62829710251a" -dependencies = [ - "bytemuck", - "byteorder-lite", - "color_quant", - "gif", - "image-webp", - "num-traits", - "png", - "tiff", - "zune-core", - "zune-jpeg", -] - -[[package]] -name = "image-webp" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" -dependencies = [ - "byteorder-lite", - "quick-error", -] - [[package]] name = "indexmap" version = "1.9.3" @@ -2519,32 +1475,19 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.14.0" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", ] -[[package]] -name = "indicatif" -version = "0.17.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235" -dependencies = [ - "console", - "number_prefix", - "portable-atomic", - "unicode-width 0.2.2", - "web-time", -] - [[package]] name = "indoc" -version = "2.0.7" +version = "2.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" dependencies = [ "rustversion", ] @@ -2557,20 +1500,20 @@ checksum = "71dd52191aae121e8611f1e8dc3e324dd0dd1dee1e6dd91d10ee07a3cfb4d9d8" [[package]] name = "ipnet" -version = "2.11.0" +version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] name = "is-macro" -version = "0.3.7" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d57a3e447e24c22647738e4607f1df1e0ec6f72e16182c4cd199f647cdfb0e4" +checksum = "8267aa6001e25494f3015f9663bbd88a18240c74483afa5f0934a1b3e4c388e9" dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -2579,15 +1522,6 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.14.0" @@ -2599,17 +1533,18 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.15" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jiff" -version = "0.2.32" +version = "0.2.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "961d16382652bfdd8c6f68b223b26a8c93e0d475c672f414411db31c6c5c900e" +checksum = "3ac703058abac89e5c39b0b879dce2b6b14a4ba36600c7e7e3d0c60a6883ef3c" dependencies = [ "defmt", + "jiff-core", "jiff-static", "log", "portable-atomic", @@ -2618,95 +1553,42 @@ dependencies = [ ] [[package]] -name = "jiff-static" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0879bd39df99c4c5e2c6615ccc026391a423dde10532c573e6086eb94a802cc" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "jni" -version = "0.22.4" +name = "jiff-core" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +checksum = "aee43309eb53bafb8c36d35d6e444769c8f8e6206a9fbf7546f5db9d7d4a0e93" dependencies = [ - "cfg-if", - "combine", - "jni-macros", - "jni-sys 0.4.1", + "defmt", "log", - "simd_cesu8", - "thiserror 2.0.18", - "walkdir", - "windows-link 0.2.1", ] [[package]] -name = "jni-macros" -version = "0.22.4" +name = "jiff-static" +version = "0.2.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +checksum = "6dc32470c67eb7d0e9ccb74303fa925313dc04cecb1aa048beaa6f391e36a93d" dependencies = [ + "jiff-core", "proc-macro2", "quote", - "rustc_version", - "simd_cesu8", - "syn", -] - -[[package]] -name = "jni-sys" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" -dependencies = [ - "jni-sys 0.4.1", -] - -[[package]] -name = "jni-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" -dependencies = [ - "jni-sys-macros", -] - -[[package]] -name = "jni-sys-macros" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" -dependencies = [ - "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "jobserver" -version = "0.1.34" +version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" dependencies = [ - "getrandom 0.3.4", + "getrandom 0.4.3", "libc", ] -[[package]] -name = "jpeg-decoder" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" - [[package]] name = "js-sys" -version = "0.3.102" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03d04c30968dffe80775bd4d7fb676131cd04a1fb46d2686dbffbaec2d9dfd31" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -2732,28 +1614,11 @@ dependencies = [ "cpufeatures 0.2.17", ] -[[package]] -name = "khronos-egl" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" -dependencies = [ - "libc", - "libloading 0.8.9", - "pkg-config", -] - -[[package]] -name = "khronos_api" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" - [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "lexical-parse-float" @@ -2788,21 +1653,21 @@ checksum = "803ec87c9cfb29b9d2633f20cba1f488db3fd53f2158b1024cbefb47ba05d413" [[package]] name = "libbz2-rs-sys" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c" +checksum = "32f454fd6831a29c0e827ed075bca2a15be201bd57f4168f0fd1041124eab17e" [[package]] name = "libc" -version = "0.2.186" +version = "0.2.183" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" [[package]] name = "libffi" -version = "5.1.1" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed185dbb87539a100c1b36c219e16e71572c6d4d4fed3ded898140f755adeaaf" +checksum = "7a8d526bc07aa02e6826944ec446ecd8d228bd97b1cbd21e5bc5e3407a09a585" dependencies = [ "libc", "libffi-sys", @@ -2810,23 +1675,13 @@ dependencies = [ [[package]] name = "libffi-sys" -version = "4.2.0" +version = "4.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25831b230b6a90bdea9f28339c1d00d59773a1c492e8ca09b1ad80e56394c261" +checksum = "eab801a4ae9065bfea87f37204a7940523e752056e4a090eaaaab9b47fc826b5" dependencies = [ "cc", ] -[[package]] -name = "libloading" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" -dependencies = [ - "cfg-if", - "windows-link 0.2.1", -] - [[package]] name = "libloading" version = "0.9.0" @@ -2834,23 +1689,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" dependencies = [ "cfg-if", - "windows-link 0.2.1", + "windows-link", ] [[package]] name = "liblzma" -version = "0.4.7" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45aec2360b3933207e27908049d8e4df4e476b58180afb1e56b2a4fb72efe4ba" +checksum = "aa980ea6744074a5b5e0ac6b164aca94fc970121869b3e78ae12a2b0097dbea7" dependencies = [ "liblzma-sys", ] [[package]] name = "liblzma-sys" -version = "0.4.7" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a046c7f353ba30f810545151e04f63545833803f5b86ee3ddf1517247fe560a5" +checksum = "7c7e3581f367a78d7b7e7ae948d023310556f0cfc13156c2e4e00e25616492b9" dependencies = [ "cc", "libc", @@ -2865,13 +1720,11 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.12" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ - "bitflags 2.13.0", "libc", - "redox_syscall 0.7.5", ] [[package]] @@ -2885,27 +1738,15 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" - -[[package]] -name = "linux-raw-sys" -version = "0.11.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" - -[[package]] -name = "litrs" -version = "1.0.0" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "lock_api" @@ -2918,9 +1759,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.33" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "lru" @@ -2933,9 +1774,9 @@ dependencies = [ [[package]] name = "lru-slab" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" [[package]] name = "lz4_flex" @@ -2948,30 +1789,14 @@ dependencies = [ [[package]] name = "mac_address" -version = "1.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303" -dependencies = [ - "nix 0.29.0", - "winapi", -] - -[[package]] -name = "macro_rules_attribute" -version = "0.2.2" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520" +checksum = "f3d0581a75c45969c63afd2bb87b1d8b25cfcc556c7a918cf9bb13b0fe8d2381" dependencies = [ - "macro_rules_attribute-proc_macro", - "paste", + "nix 0.31.2", + "windows-sys 0.61.2", ] -[[package]] -name = "macro_rules_attribute-proc_macro" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30" - [[package]] name = "malachite-base" version = "0.9.2" @@ -2979,7 +1804,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4f44099731f17094b07825c88ccb5fbd1bfa1f82fafff7daa33e8b8652db16e" dependencies = [ "hashbrown 0.16.1", - "itertools 0.14.0", + "itertools", "libm", "ryu", ] @@ -3003,7 +1828,7 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a137660cdba20f136c8a223125f08088adb4e0b72fbb8466f08c43e31cc0427d" dependencies = [ - "itertools 0.14.0", + "itertools", "libm", "malachite-base", "wide", @@ -3015,21 +1840,12 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ffcbeed95e34c0fcc3864ccd146e129cbbf7de1513d3afbcfb47c7674c82d94" dependencies = [ - "itertools 0.14.0", + "itertools", "libm", "malachite-base", "malachite-nz", ] -[[package]] -name = "malloc_buf" -version = "0.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" -dependencies = [ - "libc", -] - [[package]] name = "manyhow" version = "0.11.4" @@ -3039,7 +1855,7 @@ dependencies = [ "manyhow-macros", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -3082,745 +1898,192 @@ checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" [[package]] name = "md-5" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" -dependencies = [ - "cfg-if", - "digest", -] - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "memmap2" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - -[[package]] -name = "metal" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f569fb946490b5743ad69813cb19629130ce9374034abe31614a36402d18f99e" -dependencies = [ - "bitflags 2.13.0", - "block", - "core-graphics-types", - "foreign-types 0.5.0", - "log", - "objc", - "paste", -] - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "mio" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" -dependencies = [ - "libc", - "log", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "monostate" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67" -dependencies = [ - "monostate-impl", - "serde", - "serde_core", -] - -[[package]] -name = "monostate-impl" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "mt19937" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56bc7ea7924ea1a79a9e817d0483e39295424cf2b1276cf2b968f9a6c9b63b54" -dependencies = [ - "rand_core 0.9.3", -] - -[[package]] -name = "naga" -version = "24.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e380993072e52eef724eddfcde0ed013b0c023c3f0417336ed041aa9f076994e" -dependencies = [ - "arrayvec", - "bit-set", - "bitflags 2.13.0", - "cfg_aliases 0.2.1", - "codespan-reporting", - "hexf-parse", - "indexmap 2.14.0", - "log", - "rustc-hash 1.1.0", - "spirv", - "strum 0.26.3", - "termcolor", - "thiserror 2.0.18", - "unicode-xid", -] - -[[package]] -name = "native-tls" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" -dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", -] - -[[package]] -name = "ndk" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" -dependencies = [ - "bitflags 2.13.0", - "jni-sys 0.3.1", - "log", - "ndk-sys 0.6.0+11769913", - "num_enum", - "raw-window-handle", - "thiserror 1.0.69", -] - -[[package]] -name = "ndk-context" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" - -[[package]] -name = "ndk-sys" -version = "0.5.0+25.2.9519653" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691" -dependencies = [ - "jni-sys 0.3.1", -] - -[[package]] -name = "ndk-sys" -version = "0.6.0+11769913" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" -dependencies = [ - "jni-sys 0.3.1", -] - -[[package]] -name = "nibble_vec" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43" -dependencies = [ - "smallvec", -] - -[[package]] -name = "nix" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" -dependencies = [ - "bitflags 2.13.0", - "cfg-if", - "cfg_aliases 0.1.1", - "libc", -] - -[[package]] -name = "nix" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" -dependencies = [ - "bitflags 2.13.0", - "cfg-if", - "cfg_aliases 0.2.1", - "libc", - "memoffset", -] - -[[package]] -name = "nix" -version = "0.30.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" -dependencies = [ - "bitflags 2.13.0", - "cfg-if", - "cfg_aliases 0.2.1", - "libc", - "memoffset", -] - -[[package]] -name = "nix" -version = "0.31.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" -dependencies = [ - "bitflags 2.13.0", - "cfg-if", - "cfg_aliases 0.2.1", - "libc", -] - -[[package]] -name = "nohash-hasher" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" - -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "num-complex" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" - -[[package]] -name = "num-integer" -version = "0.1.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "num_enum" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" -dependencies = [ - "num_enum_derive", - "rustversion", -] - -[[package]] -name = "num_enum_derive" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "num_threads" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" -dependencies = [ - "libc", -] - -[[package]] -name = "number_prefix" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" - -[[package]] -name = "oauth2" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" -dependencies = [ - "base64 0.22.1", - "chrono", - "getrandom 0.2.16", - "http", - "rand 0.8.5", - "serde", - "serde_json", - "serde_path_to_error", - "sha2", - "thiserror 1.0.69", - "url", -] - -[[package]] -name = "objc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" -dependencies = [ - "malloc_buf", -] - -[[package]] -name = "objc-sys" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" - -[[package]] -name = "objc2" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" -dependencies = [ - "objc-sys", - "objc2-encode", -] - -[[package]] -name = "objc2" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" -dependencies = [ - "objc2-encode", -] - -[[package]] -name = "objc2-app-kit" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" -dependencies = [ - "bitflags 2.13.0", - "block2", - "libc", - "objc2 0.5.2", - "objc2-core-data", - "objc2-core-image", - "objc2-foundation 0.2.2", - "objc2-quartz-core", -] - -[[package]] -name = "objc2-app-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" -dependencies = [ - "bitflags 2.13.0", - "objc2 0.6.4", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation 0.3.2", -] - -[[package]] -name = "objc2-cloud-kit" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" -dependencies = [ - "bitflags 2.13.0", - "block2", - "objc2 0.5.2", - "objc2-core-location", - "objc2-foundation 0.2.2", -] - -[[package]] -name = "objc2-contacts" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" -dependencies = [ - "block2", - "objc2 0.5.2", - "objc2-foundation 0.2.2", -] - -[[package]] -name = "objc2-core-data" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" -dependencies = [ - "bitflags 2.13.0", - "block2", - "objc2 0.5.2", - "objc2-foundation 0.2.2", -] - -[[package]] -name = "objc2-core-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" -dependencies = [ - "bitflags 2.13.0", - "dispatch2", - "objc2 0.6.4", -] - -[[package]] -name = "objc2-core-graphics" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" -dependencies = [ - "bitflags 2.13.0", - "dispatch2", - "objc2 0.6.4", - "objc2-core-foundation", - "objc2-io-surface", -] - -[[package]] -name = "objc2-core-image" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" -dependencies = [ - "block2", - "objc2 0.5.2", - "objc2-foundation 0.2.2", - "objc2-metal", -] - -[[package]] -name = "objc2-core-location" -version = "0.2.2" +version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ - "block2", - "objc2 0.5.2", - "objc2-contacts", - "objc2-foundation 0.2.2", + "cfg-if", + "digest", ] [[package]] -name = "objc2-encode" -version = "4.1.0" +name = "memchr" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] -name = "objc2-foundation" -version = "0.2.2" +name = "memmap2" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ - "bitflags 2.13.0", - "block2", - "dispatch", "libc", - "objc2 0.5.2", ] [[package]] -name = "objc2-foundation" -version = "0.3.2" +name = "memoffset" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" dependencies = [ - "bitflags 2.13.0", - "objc2 0.6.4", - "objc2-core-foundation", + "autocfg", ] [[package]] -name = "objc2-io-surface" -version = "0.3.2" +name = "mime" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" -dependencies = [ - "bitflags 2.13.0", - "objc2 0.6.4", - "objc2-core-foundation", -] +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] -name = "objc2-link-presentation" -version = "0.2.2" +name = "mio" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ - "block2", - "objc2 0.5.2", - "objc2-app-kit 0.2.2", - "objc2-foundation 0.2.2", + "libc", + "wasi", + "windows-sys 0.61.2", ] [[package]] -name = "objc2-metal" -version = "0.2.2" +name = "mt19937" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +checksum = "56bc7ea7924ea1a79a9e817d0483e39295424cf2b1276cf2b968f9a6c9b63b54" dependencies = [ - "bitflags 2.13.0", - "block2", - "objc2 0.5.2", - "objc2-foundation 0.2.2", + "rand_core 0.9.5", ] [[package]] -name = "objc2-quartz-core" -version = "0.2.2" +name = "nibble_vec" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43" dependencies = [ - "bitflags 2.13.0", - "block2", - "objc2 0.5.2", - "objc2-foundation 0.2.2", - "objc2-metal", + "smallvec", ] [[package]] -name = "objc2-symbols" -version = "0.2.2" +name = "nix" +version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" dependencies = [ - "objc2 0.5.2", - "objc2-foundation 0.2.2", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", ] [[package]] -name = "objc2-ui-kit" -version = "0.2.2" +name = "nix" +version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +checksum = "5d6d0705320c1e6ba1d912b5e37cf18071b6c2e9b7fa8215a1e8a7651966f5d3" dependencies = [ - "bitflags 2.13.0", - "block2", - "objc2 0.5.2", - "objc2-cloud-kit", - "objc2-core-data", - "objc2-core-image", - "objc2-core-location", - "objc2-foundation 0.2.2", - "objc2-link-presentation", - "objc2-quartz-core", - "objc2-symbols", - "objc2-uniform-type-identifiers", - "objc2-user-notifications", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", ] [[package]] -name = "objc2-uniform-type-identifiers" -version = "0.2.2" +name = "nu-ansi-term" +version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "block2", - "objc2 0.5.2", - "objc2-foundation 0.2.2", + "windows-sys 0.61.2", ] [[package]] -name = "objc2-user-notifications" -version = "0.2.2" +name = "num-complex" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ - "bitflags 2.13.0", - "block2", - "objc2 0.5.2", - "objc2-core-location", - "objc2-foundation 0.2.2", + "num-traits", ] [[package]] -name = "object" -version = "0.37.3" +name = "num-conv" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" -dependencies = [ - "memchr", -] +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" [[package]] -name = "once_cell" -version = "1.21.3" +name = "num-integer" +version = "0.1.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] [[package]] -name = "once_cell_polyfill" -version = "1.70.2" +name = "num-traits" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] [[package]] -name = "onig" -version = "6.5.1" +name = "num_cpus" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "336b9c63443aceef14bea841b899035ae3abe89b7c486aaf4c5bd8aafedac3f0" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" dependencies = [ - "bitflags 2.13.0", + "hermit-abi", "libc", - "once_cell", - "onig_sys", ] [[package]] -name = "onig_sys" -version = "69.9.1" +name = "num_enum" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f86c6eef3d6df15f23bcfb6af487cbd2fed4e5581d58d5bf1f5f8b7f6727dc" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" dependencies = [ - "cc", - "pkg-config", + "num_enum_derive", + "rustversion", ] [[package]] -name = "openssl" -version = "0.10.75" +name = "num_enum_derive" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "bitflags 2.13.0", - "cfg-if", - "foreign-types 0.3.2", - "libc", - "once_cell", - "openssl-macros", - "openssl-sys", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "openssl-macros" -version = "0.1.1" +name = "object" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" dependencies = [ - "proc-macro2", - "quote", - "syn", + "memchr", ] [[package]] -name = "openssl-probe" -version = "0.1.6" +name = "once_cell" +version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] -name = "openssl-sys" -version = "0.9.111" +name = "once_cell_polyfill" +version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "opentelemetry" @@ -3879,59 +2142,25 @@ dependencies = [ "glob", "opentelemetry", "percent-encoding", - "rand 0.8.5", + "rand 0.8.8", "thiserror 1.0.69", "tokio", "tokio-stream", ] -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - [[package]] name = "optional" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978aa494585d3ca4ad74929863093e87cac9790d81fe7aba2b3dc2890643a0fc" -[[package]] -name = "orbclient" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" -dependencies = [ - "libc", - "libredox", -] - -[[package]] -name = "ordered-float" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951" -dependencies = [ - "num-traits", -] - [[package]] name = "ordermap" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f7476a5b122ff1fce7208e7ee9dccd0a516e835f5b8b19b8f3c98a34cf757c1" -dependencies = [ - "indexmap 2.14.0", -] - -[[package]] -name = "owned_ttf_parser" -version = "0.25.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +checksum = "16a756ddcdeb6c0efc8927bdf0ed112885815a35ba350472a467be5104f01ca1" dependencies = [ - "ttf-parser", + "indexmap 2.14.2", ] [[package]] @@ -3968,9 +2197,9 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.18", + "redox_syscall", "smallvec", - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -3979,12 +2208,6 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" -[[package]] -name = "pastey" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" - [[package]] name = "pbkdf2" version = "0.12.2" @@ -4060,7 +2283,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ "phf_shared 0.11.3", - "rand 0.8.5", + "rand 0.8.8", ] [[package]] @@ -4083,7 +2306,7 @@ dependencies = [ "phf_shared 0.13.1", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -4106,41 +2329,35 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.10" +version = "1.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.10" +version = "1.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "pin-project-lite" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" - -[[package]] -name = "pin-utils" -version = "0.1.0" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "pkg-config" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "pmutil" @@ -4150,86 +2367,38 @@ checksum = "52a40bc70c2c58040d2d8b167ba9a5ff59fc9dab7ad44771cfde3dcfde7a09c6" dependencies = [ "proc-macro2", "quote", - "syn", -] - -[[package]] -name = "png" -version = "0.17.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide", -] - -[[package]] -name = "polling" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" -dependencies = [ - "cfg-if", - "concurrent-queue", - "hermit-abi", - "pin-project-lite", - "rustix 1.1.3", - "windows-sys 0.61.2", + "syn 2.0.119", ] [[package]] name = "portable-atomic" -version = "1.11.1" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "portable-atomic-util" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" dependencies = [ "portable-atomic", ] -[[package]] -name = "portable-pty" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e" -dependencies = [ - "anyhow", - "bitflags 1.3.2", - "downcast-rs", - "filedescriptor", - "lazy_static", - "libc", - "log", - "nix 0.28.0", - "serial2", - "shared_library", - "shell-words", - "winapi", - "winreg", -] - [[package]] name = "potential_utf" -version = "0.1.4" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ "zerovec", ] [[package]] name = "powerfmt" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "ppv-lite86" @@ -4252,15 +2421,6 @@ dependencies = [ "xxhash-rust", ] -[[package]] -name = "proc-macro-crate" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" -dependencies = [ - "toml_edit 0.25.12+spec-1.1.0", -] - [[package]] name = "proc-macro-utils" version = "0.10.0" @@ -4274,33 +2434,13 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] -[[package]] -name = "process-wrap" -version = "9.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e842efad9119158434d193c6682e2ebee4b44d6ad801d7b349623b3f57cdf55" -dependencies = [ - "futures", - "indexmap 2.14.0", - "nix 0.31.3", - "tokio", - "tracing", - "windows 0.62.2", -] - -[[package]] -name = "profiling" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" - [[package]] name = "prost" version = "0.13.5" @@ -4318,17 +2458,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "psm" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645dbe486e346d9b5de3ef16ede18c26e6c70ad97418f4874b8b1889d6e761ea" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" dependencies = [ "ar_archive_writer", "cc", @@ -4353,14 +2493,14 @@ dependencies = [ "opentelemetry-otlp", "opentelemetry_sdk", "probing-memtable", - "rand 0.9.2", + "rand 0.9.5", "rcgen", "rustls", "rustls-pemfile", "serde", "serde_json", "sha2", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", "tokio", "tokio-rustls", @@ -4373,120 +2513,29 @@ dependencies = [ "uuid", ] -[[package]] -name = "pulsing-bench" -version = "1.1.0" -dependencies = [ - "anyhow", - "async-trait", - "chrono", - "colored", - "futures-util", - "hf-hub", - "humantime", - "log", - "pulsing-actor", - "pyo3", - "pyo3-async-runtimes", - "rand 0.9.2", - "reqwest 0.12.24", - "reqwest-eventsource", - "serde", - "serde_json", - "tokenizers", - "tokio", - "tracing", - "tracing-subscriber", - "uuid", - "vergen-gitcl", -] - -[[package]] -name = "pulsing-bench-py" -version = "0.1.3" -dependencies = [ - "pulsing-bench", - "pyo3", - "pyo3-async-runtimes", - "serde_json", - "tracing", - "tracing-subscriber", -] - [[package]] name = "pulsing-bindings-core" version = "0.1.3" dependencies = [ - "bincode", - "futures", - "pulsing-actor", - "serde", - "uuid", -] - -[[package]] -name = "pulsing-cli" -version = "0.1.3" -dependencies = [ - "anyhow", - "clap", - "pulsing-forge", - "pulsing-gui", - "pulsing-rpymod", - "pulsing-workspace", - "rustpython", - "rustpython-vm", - "serde_json", - "tempfile", - "tokio", -] - -[[package]] -name = "pulsing-forge" -version = "0.1.3" -dependencies = [ - "anyhow", - "base64 0.22.1", - "chrono", - "clap", - "comfy-table", + "bincode", "futures", - "futures-util", - "glob", - "image", - "libc", - "portable-pty", - "reedline", - "regex", - "reqwest 0.12.24", - "reqwest-eventsource", - "rmcp", + "pulsing-actor", "serde", - "serde_json", - "sha1", - "shlex", - "streaming-iterator", - "tempfile", - "thiserror 2.0.18", - "tokio", - "tokio-util", - "toml 0.8.23", - "tracing", - "tree-sitter", - "tree-sitter-bash", - "url", "uuid", ] [[package]] -name = "pulsing-gui" +name = "pulsing-cli" version = "0.1.3" dependencies = [ "anyhow", - "eframe", - "egui", - "pulsing-forge", + "clap", + "pulsing-rpymod", "pulsing-workspace", + "rustpython", + "rustpython-vm", + "serde_json", + "tempfile", "tokio", ] @@ -4501,14 +2550,13 @@ dependencies = [ "crossbeam-channel", "futures", "pulsing-actor", - "pulsing-forge", "pyo3", "pyo3-async-runtimes", "pythonize", - "reqwest 0.12.24", + "reqwest", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "uuid", @@ -4522,6 +2570,7 @@ dependencies = [ "async-trait", "bincode", "futures", + "libc", "pulsing-actor", "pulsing-bindings-core", "rustpython", @@ -4599,7 +2648,7 @@ checksum = "b2df2884957d2476731f987673befac5d521dff10abb0a7cbe12015bc7702fe9" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -4631,7 +2680,7 @@ dependencies = [ "proc-macro2", "pyo3-macros-backend", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -4644,7 +2693,7 @@ dependencies = [ "proc-macro2", "pyo3-build-config", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -4657,36 +2706,21 @@ dependencies = [ "serde", ] -[[package]] -name = "quick-error" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" - -[[package]] -name = "quick-xml" -version = "0.39.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e" -dependencies = [ - "memchr", -] - [[package]] name = "quinn" -version = "0.11.9" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", - "cfg_aliases 0.2.1", + "cfg_aliases", "pin-project-lite", "quinn-proto", "quinn-udp", - "rustc-hash 2.1.1", + "rustc-hash", "rustls", - "socket2 0.6.4", - "thiserror 2.0.18", + "socket2 0.6.5", + "thiserror 2.0.21", "tokio", "tracing", "web-time", @@ -4694,20 +2728,21 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.13" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", - "getrandom 0.3.4", + "getrandom 0.4.3", "lru-slab", - "rand 0.9.2", + "rand 0.10.3", + "rand_pcg", "ring", - "rustc-hash 2.1.1", + "rustc-hash", "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tracing", "web-time", @@ -4715,23 +2750,23 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.14" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ - "cfg_aliases 0.2.1", + "cfg_aliases", "libc", "once_cell", - "socket2 0.6.4", + "socket2 0.6.5", "tracing", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "quote" -version = "1.0.46" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -4755,7 +2790,7 @@ dependencies = [ "proc-macro-utils", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -4791,9 +2826,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.8.5" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha 0.3.1", @@ -4802,19 +2837,19 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.2" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ "rand_chacha 0.9.0", - "rand_core 0.9.3", + "rand_core 0.9.5", ] [[package]] name = "rand" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", "getrandom 0.4.3", @@ -4838,7 +2873,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core 0.9.3", + "rand_core 0.9.5", ] [[package]] @@ -4847,14 +2882,14 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom 0.2.16", + "getrandom 0.2.17", ] [[package]] name = "rand_core" -version = "0.9.3" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" dependencies = [ "getrandom 0.3.4", ] @@ -4866,49 +2901,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] -name = "rand_xoshiro" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" -dependencies = [ - "rand_core 0.6.4", -] - -[[package]] -name = "raw-window-handle" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" - -[[package]] -name = "rayon" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-cond" -version = "0.4.0" +name = "rand_pcg" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" dependencies = [ - "either", - "itertools 0.14.0", - "rayon", + "rand_core 0.10.1", ] [[package]] -name = "rayon-core" -version = "1.13.0" +name = "rand_xoshiro" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" dependencies = [ - "crossbeam-deque", - "crossbeam-utils", + "rand_core 0.6.4", ] [[package]] @@ -4924,31 +2931,13 @@ dependencies = [ "yasna", ] -[[package]] -name = "redox_syscall" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" -dependencies = [ - "bitflags 1.3.2", -] - [[package]] name = "redox_syscall" version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.13.0", -] - -[[package]] -name = "redox_syscall" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4666a1a60d8412eab19d94f6d13dcc9cea0a5ef4fdf6a5db306537413c661b1b" -dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", ] [[package]] @@ -4957,67 +2946,36 @@ version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" dependencies = [ - "getrandom 0.2.16", - "libredox", - "thiserror 1.0.69", -] - -[[package]] -name = "redox_users" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" -dependencies = [ - "getrandom 0.2.16", + "getrandom 0.2.17", "libredox", - "thiserror 2.0.18", -] - -[[package]] -name = "reedline" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd4728ee71d2aa3a364ee64470d1aa64b3f0467b2d28b73df15259d005dec64a" -dependencies = [ - "chrono", - "crossterm 0.28.1", - "fd-lock", - "itertools 0.13.0", - "nu-ansi-term", - "serde", - "strip-ansi-escapes", - "strum 0.26.3", - "strum_macros 0.26.4", "thiserror 1.0.69", - "unicode-segmentation", - "unicode-width 0.1.14", ] [[package]] name = "ref-cast" -version = "1.0.25" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" dependencies = [ "ref-cast-impl", ] [[package]] name = "ref-cast-impl" -version = "1.0.25" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] name = "regex" -version = "1.12.2" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" dependencies = [ "aho-corasick", "memchr", @@ -5027,9 +2985,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.13" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", @@ -5038,39 +2996,28 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" - -[[package]] -name = "renderdoc-sys" -version = "1.1.0" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "reqwest" -version = "0.12.24" +version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", - "encoding_rs", "futures-core", - "futures-util", "h2", "http", "http-body", "http-body-util", "hyper", "hyper-rustls", - "hyper-tls", "hyper-util", "js-sys", "log", - "mime", - "native-tls", "percent-encoding", "pin-project-lite", "quinn", @@ -5081,68 +3028,15 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-native-tls", "tokio-rustls", - "tokio-util", - "tower 0.5.2", - "tower-http", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-streams 0.4.2", - "web-sys", - "webpki-roots 1.0.4", -] - -[[package]] -name = "reqwest" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "serde", - "serde_json", - "sync_wrapper", - "tokio", - "tokio-util", - "tower 0.5.2", + "tower 0.5.3", "tower-http", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", - "wasm-streams 0.5.0", "web-sys", -] - -[[package]] -name = "reqwest-eventsource" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632c55746dbb44275691640e7b40c907c16a2dc1a5842aa98aaec90da6ec6bde" -dependencies = [ - "eventsource-stream", - "futures-core", - "futures-timer", - "mime", - "nom", - "pin-project-lite", - "reqwest 0.12.24", - "thiserror 1.0.69", + "webpki-roots", ] [[package]] @@ -5163,7 +3057,7 @@ dependencies = [ "pmutil", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -5174,105 +3068,36 @@ checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ "cc", "cfg-if", - "getrandom 0.2.16", + "getrandom 0.2.17", "libc", "untrusted 0.9.0", "windows-sys 0.52.0", ] -[[package]] -name = "rmcp" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0810a9f717d9828f475fe1f629f4c305c8464b7f496c3a854b58d29e65f4058e" -dependencies = [ - "async-trait", - "base64 0.22.1", - "chrono", - "futures", - "http", - "oauth2", - "pastey", - "pin-project-lite", - "process-wrap", - "reqwest 0.13.4", - "rmcp-macros", - "serde", - "serde_json", - "sse-stream", - "thiserror 2.0.18", - "tokio", - "tokio-stream", - "tokio-util", - "tracing", - "url", -] - -[[package]] -name = "rmcp-macros" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aefac48c364756e97f04c0401ba3231e8607882c7c1d92da0437dc16307904d" -dependencies = [ - "darling 0.23.0", - "proc-macro2", - "quote", - "serde_json", - "syn", -] - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - [[package]] name = "rustc-hash" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" - -[[package]] -name = "rustc_version" -version = "0.4.1" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - -[[package]] -name = "rustix" -version = "0.38.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" -dependencies = [ - "bitflags 2.13.0", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", -] +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" [[package]] name = "rustix" -version = "1.1.3" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "errno", "libc", - "linux-raw-sys 0.11.0", + "linux-raw-sys", "windows-sys 0.61.2", ] [[package]] name = "rustls" -version = "0.23.35" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "log", @@ -5295,9 +3120,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.13.0" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94182ad936a0c91c324cd46c6511b9510ed16af436d7b5bab34beab0afd55f7a" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" dependencies = [ "web-time", "zeroize", @@ -5305,9 +3130,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.8" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ffdfa2f5286e2247234e03f680868ac2815974dc39e00ea15adc445d0aafe52" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -5342,9 +3167,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12e4fc1331357a7afc6d52d637796a946b1efaaca07c914132f8fd4fd69d595f" dependencies = [ "ahash", - "bitflags 2.13.0", - "indexmap 2.14.0", - "itertools 0.14.0", + "bitflags 2.13.2", + "indexmap 2.14.2", + "itertools", "log", "malachite-bigint", "memchr", @@ -5355,7 +3180,7 @@ dependencies = [ "rustpython-ruff_python_ast", "rustpython-ruff_text_size", "rustpython-wtf8", - "thiserror 2.0.18", + "thiserror 2.0.21", "unicode_names2 2.0.0", ] @@ -5366,10 +3191,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f3c0808a170ea900e0489a06d6aa04ce5d27d62b347836c2f98df958f47f243" dependencies = [ "ascii", - "bitflags 2.13.0", + "bitflags 2.13.2", "cfg-if", "getrandom 0.3.4", - "itertools 0.14.0", + "itertools", "libc", "lock_api", "malachite-base", @@ -5399,7 +3224,7 @@ dependencies = [ "rustpython-ruff_python_parser", "rustpython-ruff_source_file", "rustpython-ruff_text_size", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -5408,9 +3233,9 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9f18ba67b55aec49c3e2d223bbdcacff0d7e0f5d304fb0e64b044b8dca13c7c" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "bitflagset", - "itertools 0.14.0", + "itertools", "lz4_flex", "malachite-bigint", "num-complex", @@ -5426,7 +3251,7 @@ checksum = "6ba6c04350bee9e54b241b93675a0558c2b33fe982213e47a6da0924898af0f2" dependencies = [ "rustpython-compiler", "rustpython-derive-impl", - "syn", + "syn 2.0.119", ] [[package]] @@ -5435,13 +3260,13 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "322d64ea8a21d52cd769db0f6190b6e7c17963b13c8c17f39d7364e68af96731" dependencies = [ - "itertools 0.14.0", + "itertools", "maplit", "proc-macro2", "quote", "rustpython-compiler-core", "rustpython-doc", - "syn", + "syn 2.0.119", "syn-ext", "textwrap", ] @@ -5485,16 +3310,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f021ff72cabf5e2cd6d8ec8813d376a8445a228dc610ab56c27bd9054cda70d4" dependencies = [ "aho-corasick", - "bitflags 2.13.0", + "bitflags 2.13.2", "compact_str", "get-size2", "is-macro", "memchr", - "rustc-hash 2.1.1", + "rustc-hash", "rustpython-ruff_python_trivia", "rustpython-ruff_source_file", "rustpython-ruff_text_size", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -5503,12 +3328,12 @@ version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01e6ee78bd9671fb5766664b2695fe1f2a92a961f4d9101646c570d8acdb1e0b" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "bstr", "compact_str", "get-size2", "memchr", - "rustc-hash 2.1.1", + "rustc-hash", "rustpython-ruff_python_ast", "rustpython-ruff_python_trivia", "rustpython-ruff_text_size", @@ -5524,7 +3349,7 @@ version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "79e7cfd1056f3a02ff0d2d0e4474286ca963260782f878b7b81c1dd87432e682" dependencies = [ - "itertools 0.14.0", + "itertools", "rustpython-ruff_source_file", "rustpython-ruff_text_size", "unicode-ident", @@ -5555,7 +3380,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad4b7bd82b2a531f7c2ad96864ce11285959fc7d8524f1ba54db8ce3a23a3d2c" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "num_enum", "optional", "rustpython-wtf8", @@ -5586,8 +3411,8 @@ dependencies = [ "gethostname", "hex", "hmac", - "indexmap 2.14.0", - "itertools 0.14.0", + "indexmap 2.14.2", + "itertools", "libc", "liblzma", "liblzma-sys", @@ -5608,8 +3433,8 @@ dependencies = [ "pbkdf2", "phf 0.13.1", "pymath", - "rand_core 0.9.3", - "rustix 1.1.3", + "rand_core 0.9.5", + "rustix", "rustpython-common", "rustpython-derive", "rustpython-ruff_python_ast", @@ -5621,8 +3446,8 @@ dependencies = [ "sha-1", "sha2", "sha3", - "socket2 0.6.4", - "system-configuration 0.7.0", + "socket2 0.6.5", + "system-configuration", "termios", "ucd", "unic-char-property", @@ -5646,7 +3471,7 @@ checksum = "1880770161cef896bf9c7e065dae574e3b4c3cf6172e485f1ce86f0483816ab2" dependencies = [ "ahash", "ascii", - "bitflags 2.13.0", + "bitflags 2.13.2", "bstr", "caseless", "cfg-if", @@ -5659,13 +3484,13 @@ dependencies = [ "glob", "half", "hex", - "indexmap 2.14.0", + "indexmap 2.14.2", "is-macro", - "itertools 0.14.0", + "itertools", "junction", "libc", "libffi", - "libloading 0.9.0", + "libloading", "log", "malachite-bigint", "memchr", @@ -5680,7 +3505,7 @@ dependencies = [ "paste", "psm", "result-like", - "rustix 1.1.3", + "rustix", "rustpython-codegen", "rustpython-common", "rustpython-compiler", @@ -5695,9 +3520,9 @@ dependencies = [ "scoped-tls", "scopeguard", "static_assertions", - "strum 0.28.0", - "strum_macros 0.28.0", - "thiserror 2.0.18", + "strum", + "strum_macros", + "thiserror 2.0.21", "timsort", "uname", "unic-ucd-bidi", @@ -5717,15 +3542,15 @@ checksum = "ada88d2f69ff5516d69e0f3294e9db2ff8ee71a15291b8f3f8584f07ad1ca28d" dependencies = [ "ascii", "bstr", - "itertools 0.14.0", + "itertools", "memchr", ] [[package]] name = "rustversion" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "rustyline" @@ -5733,7 +3558,7 @@ version = "17.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e902948a25149d50edc1a8e0141aad50f54e22ba83ff988cf8f7c9ef07f50564" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "cfg-if", "clipboard-win", "fd-lock", @@ -5744,7 +3569,7 @@ dependencies = [ "nix 0.30.1", "radix_trie", "unicode-segmentation", - "unicode-width 0.2.2", + "unicode-width", "utf8parse", "windows-sys 0.60.2", ] @@ -5757,9 +3582,9 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] name = "safe_arch" -version = "1.0.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f7caad094bd561859bcd467734a720c3c1f5d1f338995351fefe2190c45efed" +checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f" dependencies = [ "bytemuck", ] @@ -5775,9 +3600,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -5794,40 +3619,11 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "security-framework" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags 2.13.0", - "core-foundation 0.9.4", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -5835,63 +3631,42 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] name = "serde_json" -version = "1.0.145" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ - "indexmap 2.14.0", "itoa", "memchr", - "ryu", - "serde", - "serde_core", -] - -[[package]] -name = "serde_path_to_error" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" -dependencies = [ - "itoa", "serde", "serde_core", + "zmij", ] [[package]] name = "serde_spanned" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" -dependencies = [ - "serde", -] - -[[package]] -name = "serde_spanned" -version = "1.1.1" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" dependencies = [ "serde_core", ] @@ -5902,21 +3677,10 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serial2" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eb6ea5562eeaed6936b8b54e086aa0f88b9e5b1bef45beb038e2519fa1185b1" -dependencies = [ - "cfg-if", - "libc", - "windows-sys 0.61.2", + "form_urlencoded", + "itoa", + "ryu", + "serde", ] [[package]] @@ -5930,17 +3694,6 @@ dependencies = [ "digest", ] -[[package]] -name = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest", -] - [[package]] name = "sha2" version = "0.10.9" @@ -5971,48 +3724,11 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "shared_library" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" -dependencies = [ - "lazy_static", - "libc", -] - -[[package]] -name = "shell-words" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" - [[package]] name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "signal-hook" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" -dependencies = [ - "libc", - "signal-hook-registry", -] - -[[package]] -name = "signal-hook-mio" -version = "0.2.5" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" -dependencies = [ - "libc", - "mio", - "signal-hook", -] +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "signal-hook-registry" @@ -6024,101 +3740,23 @@ dependencies = [ "libc", ] -[[package]] -name = "simd-adler32" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" - -[[package]] -name = "simd_cesu8" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" -dependencies = [ - "rustc_version", - "simdutf8", -] - -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - [[package]] name = "siphasher" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" [[package]] name = "slab" -version = "0.4.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" - -[[package]] -name = "slotmap" -version = "1.1.1" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" -dependencies = [ - "version_check", -] +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" - -[[package]] -name = "smithay-client-toolkit" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" -dependencies = [ - "bitflags 2.13.0", - "calloop 0.14.4", - "calloop-wayland-source", - "cursor-icon", - "libc", - "log", - "memmap2", - "rustix 1.1.3", - "thiserror 2.0.18", - "wayland-backend", - "wayland-client", - "wayland-csd-frame", - "wayland-cursor", - "wayland-protocols", - "wayland-protocols-experimental", - "wayland-protocols-misc", - "wayland-protocols-wlr", - "wayland-scanner", - "xkeysym", -] - -[[package]] -name = "smithay-clipboard" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" -dependencies = [ - "libc", - "smithay-client-toolkit", - "wayland-backend", -] - -[[package]] -name = "smol_str" -version = "0.2.2" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" -dependencies = [ - "serde", -] +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "socket2" @@ -6132,59 +3770,14 @@ dependencies = [ [[package]] name = "socket2" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", "windows-sys 0.61.2", ] -[[package]] -name = "socks" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0c3dbbd9ae980613c6dd8e28a9407b50509d3803b57624d5dfe8315218cd58b" -dependencies = [ - "byteorder", - "libc", - "winapi", -] - -[[package]] -name = "spirv" -version = "0.3.0+sdk-1.3.268.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844" -dependencies = [ - "bitflags 2.13.0", -] - -[[package]] -name = "spm_precompiled" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326" -dependencies = [ - "base64 0.13.1", - "nom", - "serde", - "unicode-segmentation", -] - -[[package]] -name = "sse-stream" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3962b63f038885f15bce2c6e02c0e7925c072f1ac86bb60fd44c5c6b762fb72" -dependencies = [ - "bytes", - "futures-util", - "http-body", - "http-body-util", - "pin-project-lite", -] - [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -6197,55 +3790,18 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "streaming-iterator" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" - -[[package]] -name = "strip-ansi-escapes" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025" -dependencies = [ - "vte", -] - [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "strum" -version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" -dependencies = [ - "strum_macros 0.26.4", -] - [[package]] name = "strum" version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" -[[package]] -name = "strum_macros" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "rustversion", - "syn", -] - [[package]] name = "strum_macros" version = "0.28.0" @@ -6255,7 +3811,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -6266,9 +3822,20 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.110" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a99801b5bd34ede4cf3fc688c5919368fea4e4814a4664359503e6015b280aea" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -6277,13 +3844,13 @@ dependencies = [ [[package]] name = "syn-ext" -version = "0.5.0" +version = "0.5.1+deprecated" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b126de4ef6c2a628a68609dd00733766c3b015894698a438ebdf374933fc31d1" +checksum = "a0d85a9541ea8696f63d423c4f13cc186980770d35a0a8a4e1939011b09c780f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -6297,24 +3864,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn", -] - -[[package]] -name = "system-configuration" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" -dependencies = [ - "bitflags 2.13.0", - "core-foundation 0.9.4", - "system-configuration-sys", + "syn 3.0.9", ] [[package]] @@ -6323,8 +3879,8 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ - "bitflags 2.13.0", - "core-foundation 0.9.4", + "bitflags 2.13.2", + "core-foundation", "system-configuration-sys", ] @@ -6346,26 +3902,17 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" [[package]] name = "tempfile" -version = "3.24.0" +version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", - "rustix 1.1.3", + "rustix", "windows-sys 0.61.2", ] -[[package]] -name = "termcolor" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" -dependencies = [ - "winapi-util", -] - [[package]] name = "termios" version = "0.3.3" @@ -6377,9 +3924,9 @@ dependencies = [ [[package]] name = "textwrap" -version = "0.16.2" +version = "0.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" +checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49" [[package]] name = "thiserror" @@ -6392,11 +3939,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.21", ] [[package]] @@ -6407,72 +3954,47 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if", ] -[[package]] -name = "tiff" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba1310fcea54c6a9a4fd1aad794ecc02c31682f6bfbecdf460bf19533eed1e3e" -dependencies = [ - "flate2", - "jpeg-decoder", - "weezl", -] - [[package]] name = "time" -version = "0.3.44" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", - "itoa", - "libc", "num-conv", - "num_threads", "powerfmt", - "serde", + "serde_core", "time-core", - "time-macros", ] [[package]] name = "time-core" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" - -[[package]] -name = "time-macros" -version = "0.2.24" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" -dependencies = [ - "num-conv", - "time-core", -] +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" [[package]] name = "timsort" @@ -6482,9 +4004,9 @@ checksum = "639ce8ef6d2ba56be0383a94dd13b92138d58de44c62618303bb798fa92bdc00" [[package]] name = "tinystr" -version = "0.8.2" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -6492,96 +4014,42 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokenizers" -version = "0.21.4" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a620b996116a59e184c2fa2dfd8251ea34a36d0a514758c6f966386bd2e03476" -dependencies = [ - "ahash", - "aho-corasick", - "compact_str", - "dary_heap", - "derive_builder", - "esaxx-rs", - "getrandom 0.3.4", - "hf-hub", - "indicatif", - "itertools 0.14.0", - "log", - "macro_rules_attribute", - "monostate", - "onig", - "paste", - "rand 0.9.2", - "rayon", - "rayon-cond", - "regex", - "regex-syntax", - "serde", - "serde_json", - "spm_precompiled", - "thiserror 2.0.18", - "unicode-normalization-alignments", - "unicode-segmentation", - "unicode_categories", -] +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.48.0" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", "mio", "pin-project-lite", "signal-hook-registry", - "socket2 0.6.4", + "socket2 0.6.5", "tokio-macros", "windows-sys 0.61.2", ] [[package]] name = "tokio-macros" -version = "2.6.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn", -] - -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", + "syn 3.0.9", ] [[package]] name = "tokio-rustls" -version = "0.26.4" +version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ "rustls", "tokio", @@ -6589,9 +4057,9 @@ dependencies = [ [[package]] name = "tokio-stream" -version = "0.1.17" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" dependencies = [ "futures-core", "pin-project-lite", @@ -6600,12 +4068,10 @@ dependencies = [ [[package]] name = "tokio-test" -version = "0.4.4" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2468baabc3311435b55dd935f702f42cd1b8abb7e754fb7dfb16bd36aa88f9f7" +checksum = "12bc5db7778a8e08ee255090861e0e7aac55e784300077e7ed293c7be36168b2" dependencies = [ - "async-stream", - "bytes", "futures-core", "tokio", "tokio-stream", @@ -6613,109 +4079,57 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.17" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", "futures-sink", "futures-util", + "libc", "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" -dependencies = [ - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.11", - "toml_edit 0.22.27", -] - -[[package]] -name = "toml" -version = "1.1.2+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee" -dependencies = [ - "indexmap 2.14.0", - "serde_core", - "serde_spanned 1.1.1", - "toml_datetime 1.1.1+spec-1.1.0", - "toml_parser", - "toml_writer", - "winnow 1.0.3", -] - -[[package]] -name = "toml_datetime" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" -dependencies = [ - "serde", + "tokio", ] [[package]] -name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +name = "toml" +version = "1.2.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" dependencies = [ + "indexmap 2.14.2", "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", ] [[package]] -name = "toml_edit" -version = "0.22.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" -dependencies = [ - "indexmap 2.14.0", - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.11", - "toml_write", - "winnow 0.7.15", -] - -[[package]] -name = "toml_edit" -version = "0.25.12+spec-1.1.0" +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ - "indexmap 2.14.0", - "toml_datetime 1.1.1+spec-1.1.0", - "toml_parser", - "winnow 1.0.3", + "serde_core", ] [[package]] name = "toml_parser" -version = "1.1.2+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ - "winnow 1.0.3", + "winnow", ] -[[package]] -name = "toml_write" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" - [[package]] name = "toml_writer" -version = "1.1.1+spec-1.1.0" +version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" [[package]] name = "tonic" @@ -6758,7 +4172,7 @@ dependencies = [ "indexmap 1.9.3", "pin-project", "pin-project-lite", - "rand 0.8.5", + "rand 0.8.8", "slab", "tokio", "tokio-util", @@ -6769,9 +4183,9 @@ dependencies = [ [[package]] name = "tower" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", @@ -6788,13 +4202,13 @@ version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "bytes", "futures-util", "http", "http-body", "pin-project-lite", - "tower 0.5.2", + "tower 0.5.3", "tower-layer", "tower-service", "url", @@ -6814,11 +4228,10 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" -version = "0.1.41" +version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ - "log", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -6826,20 +4239,20 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.30" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "tracing-core" -version = "0.1.34" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", "valuable", @@ -6886,9 +4299,9 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.3.20" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" dependencies = [ "matchers", "nu-ansi-term", @@ -6903,68 +4316,23 @@ dependencies = [ "tracing-serde", ] -[[package]] -name = "tree-sitter" -version = "0.25.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87" -dependencies = [ - "cc", - "regex", - "regex-syntax", - "serde_json", - "streaming-iterator", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-bash" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5ec769279cc91b561d3df0d8a5deb26b0ad40d183127f409494d6d8fc53062" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-language" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "009994f150cc0cd50ff54917d5bc8bffe8cad10ca10d81c34da2ec421ae61782" - [[package]] name = "try-lock" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" -[[package]] -name = "ttf-parser" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" - [[package]] name = "twox-hash" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c" - -[[package]] -name = "type-map" -version = "0.5.1" +version = "2.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" -dependencies = [ - "rustc-hash 2.1.1", -] +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" [[package]] name = "typenum" -version = "1.19.0" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "ucd" @@ -7100,57 +4468,30 @@ checksum = "061dbb8cc7f108532b6087a0065eff575e892a4bcb503dc57323a197457cc202" [[package]] name = "unicode-ident" -version = "1.0.22" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-normalization-alignments" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de" -dependencies = [ - "smallvec", -] - [[package]] name = "unicode-segmentation" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" - -[[package]] -name = "unicode-width" -version = "0.1.14" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] name = "unicode-width" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" - -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - -[[package]] -name = "unicode_categories" -version = "0.1.1" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "unicode_names2" @@ -7181,7 +4522,7 @@ dependencies = [ "getopts", "log", "phf_codegen", - "rand 0.8.5", + "rand 0.8.8", ] [[package]] @@ -7191,7 +4532,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1262662dc96937c71115228ce2e1d30f41db71a7a45d3459e98783ef94052214" dependencies = [ "phf_codegen", - "rand 0.8.5", + "rand 0.8.8", ] [[package]] @@ -7212,31 +4553,11 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" -[[package]] -name = "ureq" -version = "2.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" -dependencies = [ - "base64 0.22.1", - "flate2", - "log", - "native-tls", - "once_cell", - "rustls", - "rustls-pki-types", - "serde", - "serde_json", - "socks", - "url", - "webpki-roots 0.26.11", -] - [[package]] name = "url" -version = "2.5.7" +version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" dependencies = [ "form_urlencoded", "idna", @@ -7246,9 +4567,12 @@ dependencies = [ [[package]] name = "utf8_iter" -version = "1.0.4" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] [[package]] name = "utf8parse" @@ -7256,17 +4580,22 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "uuid" -version = "1.23.4" +version = "1.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53" +checksum = "4a06f08a856b009bc7bbaf7d3e79808595d032dd19074c0c2ef26e49e03e6bdc" dependencies = [ "atomic", "getrandom 0.4.3", "js-sys", - "rand 0.10.2", - "serde_core", + "rand 0.10.3", "wasm-bindgen", ] @@ -7276,64 +4605,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - -[[package]] -name = "vergen" -version = "9.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b2bf58be11fc9414104c6d3a2e464163db5ef74b12296bda593cac37b6e4777" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", - "vergen-lib", -] - -[[package]] -name = "vergen-gitcl" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9dfc1de6eb2e08a4ddf152f1b179529638bedc0ea95e6d667c014506377aefe" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", - "time", - "vergen", - "vergen-lib", -] - -[[package]] -name = "vergen-lib" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b07e6010c0f3e59fcb164e0163834597da68d1f864e2b8ca49f74de01e9c166" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", -] - [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "vte" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "231fdcd7ef3037e8330d8e17e61011a2c244126acc0a982f4040ac3f9f0bc077" -dependencies = [ - "memchr", -] - [[package]] name = "walkdir" version = "2.5.0" @@ -7346,9 +4623,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -7361,393 +4638,111 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasip2" -version = "1.0.1+wasi-0.2.4" +version = "1.0.4+wasi-0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.125" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ddb3f79143bced6de84270411622a2699cee572fc0875aeaf1e7867cf9fca1a" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.75" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "503b14d284f2c8dac03b819967e155ea753f573586193b2b2c95990cb5d69280" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.125" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e21a184b13fb19e157296e2c46056aec9092264fab83e4ba59e68c61b323c3d" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.125" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fecefd9c35bd935a20fc3fc344b5f29138961e4f47fb03297d88f2587afb5ebd" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.125" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23939e44bb9a5d7576fa2b563dc2e136628f1224e88a8deed09e04858b77871f" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm-streams" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "wasm-streams" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "wayland-backend" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2857dd20b54e916ec7253b3d6b4d5c4d7d4ca2c33c2e11c6c76a99bd8744755d" -dependencies = [ - "cc", - "downcast-rs", - "rustix 1.1.3", - "scoped-tls", - "smallvec", - "wayland-sys", -] - -[[package]] -name = "wayland-client" -version = "0.31.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645c7c96bb74690c3189b5c9cb4ca1627062bb23693a4fad9d8c3de958260144" -dependencies = [ - "bitflags 2.13.0", - "rustix 1.1.3", - "wayland-backend", - "wayland-scanner", -] - -[[package]] -name = "wayland-csd-frame" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" -dependencies = [ - "bitflags 2.13.0", - "cursor-icon", - "wayland-backend", -] - -[[package]] -name = "wayland-cursor" -version = "0.31.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" -dependencies = [ - "rustix 1.1.3", - "wayland-client", - "xcursor", -] - -[[package]] -name = "wayland-protocols" -version = "0.32.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" -dependencies = [ - "bitflags 2.13.0", - "wayland-backend", - "wayland-client", - "wayland-scanner", -] - -[[package]] -name = "wayland-protocols-experimental" -version = "20250721.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1" -dependencies = [ - "bitflags 2.13.0", - "wayland-backend", - "wayland-client", - "wayland-protocols", - "wayland-scanner", -] - -[[package]] -name = "wayland-protocols-misc" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" -dependencies = [ - "bitflags 2.13.0", - "wayland-backend", - "wayland-client", - "wayland-protocols", - "wayland-scanner", -] - -[[package]] -name = "wayland-protocols-wlr" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" -dependencies = [ - "bitflags 2.13.0", - "wayland-backend", - "wayland-client", - "wayland-protocols", - "wayland-scanner", -] - -[[package]] -name = "wayland-scanner" -version = "0.31.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c324a910fd86ebdc364a3e61ec1f11737d3b1d6c273c0239ee8ff4bc0d24b4a" -dependencies = [ - "proc-macro2", - "quick-xml", - "quote", -] - -[[package]] -name = "wayland-sys" -version = "0.31.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" -dependencies = [ - "dlib", - "log", - "once_cell", - "pkg-config", -] - -[[package]] -name = "web-sys" -version = "0.3.102" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6430a72df5eb332242960fe84b3002a241163998241eb596d4f739b9757061d" -dependencies = [ - "js-sys", - "wasm-bindgen", + "wasm-bindgen-macro", + "wasm-bindgen-shared", ] [[package]] -name = "web-time" -version = "1.1.0" +name = "wasm-bindgen-futures" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] -name = "webbrowser" -version = "1.2.1" +name = "wasm-bindgen-macro" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fc95580916af1e68ff6a7be07446fc5db73ebf71cf092de939bbf5f7e189f72" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ - "core-foundation 0.10.0", - "jni", - "log", - "ndk-context", - "objc2 0.6.4", - "objc2-foundation 0.3.2", - "url", - "web-sys", + "quote", + "wasm-bindgen-macro-support", ] [[package]] -name = "webpki-roots" -version = "0.26.11" +name = "wasm-bindgen-macro-support" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ - "webpki-roots 1.0.4", + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", ] [[package]] -name = "webpki-roots" -version = "1.0.4" +name = "wasm-bindgen-shared" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2878ef029c47c6e8cf779119f20fcf52bde7ad42a731b2a304bc221df17571e" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ - "rustls-pki-types", + "unicode-ident", ] [[package]] -name = "weezl" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" - -[[package]] -name = "wgpu" -version = "24.0.5" +name = "web-sys" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b0b3436f0729f6cdf2e6e9201f3d39dc95813fad61d826c1ed07918b4539353" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ - "arrayvec", - "bitflags 2.13.0", - "cfg_aliases 0.2.1", - "document-features", "js-sys", - "log", - "parking_lot", - "profiling", - "raw-window-handle", - "smallvec", - "static_assertions", "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "wgpu-core", - "wgpu-hal", - "wgpu-types", -] - -[[package]] -name = "wgpu-core" -version = "24.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f0aa306497a238d169b9dc70659105b4a096859a34894544ca81719242e1499" -dependencies = [ - "arrayvec", - "bit-vec", - "bitflags 2.13.0", - "cfg_aliases 0.2.1", - "document-features", - "indexmap 2.14.0", - "log", - "naga", - "once_cell", - "parking_lot", - "profiling", - "raw-window-handle", - "rustc-hash 1.1.0", - "smallvec", - "thiserror 2.0.18", - "wgpu-hal", - "wgpu-types", ] [[package]] -name = "wgpu-hal" -version = "24.0.4" +name = "web-time" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f112f464674ca69f3533248508ee30cb84c67cf06c25ff6800685f5e0294e259" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" dependencies = [ - "android_system_properties", - "arrayvec", - "ash", - "bitflags 2.13.0", - "bytemuck", - "cfg_aliases 0.2.1", - "core-graphics-types", - "glow", - "glutin_wgl_sys", - "gpu-alloc", - "gpu-descriptor", "js-sys", - "khronos-egl", - "libc", - "libloading 0.8.9", - "log", - "metal", - "naga", - "ndk-sys 0.5.0+25.2.9519653", - "objc", - "once_cell", - "ordered-float", - "parking_lot", - "profiling", - "raw-window-handle", - "renderdoc-sys", - "rustc-hash 1.1.0", - "smallvec", - "thiserror 2.0.18", "wasm-bindgen", - "web-sys", - "wgpu-types", - "windows 0.58.0", ] [[package]] -name = "wgpu-types" -version = "24.0.0" +name = "webpki-roots" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50ac044c0e76c03a0378e7786ac505d010a873665e2d51383dcff8dd227dc69c" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" dependencies = [ - "bitflags 2.13.0", - "js-sys", - "log", - "web-sys", + "rustls-pki-types", ] [[package]] name = "which" -version = "8.0.4" +version = "8.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48d7cd18d4acb58fb3cdfe9ea54e6cd96a4e7d4cc45c56338b236e82dad47248" +checksum = "bae2f2b2b816647a1cab1acc91f5bd20812d53cb344382635ec2181940c8034f" dependencies = [ "libc", ] [[package]] name = "wide" -version = "1.5.0" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfdfe6a32973f2d1b268b8895845a8a96cac2f0191e72c27cc929036060dbf89" +checksum = "d920ac99c3c8edce110cb8d07dbb324d6d026011dce85b1e9355b70f0adacc4f" dependencies = [ "bytemuck", "safe_arch", @@ -7790,83 +4785,17 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows" -version = "0.58.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" -dependencies = [ - "windows-core 0.58.0", - "windows-targets 0.52.6", -] - -[[package]] -name = "windows" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" -dependencies = [ - "windows-collections", - "windows-core 0.62.2", - "windows-future", - "windows-numerics", -] - -[[package]] -name = "windows-collections" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" -dependencies = [ - "windows-core 0.62.2", -] - -[[package]] -name = "windows-core" -version = "0.58.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" -dependencies = [ - "windows-implement 0.58.0", - "windows-interface 0.58.0", - "windows-result 0.2.0", - "windows-strings 0.1.0", - "windows-targets 0.52.6", -] - [[package]] name = "windows-core" version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ - "windows-implement 0.60.2", - "windows-interface 0.59.3", - "windows-link 0.2.1", - "windows-result 0.4.1", - "windows-strings 0.5.1", -] - -[[package]] -name = "windows-future" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" -dependencies = [ - "windows-core 0.62.2", - "windows-link 0.2.1", - "windows-threading", -] - -[[package]] -name = "windows-implement" -version = "0.58.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" -dependencies = [ - "proc-macro2", - "quote", - "syn", + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", ] [[package]] @@ -7877,18 +4806,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn", -] - -[[package]] -name = "windows-interface" -version = "0.58.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" -dependencies = [ - "proc-macro2", - "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -7899,86 +4817,22 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] -[[package]] -name = "windows-link" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" - [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-numerics" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" -dependencies = [ - "windows-core 0.62.2", - "windows-link 0.2.1", -] - -[[package]] -name = "windows-registry" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e" -dependencies = [ - "windows-link 0.1.3", - "windows-result 0.3.4", - "windows-strings 0.4.2", -] - -[[package]] -name = "windows-result" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-result" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" -dependencies = [ - "windows-link 0.1.3", -] - [[package]] name = "windows-result" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-strings" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" -dependencies = [ - "windows-result 0.2.0", - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-strings" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" -dependencies = [ - "windows-link 0.1.3", + "windows-link", ] [[package]] @@ -7987,7 +4841,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -8023,7 +4877,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -8048,7 +4902,7 @@ version = "0.53.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ - "windows-link 0.2.1", + "windows-link", "windows_aarch64_gnullvm 0.53.1", "windows_aarch64_msvc 0.53.1", "windows_i686_gnu 0.53.1", @@ -8059,15 +4913,6 @@ dependencies = [ "windows_x86_64_msvc 0.53.1", ] -[[package]] -name = "windows-threading" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" -dependencies = [ - "windows-link 0.2.1", -] - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -8164,173 +5009,45 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" -[[package]] -name = "winit" -version = "0.30.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" -dependencies = [ - "android-activity", - "atomic-waker", - "bitflags 2.13.0", - "block2", - "bytemuck", - "calloop 0.13.0", - "cfg_aliases 0.2.1", - "concurrent-queue", - "core-foundation 0.9.4", - "core-graphics", - "cursor-icon", - "dpi", - "js-sys", - "libc", - "ndk", - "objc2 0.5.2", - "objc2-app-kit 0.2.2", - "objc2-foundation 0.2.2", - "objc2-ui-kit", - "orbclient", - "percent-encoding", - "pin-project", - "raw-window-handle", - "redox_syscall 0.4.1", - "rustix 0.38.44", - "smol_str", - "tracing", - "unicode-segmentation", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "web-time", - "windows-sys 0.52.0", - "x11-dl", - "x11rb", - "xkbcommon-dl", -] - -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" -dependencies = [ - "memchr", -] - [[package]] name = "winnow" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" -dependencies = [ - "memchr", -] - -[[package]] -name = "winreg" -version = "0.10.1" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" -dependencies = [ - "winapi", -] +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" [[package]] name = "winresource" -version = "0.1.31" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0986a8b1d586b7d3e4fe3d9ea39fb451ae22869dcea4aa109d287a374d866087" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" dependencies = [ - "toml 1.1.2+spec-1.1.0", + "toml", "version_check", ] [[package]] name = "wit-bindgen" -version = "0.46.0" +version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "writeable" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" - -[[package]] -name = "x11-dl" -version = "2.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" -dependencies = [ - "libc", - "once_cell", - "pkg-config", -] - -[[package]] -name = "x11rb" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" -dependencies = [ - "as-raw-xcb-connection", - "gethostname", - "libc", - "libloading 0.8.9", - "once_cell", - "rustix 1.1.3", - "x11rb-protocol", -] - -[[package]] -name = "x11rb-protocol" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" - -[[package]] -name = "xcursor" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b" - -[[package]] -name = "xkbcommon-dl" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" -dependencies = [ - "bitflags 2.13.0", - "dlib", - "log", - "once_cell", - "xkeysym", -] - -[[package]] -name = "xkeysym" -version = "0.2.1" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "xml" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "636f85e5ca6488e96401b61eb7de54f4e44755c988af0f52cf90230c312a1a89" - -[[package]] -name = "xml-rs" -version = "0.8.28" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f" +checksum = "2f45bb2c13fec6a6cb4c0f76a7e94839e110a14ec803ec2940777a94c347bc52" [[package]] name = "xxhash-rust" -version = "0.8.15" +version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3" +checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" [[package]] name = "yasna" @@ -8343,9 +5060,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.1" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -8354,68 +5071,68 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.1" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", "synstructure", ] [[package]] name = "zerocopy" -version = "0.8.27" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.27" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "zerofrom" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", "synstructure", ] [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] name = "zerotrie" -version = "0.2.3" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", "yoke", @@ -8424,9 +5141,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.5" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -8435,13 +5152,13 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.2" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -8452,21 +5169,12 @@ checksum = "40990edd51aae2c2b6907af74ffb635029d5788228222c4bb811e9351c0caad3" [[package]] name = "zlib-rs" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b142a20ec14a91d5bc708c1dc21b080c550113d8aa77afa29635673a65dd02c5" - -[[package]] -name = "zune-core" -version = "0.4.12" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" [[package]] -name = "zune-jpeg" -version = "0.4.21" +name = "zmij" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" -dependencies = [ - "zune-core", -] +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index de3d51da6..7f2079b65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,25 +1,19 @@ [workspace] members = [ "crates/pulsing-actor", - "crates/pulsing-bench", - "crates/pulsing-bench-py", "crates/pulsing-py", - "crates/pulsing-forge", "crates/pulsing-bindings-core", "crates/pulsing-rpymod", "crates/pulsing-workspace", "crates/pulsing-cli", - "crates/pulsing-gui", ] -# `cargo build` without -p skips benches / PyO3-only crates (faster default link graph). +# `cargo build` without -p skips the PyO3 extension. default-members = [ "crates/pulsing-actor", - "crates/pulsing-forge", "crates/pulsing-bindings-core", "crates/pulsing-rpymod", "crates/pulsing-workspace", "crates/pulsing-cli", - "crates/pulsing-gui", ] resolver = "3" @@ -34,7 +28,7 @@ description = "Pulsing - Distributed Actor Framework" authors = ["Reiase "] license = "Apache-2.0" repository = "https://github.com/DeepLink-org/Pulsing" -keywords = ["actor", "distributed", "async", "inference"] +keywords = ["actor", "distributed", "async"] [workspace.dependencies] pulsing-actor = { path = "crates/pulsing-actor" } @@ -55,12 +49,10 @@ tokio = { version = "1", default-features = false, features = [ ] } tokio-util = { version = "0.7", default-features = false, features = ["codec", "net", "rt"] } tokio-stream = { version = "0.1", default-features = false } -futures-util = { version = "0.3", default-features = false, features = ["std", "async-await"] } # Serialization serde = { version = "1", features = ["derive"] } serde_json = { version = "1" } -serde_with = "3.9" bytes = { version = "1" } bincode = "1.3" @@ -91,19 +83,10 @@ opentelemetry-otlp = { version = "0.27", default-features = false, features = [ "grpc-tonic", "trace", ] } -log = { version = "0.4", default-features = false } -env_logger = { version = "0.11", default-features = false, features = ["humantime", "auto-color"] } # Utilities uuid = { version = "1", features = ["v4", "fast-rng"] } rand = { version = "0.9" } -rand_distr = "0.5" -chrono = "0.4" -colored = "2.1" -humantime = "2.1" -indicatif = "0.17" -rayon = "1.10" -sysinfo = "0.33" # HTTP # axum = { version = "0.8", features = ["macros"] } @@ -115,7 +98,6 @@ reqwest = { version = "0.12", default-features = false, features = [ "rustls-tls", "http2", ] } -reqwest-eventsource = "0.6" # TLS rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "std"] } @@ -125,23 +107,11 @@ aws-lc-rs = { version = "1.8" } rustls-pemfile = { version = "2" } time = { version = "0.3" } -# CLI (removed clap - now using Python hyperparameter) -strum_macros = "0.27" - # Testing tokio-test = "0.4" -mockito = "1.5" -tabled = "=0.14" # Other -tokenizers = { version = "0.21", features = ["http"] } -hf-hub = { version = "0.4", features = ["tokio"] } -vergen-gitcl = "1.0" -pkcs8 = { version = "0.10", features = ["alloc"] } -sha2 = "0.10" probing-memtable = "0.2.5" -ed25519-dalek = { version = "2.0", features = ["pkcs8"] } -der = "0.7" # Dev (`just dev`, `cargo check`): compile speed + lean intermediates. # debug=1 → line tables only (breakpoints/backtraces without full DWARF). diff --git a/Justfile b/Justfile index b92de5f29..2edac6bf3 100644 --- a/Justfile +++ b/Justfile @@ -16,16 +16,12 @@ default: dev dev: @echo "==> Path A: maturin develop (extension-module, profile.dev)..." maturin develop - @echo "==> Building benchmarks..." - maturin develop --manifest-path crates/pulsing-bench-py/Cargo.toml @echo "Ready! Use: python -m pulsing.cli | just build-release for wheel + binary" # Same as `dev` but install with [profile.release] (smaller .so, slower compile) dev-release: @echo "==> Path A: maturin develop --release (profile.release)..." maturin develop --release - @echo "==> Building benchmarks (release)..." - maturin develop --release --manifest-path crates/pulsing-bench-py/Cargo.toml @echo "Ready! (release profile)" # Build pulsing-cli debug binary (RustPython path; profile.dev) @@ -76,7 +72,7 @@ check-quick: check-fmt lint @echo "✅ Format and lint checks passed!" # Python sources for ruff (docs markdown uses docs/pyproject.toml separately) -ruff_paths := "python tests examples benchmarks crates/pulsing-bench-py" +ruff_paths := "python tests examples" # 检查代码格式 (不修改) check-fmt: @@ -90,7 +86,7 @@ test: test-rust test-python # Run Rust tests (pulsing-py via maturin; pulsing-cli via separate `-p` graph) test-rust: - cargo test --workspace --exclude pulsing-bench-py --exclude pulsing-py --exclude pulsing-cli + cargo test --workspace --exclude pulsing-py --exclude pulsing-cli cargo test -p pulsing-cli # Run Python tests @@ -112,7 +108,7 @@ fmt: # Lint all code lint: - cargo clippy --workspace --exclude pulsing-py --exclude pulsing-bench-py --all-targets -- -D warnings + cargo clippy --workspace --exclude pulsing-py --all-targets -- -D warnings ruff check {{ruff_paths}} # ============================================================================= @@ -131,17 +127,17 @@ cov: cov-rust cov-python # Rust coverage with HTML report cov-rust: @echo "Running Rust tests with coverage..." - cargo llvm-cov --workspace --exclude pulsing-py --exclude pulsing-bench-py --html + cargo llvm-cov --workspace --exclude pulsing-py --html @echo "Report: target/llvm-cov/html/index.html" # Rust coverage summary (terminal only, no HTML) cov-rust-summary: - cargo llvm-cov --workspace --exclude pulsing-py --exclude pulsing-bench-py + cargo llvm-cov --workspace --exclude pulsing-py # Rust coverage with nightly (支持 #[coverage(off)] 标记,但可能不稳定) cov-rust-nightly: @echo "Running Rust tests with coverage (nightly)..." - cargo +nightly llvm-cov --workspace --exclude pulsing-py --exclude pulsing-bench-py --html + cargo +nightly llvm-cov --workspace --exclude pulsing-py --html @echo "Report: target/llvm-cov/html/index.html" # Python coverage with HTML report @@ -262,7 +258,7 @@ ci-test: export PATH="$HOME/.local/bin:$PATH" # Install wheel and dependencies using uv (preferred) or pip if command -v uv &> /dev/null; then - # Main package only — pulsing-bench must not overwrite pulsing/__init__.py + # Install the actor runtime wheel. uv pip install --system dist/pulsing-*.whl pytest pytest-asyncio # Use same interpreter as above (where wheel was installed); do not use uv run (project venv has no pulsing) for py in python3.12 python3.11 python3.10 python3 python; do diff --git a/README.md b/README.md index f0d09107f..419f35b8e 100644 --- a/README.md +++ b/README.md @@ -1,299 +1,106 @@ # Pulsing -[![CI](https://github.com/DeepLink-org/pulsing/actions/workflows/ci.yml/badge.svg)](https://github.com/DeepLink-org/pulsing/actions/workflows/ci.yml) -[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) -[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/) -[![Rust](https://img.shields.io/badge/rust-1.75+-orange.svg)](https://www.rust-lang.org/) +[中文文档](README.zh.md) -**[中文文档](README.zh.md)** +A distributed actor runtime built in Rust, designed for Python. +Pulsing provides location-transparent actor calls, streaming messages, and +built-in cluster discovery without Redis or etcd. -**Backbone for distributed AI systems.** - -**Actor runtime. Streaming-first. Zero dependencies. Built-in discovery.** - -Pulsing is a distributed actor runtime built in Rust, designed for Python. Connect AI agents and services across machines — no Redis, no etcd, no YAML. Just `pip install pulsing`. - -🚀 **Zero Dependencies** — Pure Rust + Tokio, no NATS/etcd/Redis - -⚡ **Streaming-first** — Native support for streaming responses, built for LLM token generation - -🌐 **Built-in Discovery** — SWIM/Gossip protocol for automatic cluster management - -🔀 **Same API Everywhere** — Same `await actor.method()` for local and remote Actors - -## 🚀 Get Started in 5 Minutes - -### Installation +## Install ```bash pip install pulsing ``` -### Your First Multi-Agent Application +## First actor ```python import asyncio import pulsing as pul -from pulsing.agent import runtime + @pul.remote -class Greeter: - def __init__(self, display_name: str): - self.display_name = display_name +class Counter: + def __init__(self, value=0): + self.value = value - def greet(self, message: str) -> str: - return f"[{self.display_name}] Received: {message}" + def inc(self): + self.value += 1 + return self.value - async def chat_with(self, peer_name: str, message: str) -> str: - # Use Greeter.resolve() to get a typed proxy - peer = await Greeter.resolve(peer_name) - return await peer.greet(f"From {self.display_name}: {message}") async def main(): - async with runtime(): - # Create two agents - alice = await Greeter.spawn(display_name="Alice", name="alice") - bob = await Greeter.spawn(display_name="Bob", name="bob") + await pul.init() + try: + counter = await Counter.spawn(value=0, name="counter") + print(await counter.inc()) # 1 + finally: + await pul.shutdown() - # Agent communication - reply = await alice.chat_with("bob", "Hello!") - print(reply) # [Bob] Received: From Alice: Hello! asyncio.run(main()) ``` -**That's it!** `@pul.remote` turns a regular class into a distributed Actor, and `Greeter.resolve()` enables agents to discover and communicate with each other. - -## 💡 I want to... - -| Scenario | Example | Description | -|----------|---------|-------------| -| **Quick start** | `examples/quickstart/` | Get started in 10 lines | -| **Multi-Agent collaboration** | `examples/agent/pulsing/` | AI debate, brainstorming, role-playing | -| **Distributed LLM inference** | `pulsing actor router/vllm` | GPU cluster inference service | -| **Integrate AutoGen** | `examples/agent/autogen/` | One line to go distributed | -| **Integrate LangGraph** | `examples/agent/langgraph/` | Execute graphs across nodes | -| **Agent workspace CLI** | `pulsing agent init` | [Pulsing Agent](examples/agent/workspace-demo.md) — multi-agent in your repo | -| **Agent tools & environment** | `examples/python/forge_minimal.py` | [Pulsing Forge](docs/src/forge/index.md) — sandboxed shell, files, plan | - -## 🔨 Pulsing Forge - -**A general-purpose tool and environment runtime for AI agents** — run shell commands, edit files, and manage plans inside a configurable sandbox. Embed in any agent framework, or deploy isolated workers via Pulsing Actors. - -```python -from pulsing.forge import ForgeEnvironment - -env = ForgeEnvironment(cwd=".") -env.runtime().call_tool("shell_command", {"cmd": "pytest -q", "workdir": "."}) -``` - -Docs: [Forge chapter](docs/src/forge/index.md) · Package README: [python/pulsing/forge/README.md](python/pulsing/forge/README.md) - -## 🤖 Pulsing Agent - -**Workspace-scoped multi-agent SDK + CLI** — init a `.pulsing/` workspace, wake agents on the cluster, and collaborate with Forge tools. - -```bash -pip install pulsing[agent] -pulsing agent init -pulsing agent wake --agents guide -pulsing agent say guide "run pytest" -``` - -Docs: [workspace demo](examples/agent/workspace-demo.md) · SDK: `from pulsing.agent import Agent, spawn_agent` +For a cluster, initialize each node with `addr` and join using `seeds`. +Resolve named actors with `await Counter.resolve("counter")`. -## 🎯 Core Capabilities +## Scope -### 1. Multi-Agent Collaboration +- Actor mailboxes, lifecycle, supervision, and named actor discovery. +- Local and remote request/reply, one-way calls, and streaming responses. +- HTTP/2 transport, TLS, and opaque tensor-buffer transport. +- Python `@remote`, subprocess integration, queues, and pub/sub. +- CLI actor startup and cluster inspection. +- Workspace scaffolding, checkpoints, rollback, and Python workflows. -Multiple AI Agents working in parallel and communicating: +Inference servers, LLM clients, Forge tools and coding agents, the desktop GUI, +and benchmark modules are no longer bundled. Applications can implement their +own services on top of the actor API. -```python -from pulsing.agent import agent, runtime, llm - -@agent(role="Researcher", goal="Deep analysis") -class Researcher: - async def analyze(self, topic: str) -> str: - client = await llm() - return await client.ainvoke(f"Analyze: {topic}") - -@agent(role="Reviewer", goal="Evaluate proposals") -class Reviewer: - async def review(self, proposal: str) -> str: - client = await llm() - return await client.ainvoke(f"Review: {proposal}") - -async with runtime(): - researcher = await Researcher.spawn(name="researcher") - reviewer = await Reviewer.spawn(name="reviewer") - - # Parallel work and collaboration - analysis = await researcher.analyze("AI trends") - feedback = await reviewer.review(analysis) -``` +## CLI ```bash -# Run MBTI personality discussion example -python examples/agent/pulsing/mbti_discussion.py --mock --group-size 6 - -# Run parallel idea generation example -python examples/agent/pulsing/parallel_ideas_async.py --mock --n-ideas 5 +pulsing actor my_app.Counter --addr 0.0.0.0:8000 --name counter +pulsing inspect actors --endpoint 127.0.0.1:8000 +pulsing init --template minimal +pulsing checkpoint -m "working state" +pulsing history +pulsing rollback ``` -### 2. One Line to Distributed +The Rust CLI also supports `pulsing run [script.py]` (alias `workflow`). +Workflows execute once and return to the shell, without an LLM session. -Develop locally, scale seamlessly to clusters: +## Development -```python -# Standalone mode (development) -async with runtime(): - agent = await MyAgent.spawn(name="agent") - -# Distributed mode (production) — just add address -async with runtime(addr="0.0.0.0:8001"): - agent = await MyAgent.spawn(name="agent") - -# Other nodes auto-discover -async with runtime(addr="0.0.0.0:8002", seeds=["node1:8001"]): - agent = await resolve("agent") # Cross-node transparent call -``` - -### 3. LLM Inference Service - -Out-of-the-box GPU cluster inference: +Requires Python 3.10+ and a current stable Rust toolchain. The RustPython CLI +requires Rust 1.93 or newer. ```bash -# Start Router (OpenAI-compatible API) -pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 --http_port 8080 --model_name my-llm - -# Start vLLM Worker (can have multiple) -pulsing actor pulsing.serving.VllmWorker --model Qwen/Qwen2.5-0.5B --addr 0.0.0.0:8002 --seeds 127.0.0.1:8000 - -# Test -curl http://localhost:8080/v1/chat/completions \ - -d '{"model": "my-llm", "messages": [{"role": "user", "content": "Hello"}]}' -``` - -### 4. Agent Framework Integration - -Have existing AutoGen/LangGraph code? One-line migration: - -```python -# AutoGen: Replace runtime -from pulsing.autogen import PulsingRuntime -runtime = PulsingRuntime(addr="0.0.0.0:8000") - -# LangGraph: Wrap the graph -from pulsing.langgraph import with_pulsing -distributed_app = with_pulsing(app, seeds=["gpu-server:8001"]) -``` - -### 5. Fast TensorDict Transport - -`TensorMessage` carries opaque metadata and ordered, contiguous CPU buffers -without putting tensor payloads in the normal pickle envelope. The caller (for -example PulsingQueue) moves CUDA tensors to CPU, makes them contiguous, and -encodes dtype, shape, byte order, and TensorDict structure in metadata. Pulsing -only transports those bytes and buffers. - -```python -from array import array - -import pulsing as pul - -cpu_buffer = array("f", range(6)) -message = pul.TensorMessage( - metadata=b"...", # dtype, shape, byte order, and TensorDict structure - buffers=[memoryview(cpu_buffer).cast("B")], - version=1, -) -``` - -Clear-text remote connections use a pooled raw TCP path by default. It sends -the header, metadata, and original buffers with vectored I/O and reads every -payload directly into its final receive allocation. TLS and -`PULSING_TENSOR_TRANSPORT=http2` use the packed HTTP/2 compatibility path. - -See the [complete transport design](docs/src/design/tensor-message-transport.md) -and the [runnable TCP example](examples/python/tensor_message_fast_path.py). - -## 📚 Example Guide - -``` -examples/ -├── quickstart/ # ⭐ 5-minute quickstart -│ └── hello_agent.py # First Agent -├── agent/ -│ ├── pulsing/ # ⭐⭐ Multi-Agent apps -│ │ ├── mbti_discussion.py # MBTI personality discussion -│ │ └── parallel_ideas_async.py # Parallel idea generation -│ ├── autogen/ # AutoGen integration -│ └── langgraph/ # LangGraph integration -├── python/ # ⭐⭐ Basic examples -│ ├── ping_pong.py # Actor basics -│ ├── cluster.py # Cluster communication -│ ├── tensor_message_fast_path.py # Tensor transport -│ └── ... -└── rust/ # Rust examples -``` - -## 🔧 Technical Features - -- **Zero external dependencies**: Pure Rust + Tokio, no NATS/etcd/Redis needed -- **Gossip protocol**: Built-in SWIM protocol for node discovery and failure detection -- **Location transparency**: Same API for local and remote Actors -- **Streaming messages**: Native support for streaming requests/responses (LLM-ready) -- **Type safety**: Rust Behavior API provides compile-time message type checking - -## 📦 Project Structure - -``` -Pulsing/ -├── crates/ # Rust core -│ ├── pulsing-actor/ # Actor System -│ └── pulsing-py/ # Python bindings -├── python/pulsing/ # Python package -│ ├── actor/ # Actor API -│ ├── agent/ # Agent toolkit -│ ├── autogen/ # AutoGen integration -│ └── langgraph/ # LangGraph integration -├── examples/ # Example code -└── docs/ # Documentation -``` - -## 🛠️ Development - -### Prerequisites - -- [Rust](https://rustup.rs/) ≥ 1.75 -- Python ≥ 3.10 -- [uv](https://docs.astral.sh/uv/) (recommended package manager) -- [just](https://github.com/casey/just) (task runner: `cargo install just` or `brew install just`) - -### Quick Setup - -```bash -# 1. Install Python dependencies uv sync --extra dev - -# 2. Compile Rust core and install (run again after any Rust changes) uv run maturin develop +just test +just fmt +just lint ``` -### Common Commands +`just build-wheel` builds the Python wheel; `just build-binary` builds the +RustPython CLI. See [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow. -```bash -just dev # Compile and install in development mode -just test # Run all tests (Rust + Python) -just test-python # Python tests only -just fmt # Format code (Rust + Python) -just lint # Lint check -just check # Full pre-commit check (format + lint + test) -just cov # Generate coverage report -``` +## Project layout -See [CONTRIBUTING.md](CONTRIBUTING.md) for a detailed guide on the development workflow. +| Path | Purpose | +|------|---------| +| `crates/pulsing-actor/` | Actor runtime, discovery, transport | +| `crates/pulsing-py/` | CPython/PyO3 bindings | +| `crates/pulsing-rpymod/` | RustPython bindings | +| `crates/pulsing-bindings-core/` | Shared binding data types | +| `crates/pulsing-cli/` | Rust CLI | +| `crates/pulsing-workspace/` | Workspace scaffolding and journal | +| `python/pulsing/` | Python SDK and integrations | +| `examples/` | Actor and transport examples | +| `docs/` | Documentation | -## 📄 License +## License Apache-2.0 diff --git a/README.zh.md b/README.zh.md index d4e1a8a0c..6863ca6d1 100644 --- a/README.zh.md +++ b/README.zh.md @@ -1,318 +1,103 @@ # Pulsing -[![CI](https://github.com/DeepLink-org/pulsing/actions/workflows/ci.yml/badge.svg)](https://github.com/DeepLink-org/pulsing/actions/workflows/ci.yml) -[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) -[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/) -[![Rust](https://img.shields.io/badge/rust-1.75+-orange.svg)](https://www.rust-lang.org/) +[English](README.md) -**[English](README.md)** +基于 Rust 构建、面向 Python 的分布式 actor 运行时。 +提供位置透明的 actor 调用、流式消息和内置集群发现,不需要 Redis 或 etcd。 -**分布式 AI 系统的通信骨干。** - -**Actor 运行时。流式优先。零依赖。内置发现。** - -Pulsing 是一个用 Rust 构建、为 Python 设计的分布式 Actor 运行时。跨机器连接 AI Agent 和服务——不需要 Redis,不需要 etcd,不需要 YAML。只需 `pip install pulsing`。 - -🚀 **零外部依赖** — 纯 Rust + Tokio,无需 NATS/etcd/Redis - -⚡ **流式优先** — 原生流式响应支持,为 LLM token 生成而设计 - -🌐 **内置发现** — SWIM/Gossip 协议实现自动集群管理 - -🔀 **统一 API** — 本地和远程 Actor 使用相同的 `await actor.method()` - -## 🚀 5分钟快速体验 - -### 安装 +## 安装 ```bash pip install pulsing ``` -### 第一个 Multi-Agent 应用 +## 第一个 actor ```python import asyncio import pulsing as pul -from pulsing.agent import runtime + @pul.remote -class Greeter: - def __init__(self, display_name: str): - self.display_name = display_name +class Counter: + def __init__(self, value=0): + self.value = value - def greet(self, message: str) -> str: - return f"[{self.display_name}] 收到: {message}" + def inc(self): + self.value += 1 + return self.value - async def chat_with(self, peer_name: str, message: str) -> str: - # 使用 Greeter.resolve() 获取有类型的代理 - peer = await Greeter.resolve(peer_name) - return await peer.greet(f"来自 {self.display_name}: {message}") async def main(): - async with runtime(): - # 创建两个 Agent - alice = await Greeter.spawn(display_name="Alice", name="alice") - bob = await Greeter.spawn(display_name="Bob", name="bob") + await pul.init() + try: + counter = await Counter.spawn(value=0, name="counter") + print(await counter.inc()) # 1 + finally: + await pul.shutdown() - # Agent 间对话 - reply = await alice.chat_with("bob", "你好!") - print(reply) # [Bob] 收到: 来自 Alice: 你好! asyncio.run(main()) ``` -**就这么简单!** `@pul.remote` 让普通类变成可分布式部署的 Actor,`Greeter.resolve()` 让 Agent 互相发现和通信。 - -## 💡 我想做... - -| 场景 | 示例 | 说明 | -|------|------|------| -| **快速体验** | `examples/quickstart/` | 10 行代码入门 | -| **Multi-Agent 协作** | `examples/agent/pulsing/` | AI 辩论、头脑风暴、角色扮演 | -| **分布式 LLM 推理** | `pulsing actor router/vllm` | GPU 集群推理服务 | -| **集成 AutoGen** | `examples/agent/autogen/` | 一行代码分布式 | -| **集成 LangGraph** | `examples/agent/langgraph/` | 计算图跨节点执行 | -| **Agent 工作区 CLI** | `pulsing agent init` | [Pulsing Agent](examples/agent/workspace-demo.md) — 在仓库内运行多 Agent | -| **Agent 工具与环境** | `examples/python/forge_minimal.py` | [Pulsing Forge](docs/src/forge/index.zh.md) — 沙箱 shell、文件、plan | - -## 🔨 Pulsing Forge - -**面向 AI Agent 的通用工具与环境运行时** — 在可配置沙箱里执行 shell、改文件、维护计划;可嵌入任意 Agent 框架,也可通过 Pulsing Actor 隔离部署。 - -```python -from pulsing.forge import ForgeEnvironment - -env = ForgeEnvironment(cwd=".") -env.runtime().call_tool("shell_command", {"cmd": "pytest -q", "workdir": "."}) -``` - -文档:[Forge 章节](docs/src/forge/index.zh.md) · 包 README:[python/pulsing/forge/README.md](python/pulsing/forge/README.md) - -## 🤖 Pulsing Agent - -**工作区级多 Agent SDK + CLI** — 初始化 `.pulsing/` 工作区,在集群上唤醒 Agent,配合 Forge 工具协作。 - -```bash -pip install pulsing[agent] -pulsing agent init -pulsing agent wake --agents guide -pulsing agent say guide "运行 pytest" -``` - -文档:[工作区示例](examples/agent/workspace-demo.md) · SDK:`from pulsing.agent import Agent, spawn_agent` - -## 🎯 核心能力 - -### 1. Multi-Agent 协作 - -多个 AI Agent 并行工作、互相通信: - -```python -from pulsing.agent import agent, runtime, llm - -@agent(role="研究员", goal="深入分析问题") -class Researcher: - async def analyze(self, topic: str) -> str: - client = await llm() - return await client.ainvoke(f"分析: {topic}") - -@agent(role="评审", goal="评估方案质量") -class Reviewer: - async def review(self, proposal: str) -> str: - client = await llm() - return await client.ainvoke(f"评审: {proposal}") - -async with runtime(): - researcher = await Researcher.spawn(name="researcher") - reviewer = await Reviewer.spawn(name="reviewer") - - # 并行工作,互相协作 - analysis = await researcher.analyze("AI 发展趋势") - feedback = await reviewer.review(analysis) -``` - -```bash -# 运行 MBTI 人格讨论示例 -python examples/agent/pulsing/mbti_discussion.py --mock --group-size 6 - -# 运行并行创意生成示例 -python examples/agent/pulsing/parallel_ideas_async.py --mock --n-ideas 5 -``` - -### 2. 一行代码分布式 - -本地开发,无缝扩展到集群: +组建集群时,为节点配置 `addr`,通过 `seeds` 加入集群。 +使用 `await Counter.resolve("counter")` 查找命名 actor。 -```python -# 单机模式(开发调试) -async with runtime(): - agent = await MyAgent.spawn(name="agent") - -# 分布式模式(生产部署)—— 只需加地址 -async with runtime(addr="0.0.0.0:8001"): - agent = await MyAgent.spawn(name="agent") +## 项目范围 -# 其他节点自动发现 -async with runtime(addr="0.0.0.0:8002", seeds=["node1:8001"]): - agent = await resolve("agent") # 跨节点透明调用 -``` +- Actor mailbox、生命周期、监督重启及命名发现。 +- 本地与远程请求响应、单向调用及流式响应。 +- HTTP/2、TLS 和不解释业务内容的 tensor buffer 传输。 +- Python `@remote`、子进程集成、队列及发布订阅。 +- CLI actor 启动与集群观察。 +- Workspace 初始化、checkpoint、rollback 及 Python workflow。 -### 3. LLM 推理服务 +项目不再内置推理服务器、LLM 客户端、Forge 工具与 coding-agent SDK、 +桌面 GUI 和 benchmark 模块。业务服务可以自行构建在 actor API 之上。 -开箱即用的 GPU 集群推理: +## 命令行 ```bash -# 启动 Router(OpenAI 兼容 API) -pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 --http_port 8080 --model_name my-llm - -# 启动 vLLM Worker(可多个) -pulsing actor pulsing.serving.VllmWorker --model Qwen/Qwen2.5-0.5B --addr 0.0.0.0:8002 --seeds 127.0.0.1:8000 - -# 测试 -curl http://localhost:8080/v1/chat/completions \ - -d '{"model": "my-llm", "messages": [{"role": "user", "content": "Hello"}]}' -``` - -### 4. Agent 框架集成 - -已有 AutoGen/LangGraph 代码?一行迁移: - -```python -# AutoGen: 替换运行时 -from pulsing.autogen import PulsingRuntime -runtime = PulsingRuntime(addr="0.0.0.0:8000") - -# LangGraph: 包装计算图 -from pulsing.langgraph import with_pulsing -distributed_app = with_pulsing(app, seeds=["gpu-server:8001"]) -``` - -### 5. TensorDict 快速传输 - -`TensorMessage` 用一段不透明 metadata 和多段连续 CPU buffer 传输 TensorDict。PulsingQueue -负责把 CUDA Tensor 搬到 CPU,并在交给 Pulsing 前保证每个 Tensor 连续;Pulsing 不解析 -Tensor 的 dtype、shape 或 stride,这些信息由 PulsingQueue 编码到 metadata。 - -```python -from array import array - -import pulsing as pul - -cpu_buffer = array("f", range(6)) -message = pul.TensorMessage( - metadata=b"...", # dtype / shape / TensorDict 结构 - buffers=[memoryview(cpu_buffer).cast("B")], # 必须连续 - version=1, -) - -# @remote Actor 收到 TensorMessage 时调用该专用入口。 -@pul.remote -class Storage: - async def receive_tensor(self, message: pul.TensorMessage): - return message -``` - -明文远程连接默认使用同一监听端口上的 raw TCP 数据面:长连接池复用连接,发送端用 -`write_vectored` 直接提交 header、metadata 和各原始 buffer,接收端把每个 payload -直接读入最终由 Python Tensor 持有的分配。按应用 payload 的 CPU copy 口径,主路径只有 -`应用 buffer -> TCP kernel buffer` 和 `TCP kernel buffer -> 最终接收 buffer` 两次, -不会先拼成一个大包,也不会在接收后再复制一次。远程调用的 `ask`/`tell` 完成前,发送方 -不得修改或 resize 源 buffer;完成后远端已经持有独立接收分配。若目标 actor 位于同一进程, -双方共享原 storage,接收方仍持有引用期间原地修改会彼此可见;需要快照语义时由调用方先 -`clone()`。返回的接收 buffer 生命周期由 `TensorMessage`/下游 Tensor 引用管理。 - -TLS 连接,或设置 `PULSING_TENSOR_TRANSPORT=http2` 时,使用兼容 HTTP/2 路径。该路径会 -打包和聚合 payload,copy 次数高于 raw TCP。可通过 `pulsing.tensor_transport_stats()` -检查 `active_copy_model`、raw frame/byte 计数和 HTTP/2 fallback 计数。接收边界可用以下 -环境变量限制,超限会在分配大 payload 前拒绝: - -- `PULSING_MAX_TENSOR_WIRE_BYTES`:单帧总大小,默认 64 GiB -- `PULSING_MAX_TENSOR_METADATA_BYTES`:metadata 大小,默认 64 MiB -- `PULSING_MAX_TENSOR_BUFFERS`:buffer 数量,默认 65536 - -同节点共享内存后端已在 `TensorTransport` 抽象中预留,当前尚未实现。 - -完整内容见 [TensorMessage 快速传输设计](docs/src/design/tensor-message-transport.zh.md) -和 [可运行的 TCP 示例](examples/python/tensor_message_fast_path.py)。 - -## 📚 示例导航 - -``` -examples/ -├── quickstart/ # ⭐ 5分钟入门 -│ └── hello_agent.py # 第一个 Agent -├── agent/ -│ ├── pulsing/ # ⭐⭐ Multi-Agent 应用 -│ │ ├── mbti_discussion.py # MBTI 人格讨论 -│ │ └── parallel_ideas_async.py # 并行创意生成 -│ ├── autogen/ # AutoGen 集成 -│ └── langgraph/ # LangGraph 集成 -├── python/ # ⭐⭐ 基础示例 -│ ├── ping_pong.py # Actor 基础 -│ ├── cluster.py # 集群通信 -│ ├── tensor_message_fast_path.py # Tensor 传输 -│ └── ... -└── rust/ # Rust 示例 +pulsing actor my_app.Counter --addr 0.0.0.0:8000 --name counter +pulsing inspect actors --endpoint 127.0.0.1:8000 +pulsing init --template minimal +pulsing checkpoint -m "working state" +pulsing history +pulsing rollback ``` -## 🔧 技术特性 +Rust CLI 还支持 `pulsing run [script.py]`,别名为 `workflow`。 +Workflow 执行一次后退出,不再进入 LLM 交互会话。 -- **零外部依赖**:纯 Rust + Tokio,无需 NATS/etcd/Redis -- **Gossip 协议**:内置 SWIM 协议实现节点发现和故障检测 -- **位置透明**:本地和远程 Actor 使用相同的 API -- **流式消息**:原生支持流式请求和响应(适配 LLM) -- **类型安全**:Rust Behavior API 提供编译时消息类型检查 +## 开发 -## 📦 项目结构 - -``` -Pulsing/ -├── crates/ # Rust 核心 -│ ├── pulsing-actor/ # Actor System -│ └── pulsing-py/ # Python 绑定 -├── python/pulsing/ # Python 包 -│ ├── actor/ # Actor API -│ ├── agent/ # Agent 工具箱 -│ ├── autogen/ # AutoGen 集成 -│ └── langgraph/ # LangGraph 集成 -├── examples/ # 示例代码 -└── docs/ # 文档 -``` - -## 🛠️ 开发 - -### 前置依赖 - -- [Rust](https://rustup.rs/) ≥ 1.75 -- Python ≥ 3.10 -- [uv](https://docs.astral.sh/uv/)(推荐的包管理器) -- [just](https://github.com/casey/just)(任务运行器:`cargo install just` 或 `brew install just`) - -### 快速搭建 +需要 Python 3.10+ 和当前稳定版 Rust。RustPython CLI 要求 Rust 1.93 或更新版本。 ```bash -# 1. 安装 Python 依赖 uv sync --extra dev - -# 2. 编译 Rust 核心并安装(修改 Rust 代码后需重新执行) uv run maturin develop +just test +just fmt +just lint ``` -### 常用命令 +`just build-wheel` 构建 Python wheel,`just build-binary` 构建 RustPython CLI。 +开发流程见 [CONTRIBUTING.md](CONTRIBUTING.md)。 -```bash -just dev # 编译并安装(开发模式) -just test # 运行全部测试(Rust + Python) -just test-python # 仅运行 Python 测试 -just fmt # 格式化代码 -just lint # 代码检查 -just check # 提交前完整检查(格式 + lint + 测试) -just cov # 生成覆盖率报告 -``` +## 目录 -详细开发指南请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)。 +| 路径 | 职责 | +|------|------| +| `crates/pulsing-actor/` | Actor 运行时、发现与传输 | +| `crates/pulsing-py/` | CPython/PyO3 绑定 | +| `crates/pulsing-rpymod/` | RustPython 绑定 | +| `crates/pulsing-bindings-core/` | 绑定共用数据类型 | +| `crates/pulsing-cli/` | Rust CLI | +| `crates/pulsing-workspace/` | Workspace 初始化与历史 | +| `python/pulsing/` | Python SDK 与集成 | +| `examples/` | Actor 与传输示例 | +| `docs/` | 文档 | -## 📄 License +## 许可证 Apache-2.0 diff --git a/benchmarks/PERFORMANCE_COMPARISON_REPORT.md b/benchmarks/PERFORMANCE_COMPARISON_REPORT.md deleted file mode 100644 index f2d9e37b2..000000000 --- a/benchmarks/PERFORMANCE_COMPARISON_REPORT.md +++ /dev/null @@ -1,355 +0,0 @@ -# Ray vs Pulsing:分布式 Actor 系统性能对比报告 - -## 执行摘要 - -本报告对比了两个分布式 Actor 框架——**Ray** 和 **Pulsing**——在相同负载下的性能表现。 - -**核心发现**(基于单进程公平对比,Ray 使用 Generators): - -| 指标 | Pulsing 优势 | -|------|-------------| -| 单请求平均延迟 | **快 467 倍**(1.41ms vs 659.30ms) | -| 单请求 P99 延迟 | **快 3,415 倍**(3.85ms vs 13,156ms) | -| 流式平均延迟 | **快 9.3 倍**(112.70ms vs 1,044.85ms) | -| 流式 P99 延迟 | **快 91 倍**(175ms vs 15,949ms) | -| 总吞吐量 | **高 17.8 倍**(6,715 vs 378 操作) | - -**结论**:即使 Ray 使用 Generators 实现流式处理,Pulsing 在低延迟、高吞吐场景下仍然显著优于 Ray,适合实时推理服务等延迟敏感型应用。 - ---- - -## 1. 架构设计对比 - -### 1.1 整体架构 - -``` -┌─────────────────────────────────────────────────────────────────────────┐ -│ Pulsing │ -├─────────────────────────────────────────────────────────────────────────┤ -│ ┌──────────┐ Message ┌──────────┐ Message ┌──────────┐ │ -│ │ Actor │ ──────────────▶│ Actor │ ──────────────▶│ Actor │ │ -│ └──────────┘ └──────────┘ └──────────┘ │ -│ │ │ │ │ -│ └───────────────────────────┴───────────────────────────┘ │ -│ Gossip 协议(集群发现) │ -└─────────────────────────────────────────────────────────────────────────┘ - -┌─────────────────────────────────────────────────────────────────────────┐ -│ Ray │ -├─────────────────────────────────────────────────────────────────────────┤ -│ ┌──────────┐ ObjectRef ┌─────────────┐ ObjectRef ┌──────────┐ │ -│ │ Actor │ ──────────▶ │ Object Store │ ◀────────── │ Actor │ │ -│ └──────────┘ └─────────────┘ └──────────┘ │ -│ │ │ │ │ -│ └─────────────────────────┴───────────────────────────┘ │ -│ GCS(全局控制存储)+ Raylet(调度器) │ -└─────────────────────────────────────────────────────────────────────────┘ -``` - -### 1.2 核心抽象对比 - -| 维度 | Pulsing | Ray | -|------|---------|-----| -| **编程模型** | 消息传递(Message Passing) | 远程过程调用(RPC) | -| **核心抽象** | `Actor` + `Message` | `@ray.remote` + `ObjectRef` | -| **调用方式** | `actor_ref.ask(message)` | `actor.method.remote(args)` | -| **返回值** | 直接返回 `Message` | 返回 `ObjectRef`,需 `ray.get()` 获取 | -| **集群发现** | Gossip 协议(去中心化) | GCS 全局控制存储(中心化) | - -### 1.3 代码示例对比 - -**Pulsing 定义 Actor:** -```python -class EchoWorker(Actor): - async def receive(self, msg: Message): - if msg.msg_type == "Echo": - data = msg.to_json() - return Message.from_json("Response", {"echo": data["text"]}) - -# 调用 -response = await actor_ref.ask(Message.from_json("Echo", {"text": "hello"})) -``` - -**Ray 定义 Actor:** -```python -@ray.remote -class EchoWorker: - async def echo(self, text: str) -> dict: - return {"echo": text} - -# 调用 -result = await actor.echo.remote("hello") # 返回 ObjectRef,自动解包 -``` - -### 1.4 流式处理对比 - -| 维度 | Pulsing | Ray(修正后) | -|------|---------|--------------| -| **实现方式** | `StreamMessage` + `StreamReader` | Ray Generators(`yield`) | -| **数据传输** | 分块流式(边产出边消费) | 分块流式(使用 `async for`) | -| **首字节时间** | 生成第一个 chunk 后即可接收 | 生成第一个 chunk 后即可接收 | -| **内存占用** | 仅缓存当前 chunk | 仅缓存当前 chunk(ObjectRef) | - -``` -Pulsing 流式: - Producer: [chunk1] → [chunk2] → [chunk3] → ... → [done] - Consumer: ↓ ↓ ↓ - 处理1 处理2 处理3 (边收边处理) - -Ray Generators(修正后): - Producer: [chunk1] → [chunk2] → [chunk3] → ... → [done] - Consumer: ↓ ↓ ↓ - 处理1 处理2 处理3 (边收边处理) -``` - -**注意**:修正后的 Ray benchmark 使用 Ray Generators 实现真正的流式处理,与 Pulsing 的流式语义等价。 - ---- - -## 2. 关键设计差异 - -### 2.1 差异 A:调用开销 - -| 步骤 | Pulsing | Ray | -|------|---------|-----| -| 1. 序列化 | JSON 序列化(轻量) | Pickle 序列化(较重) | -| 2. 传输 | 直接消息传递 | 写入 Object Store | -| 3. 调度 | 无额外调度 | Raylet 调度 + GCS 查询 | -| 4. 获取结果 | 直接返回 | 从 Object Store 读取 | - -**影响**:Pulsing 的调用路径更短,单请求延迟显著更低。 - -### 2.2 差异 B:流式语义(已修正) - -| 场景 | Pulsing | Ray(修正后) | -|------|---------|--------------| -| 生成 10 个 item,每个延迟 50ms | TTFT ≈ 50ms,总延迟 ≈ 500ms | TTFT ≈ 50ms,总延迟 ≈ 500ms | -| P99 尾延迟 | 较低(175ms) | 较高(15,949ms) | - -**影响**: -- 虽然两者都实现了真正的流式处理,但 Ray 的底层架构(Object Store + 序列化)导致延迟和长尾问题更严重 -- 在 LLM 推理等场景,Pulsing 可以实现更好的用户体验(更低的延迟和更稳定的 P99) - -### 2.3 差异 C:运行时模型 - -| 模式 | Pulsing | Ray | -|------|---------|-----| -| 单进程 | 轻量级 ActorSystem | 完整 Ray 运行时(Object Store + Raylet) | -| 多进程 | 每进程一个 ActorSystem,Gossip 组网 | 需连接统一 Ray 集群,否则资源争用 | -| 资源占用 | 低 | 较高(需要 Object Store 内存) | - -**影响**:Pulsing 更适合资源受限环境和多进程部署。 - ---- - -## 3. 压测实验设计 - -### 3.1 测试配置 - -| 配置项 | 单进程模式 | 多进程模式 | -|--------|-----------|-----------| -| 进程数 | 1 | 10(torchrun) | -| Worker 数/类型 | 50 | 1 | -| 总 Worker 数 | 250(5类型×50) | 50(5类型×10进程) | -| 测试时长 | 30 秒 | 300 秒 | -| 目标速率 | 100 req/s | 100 req/s | - -### 3.2 Worker 类型 - -| Worker | 功能 | 负载特征 | -|--------|------|---------| -| **EchoWorker** | 消息回显 | I/O 密集,极低延迟 | -| **ComputeWorker** | `sum(i² for i in range(n))` | CPU 密集,n ∈ [100, 10000] | -| **StreamWorker** | 生成 5-20 个 item,间隔 10-50ms | 流式,中等延迟 | -| **BatchWorker** | 累积 10 个请求后批量处理 | 状态+批处理 | -| **StatefulWorker** | SetState / GetState | 有状态操作 | - -### 3.3 请求混合 - -``` -请求类型分布: -├── 70% 单请求(Single Request) -│ ├── 25% Echo -│ ├── 25% Compute -│ ├── 25% Batch -│ └── 25% Stateful -└── 30% 流请求(Stream Request) - └── 100% Stream -``` - -### 3.4 统计指标 - -| 指标 | 说明 | -|------|------| -| **total** | 总请求/流数量 | -| **success_rate** | 成功率 | -| **avg latency** | 平均延迟(端到端) | -| **p50 / p95 / p99** | 延迟百分位数 | -| **errors** | 错误类型统计 | - ---- - -## 4. 数据对比 - -### 4.1 单进程模式(公平对比)✅ - -> **测试条件**:30秒,100 req/s,50 Workers/类型,单进程 -> -> **重要更新**:Ray benchmark 已修正为使用 Ray Generators 实现真正的流式处理,确保公平对比。 - -#### 单请求性能 - -| 指标 | Ray | Pulsing | Pulsing 优势 | -|------|----:|--------:|-------------:| -| 总请求数 | 254 | 4,734 | **18.6×** | -| 成功率 | 100% | 100% | — | -| 平均延迟 | 659.30 ms | 1.41 ms | **467× 更低** | -| P50 延迟 | 265.43 ms | 1.23 ms | **216× 更低** | -| P95 延迟 | 1,764.99 ms | 3.00 ms | **588× 更低** | -| P99 延迟 | 13,156.18 ms | 3.85 ms | **3,415× 更低** | - -**分析**: -- Ray 的 P99 延迟高达 13 秒,说明存在严重的长尾问题,可能与 Object Store 争用、序列化开销或调度延迟相关 -- Pulsing 的 P99 仅 3.85ms,延迟分布非常稳定,几乎无长尾 -- 相同时间内 Pulsing 处理的请求数是 Ray 的 18.6 倍,吞吐量优势显著 - -#### 流式性能(使用 Ray Generators) - -| 指标 | Ray | Pulsing | Pulsing 优势 | -|------|----:|--------:|-------------:| -| 总流数 | 124 | 1,981 | **16.0×** | -| 成功率 | 100% | 100% | — | -| 平均延迟 | 1,044.85 ms | 112.70 ms | **9.3× 更低** | -| P50 延迟 | 385.90 ms | 112.21 ms | **3.4× 更低** | -| P95 延迟 | 3,588.20 ms | 168.56 ms | **21.3× 更低** | -| P99 延迟 | 15,949.15 ms | 175.00 ms | **91× 更低** | - -**分析**: -- 即使使用 Ray Generators 实现流式处理,Ray 的流式 P99 仍超过 15 秒,严重影响用户体验 -- Pulsing 流式 P99 控制在 175ms 内,更适合实时场景 -- 虽然两者都实现了真正的流式处理,但 Pulsing 的延迟和吞吐量仍然显著优于 Ray -- 差异主要来自底层架构:Pulsing 的直接消息传递 vs Ray 的 Object Store + 序列化开销 - ---- - -### 4.2 多进程模式(对 Ray 不公平)⚠️ - -> **测试条件**:`torchrun --nproc_per_node=10`,每进程独立初始化 -> -> ⚠️ **注意**:此模式下每个进程创建独立的 Ray 运行时,导致资源争用,对 Ray 不公平。仅供参考。 - -#### 单请求性能 - -| 指标 | Ray(Process 8) | Pulsing | 差异 | -|------|---:|---:|---:| -| 总请求数 | 2,867 | 7,473 | Pulsing **2.6×** | -| 平均延迟 | 44.52 ms | 0.36 ms | Pulsing **123× 更低** | -| P99 延迟 | 367.10 ms | 1.01 ms | Pulsing **363× 更低** | - -#### 流式性能 - -| 指标 | Ray(Process 8) | Pulsing | 差异 | -|------|---:|---:|---:| -| 总流数 | 214 | 556 | Pulsing **2.6×** | -| 平均延迟 | 476.55 ms | 368.62 ms | Pulsing **23% 更低** | -| P99 延迟 | 2,096.25 ms | 952.86 ms | Pulsing **2.2× 更低** | - ---- - -### 4.3 错误统计 - -| 模式 | Ray | Pulsing | -|------|-----|---------| -| 单进程 | 0 错误 | 0 错误 | -| 多进程 | 0 错误 | 1 错误(网络抖动) | - -两个框架的稳定性都很好,错误率接近 0%。 - ---- - -## 5. 结论 - -### 5.1 性能对比总结(修正后,Ray 使用 Generators) - -| 维度 | Ray | Pulsing | 差异倍数 | -|------|----:|--------:|---------:| -| 单请求平均延迟 | 659.30 ms | 1.41 ms | **467×** | -| 单请求 P99 延迟 | 13,156 ms | 3.85 ms | **3,415×** | -| 流式平均延迟 | 1,044.85 ms | 112.70 ms | **9.3×** | -| 流式 P99 延迟 | 15,949 ms | 175 ms | **91×** | -| 总吞吐量(请求+流) | 378 | 6,715 | **17.8×** | - -### 5.2 差异归因 - -| 差异 | 原因 | -|------|------| -| 单请求延迟 467× | Pulsing 直接消息传递(JSON 序列化)vs Ray Object Store + Pickle 序列化 + Raylet 调度 | -| P99 尾延迟巨大(3,415×) | Ray 的 Object Store GC、序列化开销和调度争用导致严重长尾 | -| 流式延迟差异(9.3×) | 虽然都使用流式处理,但 Pulsing 的消息传递开销远低于 Ray 的 ObjectRef 机制 | -| 吞吐量差异(17.8×) | Pulsing 更低的调用开销和更高效的并发模型支持更高吞吐量 | - -### 5.3 适用场景建议 - -| 场景 | 推荐框架 | 原因 | -|------|---------|------| -| **LLM 推理服务** | Pulsing | 低延迟 + 真流式,首 token 更快 | -| **实时 API 服务** | Pulsing | 微秒级延迟,P99 稳定 | -| **高并发消息处理** | Pulsing | 轻量级,吞吐量更高 | -| **大规模数据处理** | Ray | 成熟生态,丰富的数据处理工具 | -| **分布式机器学习** | Ray | Ray Train / Tune 等成熟组件 | -| **需要复杂调度** | Ray | 支持资源感知调度、Gang 调度等 | - -### 5.4 最终结论 - -> **即使 Ray 使用 Generators 实现流式处理,Pulsing 在延迟敏感型场景下仍然显著优于 Ray**: -> - 单请求延迟快 **467 倍**(1.41ms vs 659.30ms) -> - 单请求 P99 延迟快 **3,415 倍**(3.85ms vs 13,156ms) -> - 流式平均延迟快 **9.3 倍**(112.70ms vs 1,044.85ms) -> - 流式 P99 延迟快 **91 倍**(175ms vs 15,949ms) -> - 总吞吐量高 **17.8 倍**(6,715 vs 378 操作) -> -> 对于需要低延迟、高吞吐的 Actor 系统(如推理服务、实时 API),**强烈推荐使用 Pulsing**。 -> -> 对于需要丰富生态和复杂调度的大规模数据处理任务,**Ray 仍是更好的选择**。 - ---- - -## 附录 - -### A. 测试环境 - -| 项目 | 配置 | -|------|------| -| 操作系统 | macOS (darwin 25.1.0) | -| Python | 3.12.11 | -| Ray | 最新稳定版 | -| Pulsing | 当前开发版 | - -### B. 运行测试 - -```bash -# 单进程模式(推荐,公平对比) -./benchmarks/run_stress_test_ray_single.sh # Ray -./benchmarks/run_stress_test_pulsing_single.sh # Pulsing - -# 自定义参数 -DURATION=60 RATE=200 NUM_WORKERS=100 ./benchmarks/run_stress_test_ray_single.sh -``` - -### C. 测试脚本 - -| 脚本 | 说明 | -|------|------| -| `large_scale_stress_test_ray_single.py` | Ray 单进程测试(已修正:使用 Ray Generators) | -| `large_scale_stress_test_pulsing_single.py` | Pulsing 单进程测试 | -| `large_scale_stress_test_ray.py` | Ray 多进程测试(torchrun) | -| `large_scale_stress_test.py` | Pulsing 多进程测试(torchrun) | - -### D. 测试修正说明 - -**Ray benchmark 修正**(2025-01-25): -- ✅ 修正 `StreamWorker` 使用 Ray Generators(`yield`)实现真正的流式处理 -- ✅ 修正调用端使用 `async for` 配合 Ray Generators 消费流式结果 -- ✅ 确保参数与 Pulsing benchmark 对齐(count: 5-15, delay: 0.01) - -修正后的测试结果更能反映两个框架的真实性能差异,确保公平对比。 diff --git a/benchmarks/baseline_throughput.py b/benchmarks/baseline_throughput.py deleted file mode 100644 index ca36e7c34..000000000 --- a/benchmarks/baseline_throughput.py +++ /dev/null @@ -1,334 +0,0 @@ -#!/usr/bin/env python3 -""" -Queue & Topic 基线吞吐 Benchmark(单节点) - -在单进程内测量 Queue 与 Topic 的基线吞吐与延迟,便于回归对比。 - -Usage: - python benchmarks/baseline_throughput.py - python benchmarks/baseline_throughput.py --duration 15 --output results.json - python benchmarks/baseline_throughput.py --queue-only - python benchmarks/baseline_throughput.py --topic-only --topic-subscribers 3 -""" - -from __future__ import annotations - -import argparse -import asyncio -import json -import shutil -import tempfile -import time - -import pulsing as pul -from pulsing.streaming import ( - read_queue, - write_queue, - PublishMode, - read_topic, - write_topic, -) - - -def _percentile(sorted_data: list[float], p: float) -> float: - if not sorted_data: - return 0.0 - idx = min(int(len(sorted_data) * p / 100), len(sorted_data) - 1) - return sorted_data[idx] - - -# ============================================================================= -# Queue 基线 -# ============================================================================= - - -async def run_queue_baseline( - system, - storage_path: str, - duration: float, - num_buckets: int, - record_size: int, -) -> dict: - """单 writer + 单 reader,固定时长,统计写/读吞吐与延迟.""" - topic = "baseline_queue" - write_latencies_ms: list[float] = [] - read_latencies_ms: list[float] = [] - records_written = 0 - records_read = 0 - - writer = await write_queue( - system, - topic=topic, - bucket_column="id", - num_buckets=num_buckets, - storage_path=storage_path, - ) - reader = await read_queue( - system, - topic=topic, - num_buckets=num_buckets, - storage_path=storage_path, - ) - - end_time = time.monotonic() + duration - - async def produce(): - nonlocal records_written - i = 0 - while time.monotonic() < end_time: - t0 = time.perf_counter() - try: - rec = {"id": f"r{i}", "payload": "x" * record_size} - await writer.put(rec) - write_latencies_ms.append((time.perf_counter() - t0) * 1000) - records_written += 1 - i += 1 - except Exception: - pass - - async def consume(): - nonlocal records_read - while time.monotonic() < end_time: - t0 = time.perf_counter() - try: - batch = await reader.get(limit=50, wait=True, timeout=1.0) - if batch: - read_latencies_ms.append((time.perf_counter() - t0) * 1000) - records_read += len(batch) - except asyncio.TimeoutError: - pass - except Exception: - pass - - await asyncio.gather(produce(), consume()) - - write_latencies_ms.sort() - read_latencies_ms.sort() - - return { - "duration_s": duration, - "records_written": records_written, - "records_read": records_read, - "write_throughput_rec_s": records_written / duration if duration > 0 else 0, - "read_throughput_rec_s": records_read / duration if duration > 0 else 0, - "write_latency_ms": { - "avg": sum(write_latencies_ms) / len(write_latencies_ms) - if write_latencies_ms - else 0, - "p50": _percentile(write_latencies_ms, 50), - "p95": _percentile(write_latencies_ms, 95), - "p99": _percentile(write_latencies_ms, 99), - }, - "read_latency_ms": { - "avg": sum(read_latencies_ms) / len(read_latencies_ms) - if read_latencies_ms - else 0, - "p50": _percentile(read_latencies_ms, 50), - "p95": _percentile(read_latencies_ms, 95), - "p99": _percentile(read_latencies_ms, 99), - }, - } - - -# ============================================================================= -# Topic 基线 -# ============================================================================= - - -async def run_topic_baseline( - system, - duration: float, - num_subscribers: int, - payload_size: int, -) -> dict: - """单 publisher + N subscribers,fire_and_forget,统计发布与交付吞吐.""" - topic_name = "baseline_topic" - messages_published = 0 - delivered_per_sub: list[int] = [0] * num_subscribers - publish_latencies_ms: list[float] = [] - - writer = await write_topic(system, topic_name) - readers = [] - locks = [asyncio.Lock() for _ in range(num_subscribers)] - - for i in range(num_subscribers): - reader = await read_topic(system, topic_name, reader_id=f"sub_{i}") - - def make_cb(idx): - async def cb(msg): - async with locks[idx]: - delivered_per_sub[idx] += 1 - - return cb - - reader.add_callback(make_cb(i)) - await reader.start() - readers.append(reader) - - end_time = time.monotonic() + duration - seq = 0 - - while time.monotonic() < end_time: - t0 = time.perf_counter() - try: - await writer.publish( - {"seq": seq, "payload": "x" * payload_size}, - mode=PublishMode.FIRE_AND_FORGET, - ) - publish_latencies_ms.append((time.perf_counter() - t0) * 1000) - messages_published += 1 - seq += 1 - except Exception: - pass - - await asyncio.sleep(0.2) - - for r in readers: - await r.stop() - - publish_latencies_ms.sort() - total_delivered = sum(delivered_per_sub) - - return { - "duration_s": duration, - "num_subscribers": num_subscribers, - "messages_published": messages_published, - "total_delivered": total_delivered, - "publish_throughput_msg_s": messages_published / duration - if duration > 0 - else 0, - "delivered_throughput_msg_s": total_delivered / duration if duration > 0 else 0, - "publish_latency_ms": { - "avg": sum(publish_latencies_ms) / len(publish_latencies_ms) - if publish_latencies_ms - else 0, - "p50": _percentile(publish_latencies_ms, 50), - "p95": _percentile(publish_latencies_ms, 95), - "p99": _percentile(publish_latencies_ms, 99), - }, - } - - -# ============================================================================= -# Main -# ============================================================================= - - -async def main(): - parser = argparse.ArgumentParser( - description="Queue & Topic 基线吞吐 Benchmark(单节点)" - ) - parser.add_argument( - "--duration", - type=float, - default=10.0, - help="每类基准运行时长(秒)", - ) - parser.add_argument( - "--queue-only", - action="store_true", - help="仅跑 Queue 基线", - ) - parser.add_argument( - "--topic-only", - action="store_true", - help="仅跑 Topic 基线", - ) - parser.add_argument( - "--num-buckets", - type=int, - default=4, - help="Queue 桶数", - ) - parser.add_argument( - "--topic-subscribers", - type=int, - default=1, - help="Topic 订阅者数量", - ) - parser.add_argument( - "--record-size", - type=int, - default=100, - help="单条记录 payload 字节数", - ) - parser.add_argument( - "--output", - type=str, - default=None, - help="结果写入 JSON 文件路径", - ) - args = parser.parse_args() - - system = await pul.actor_system() - storage_path = tempfile.mkdtemp(prefix="baseline_queue_") - results: dict = {"queue": None, "topic": None} - - try: - if not args.topic_only: - print("Running Queue baseline...") - results["queue"] = await run_queue_baseline( - system, - storage_path=storage_path, - duration=args.duration, - num_buckets=args.num_buckets, - record_size=args.record_size, - ) - - if not args.queue_only: - print("Running Topic baseline...") - results["topic"] = await run_topic_baseline( - system, - duration=args.duration, - num_subscribers=args.topic_subscribers, - payload_size=args.record_size, - ) - finally: - await system.shutdown() - shutil.rmtree(storage_path, ignore_errors=True) - - # 打印汇总 - print() - print("=" * 60) - print("Baseline Throughput Results") - print("=" * 60) - - if results["queue"]: - q = results["queue"] - print("\n--- Queue ---") - print(f" Duration: {q['duration_s']:.1f}s") - print(f" Write throughput: {q['write_throughput_rec_s']:.0f} rec/s") - print(f" Read throughput: {q['read_throughput_rec_s']:.0f} rec/s") - print( - f" Write latency: avg={q['write_latency_ms']['avg']:.2f}ms " - f"p50={q['write_latency_ms']['p50']:.2f}ms p99={q['write_latency_ms']['p99']:.2f}ms" - ) - print( - f" Read latency: avg={q['read_latency_ms']['avg']:.2f}ms " - f"p50={q['read_latency_ms']['p50']:.2f}ms p99={q['read_latency_ms']['p99']:.2f}ms" - ) - - if results["topic"]: - t = results["topic"] - print("\n--- Topic ---") - print(f" Duration: {t['duration_s']:.1f}s") - print(f" Subscribers: {t['num_subscribers']}") - print(f" Publish throughput: {t['publish_throughput_msg_s']:.0f} msg/s") - print( - f" Delivered total: {t['total_delivered']} ({t['delivered_throughput_msg_s']:.0f} msg/s)" - ) - print( - f" Publish latency: avg={t['publish_latency_ms']['avg']:.2f}ms " - f"p50={t['publish_latency_ms']['p50']:.2f}ms p99={t['publish_latency_ms']['p99']:.2f}ms" - ) - - print("\n" + "=" * 60) - - if args.output: - with open(args.output, "w") as f: - json.dump(results, f, indent=2) - print(f"Results written to {args.output}") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/benchmarks/concurrency_sweep.py b/benchmarks/concurrency_sweep.py deleted file mode 100644 index 14342b386..000000000 --- a/benchmarks/concurrency_sweep.py +++ /dev/null @@ -1,342 +0,0 @@ -#!/usr/bin/env python3 -""" -多并发扫描:在不同 生产者/消费者 并发组合下测量 Queue 与 Topic 吞吐。 - -扫描 (P,C) 组合,例如 P,C ∈ {1,2,4,8},得到每种并发下的写/读吞吐,便于看扩展性。 - -Usage: - python benchmarks/concurrency_sweep.py - python benchmarks/concurrency_sweep.py --producers 1 2 4 8 --consumers 1 2 4 8 --duration 8 - python benchmarks/concurrency_sweep.py --queue-only --output sweep_queue.json -""" - -from __future__ import annotations - -import argparse -import asyncio -import json -import shutil -import tempfile -import time - -import pulsing as pul -from pulsing.streaming import ( - read_queue, - write_queue, - PublishMode, - read_topic, - write_topic, -) - - -# ============================================================================= -# Queue 多并发 -# ============================================================================= - - -async def run_queue_concurrent( - system, - storage_path: str, - num_producers: int, - num_consumers: int, - duration: float, - num_buckets: int, - record_size: int, -) -> dict: - """P 个 writer + C 个 reader (rank/world_size),固定时长,汇总写/读吞吐.""" - topic = f"sweep_q_p{num_producers}_c{num_consumers}" - write_counts = [0] * num_producers - read_counts = [0] * num_consumers - write_locks = [asyncio.Lock() for _ in range(num_producers)] - read_locks = [asyncio.Lock() for _ in range(num_consumers)] - - async def producer(pid: int): - writer = await write_queue( - system, - topic=topic, - bucket_column="id", - num_buckets=num_buckets, - storage_path=storage_path, - ) - end_time = time.monotonic() + duration - i = 0 - while time.monotonic() < end_time: - try: - await writer.put({"id": f"p{pid}_{i}", "payload": "x" * record_size}) - async with write_locks[pid]: - write_counts[pid] += 1 - i += 1 - except Exception: - pass - - async def consumer(rank: int): - reader = await read_queue( - system, - topic=topic, - rank=rank, - world_size=num_consumers, - num_buckets=num_buckets, - storage_path=storage_path, - ) - end_time = time.monotonic() + duration - while time.monotonic() < end_time: - try: - batch = await reader.get(limit=50, wait=True, timeout=1.0) - if batch: - async with read_locks[rank]: - read_counts[rank] += len(batch) - except asyncio.TimeoutError: - pass - except Exception: - pass - - await asyncio.gather( - *[producer(p) for p in range(num_producers)], - *[consumer(c) for c in range(num_consumers)], - ) - - total_written = sum(write_counts) - total_read = sum(read_counts) - return { - "num_producers": num_producers, - "num_consumers": num_consumers, - "records_written": total_written, - "records_read": total_read, - "write_throughput_rec_s": total_written / duration if duration > 0 else 0, - "read_throughput_rec_s": total_read / duration if duration > 0 else 0, - "duration_s": duration, - } - - -# ============================================================================= -# Topic 多并发 -# ============================================================================= - - -async def run_topic_concurrent( - system, - num_publishers: int, - num_subscribers: int, - duration: float, - payload_size: int, -) -> dict: - """P 个 publisher + C 个 subscriber,fire_and_forget,汇总发布与交付吞吐.""" - topic_name = f"sweep_t_p{num_publishers}_c{num_subscribers}" - publish_counts = [0] * num_publishers - delivered_counts = [0] * num_subscribers - pub_locks = [asyncio.Lock() for _ in range(num_publishers)] - del_locks = [asyncio.Lock() for _ in range(num_subscribers)] - - # 先起订阅者 - readers = [] - for c in range(num_subscribers): - reader = await read_topic(system, topic_name, reader_id=f"sub_{c}") - - def make_cb(cid): - async def cb(_msg): - async with del_locks[cid]: - delivered_counts[cid] += 1 - - return cb - - reader.add_callback(make_cb(c)) - await reader.start() - readers.append(reader) - - async def publisher(pid: int): - writer = await write_topic(system, topic_name, writer_id=f"pub_{pid}") - end_time = time.monotonic() + duration - seq = 0 - while time.monotonic() < end_time: - try: - await writer.publish( - {"seq": seq, "payload": "x" * payload_size}, - mode=PublishMode.FIRE_AND_FORGET, - ) - async with pub_locks[pid]: - publish_counts[pid] += 1 - seq += 1 - except Exception: - pass - - await asyncio.gather(*[publisher(p) for p in range(num_publishers)]) - - await asyncio.sleep(0.3) - for r in readers: - await r.stop() - - total_published = sum(publish_counts) - total_delivered = sum(delivered_counts) - return { - "num_publishers": num_publishers, - "num_subscribers": num_subscribers, - "messages_published": total_published, - "messages_delivered": total_delivered, - "publish_throughput_msg_s": total_published / duration if duration > 0 else 0, - "delivered_throughput_msg_s": total_delivered / duration if duration > 0 else 0, - "duration_s": duration, - } - - -# ============================================================================= -# 扫描与输出 -# ============================================================================= - - -def parse_concurrency(s: str) -> list[int]: - """解析如 '1,2,4,8' 或 '1-4' 为整数列表.""" - s = s.strip() - if "-" in s: - a, b = s.split("-", 1) - return list(range(int(a), int(b) + 1)) - return [int(x) for x in s.replace(",", " ").split()] - - -async def main(): - parser = argparse.ArgumentParser( - description="多并发扫描:不同 生产者/消费者 下的 Queue & Topic 吞吐" - ) - parser.add_argument( - "--producers", - type=str, - default="1,2,4,8", - help="生产者并发数列表,如 1,2,4,8 或 1-4", - ) - parser.add_argument( - "--consumers", - type=str, - default="1,2,4,8", - help="消费者并发数列表,如 1,2,4,8 或 1-4", - ) - parser.add_argument( - "--duration", - type=float, - default=8.0, - help="每个 (P,C) 组合运行时长(秒)", - ) - parser.add_argument( - "--num-buckets", - type=int, - default=8, - help="Queue 桶数", - ) - parser.add_argument( - "--record-size", - type=int, - default=100, - help="单条记录 payload 字节数", - ) - parser.add_argument( - "--queue-only", - action="store_true", - help="仅扫描 Queue", - ) - parser.add_argument( - "--topic-only", - action="store_true", - help="仅扫描 Topic", - ) - parser.add_argument( - "--output", - type=str, - default=None, - help="结果 JSON 文件路径", - ) - args = parser.parse_args() - - prods = parse_concurrency(args.producers) - cons = parse_concurrency(args.consumers) - - system = await pul.actor_system() - storage_path = tempfile.mkdtemp(prefix="concurrency_sweep_") - results = {"queue": [], "topic": []} - - try: - if not args.topic_only: - print("Queue concurrency sweep...") - for P in prods: - for C in cons: - if C > args.num_buckets: - continue - r = await run_queue_concurrent( - system, - storage_path=storage_path, - num_producers=P, - num_consumers=C, - duration=args.duration, - num_buckets=args.num_buckets, - record_size=args.record_size, - ) - results["queue"].append(r) - print( - f" P={P} C={C} write={r['write_throughput_rec_s']:.0f} rec/s read={r['read_throughput_rec_s']:.0f} rec/s" - ) - - if not args.queue_only: - print("Topic concurrency sweep...") - for P in prods: - for C in cons: - r = await run_topic_concurrent( - system, - num_publishers=P, - num_subscribers=C, - duration=args.duration, - payload_size=args.record_size, - ) - results["topic"].append(r) - print( - f" P={P} C={C} publish={r['publish_throughput_msg_s']:.0f} msg/s delivered={r['delivered_throughput_msg_s']:.0f} msg/s" - ) - finally: - await system.shutdown() - shutil.rmtree(storage_path, ignore_errors=True) - - # 打印汇总表 - print() - print("=" * 72) - print("Concurrency Sweep Summary") - print("=" * 72) - - if results["queue"]: - print("\n--- Queue (rec/s) ---") - print(f"{'P':>3} {'C':>3} {'write_rec/s':>12} {'read_rec/s':>12}") - print("-" * 40) - for r in results["queue"]: - print( - f"{r['num_producers']:>3} {r['num_consumers']:>3} " - f"{r['write_throughput_rec_s']:>12.0f} {r['read_throughput_rec_s']:>12.0f}" - ) - - if results["topic"]: - print("\n--- Topic (msg/s) ---") - print(f"{'P':>3} {'C':>3} {'publish_msg/s':>14} {'delivered_msg/s':>16}") - print("-" * 50) - for r in results["topic"]: - print( - f"{r['num_publishers']:>3} {r['num_subscribers']:>3} " - f"{r['publish_throughput_msg_s']:>14.0f} {r['delivered_throughput_msg_s']:>16.0f}" - ) - - print("\n" + "=" * 72) - - if args.output: - with open(args.output, "w") as f: - json.dump( - { - "config": { - "duration_s": args.duration, - "num_buckets": args.num_buckets, - "record_size": args.record_size, - "producers": prods, - "consumers": cons, - }, - "results": results, - }, - f, - indent=2, - ) - print(f"Results written to {args.output}") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/benchmarks/large_scale_stress_test.py b/benchmarks/large_scale_stress_test.py deleted file mode 100755 index 64c3e8b59..000000000 --- a/benchmarks/large_scale_stress_test.py +++ /dev/null @@ -1,341 +0,0 @@ -#!/usr/bin/env python3 -""" -Large-Scale Stress Test Script - Multi-Process Version - -Usage: - torchrun --nproc_per_node=10 benchmarks/large_scale_stress_test.py \ - --duration 300 --rate 100 -""" - -import argparse -import asyncio -import json -import os -import random -import sys -import time -from collections import defaultdict -from dataclasses import dataclass, field - -import pulsing as pul -from pulsing.core import Actor, StreamMessage, SystemConfig - - -# ============================================================================ -# Statistics -# ============================================================================ - - -@dataclass -class Stats: - total: int = 0 - success: int = 0 - failed: int = 0 - latencies: list = field(default_factory=list) - errors: dict = field(default_factory=lambda: defaultdict(int)) - - def add(self, ok: bool, latency_ms: float, error: str = None): - self.total += 1 - if ok: - self.success += 1 - self.latencies.append(latency_ms) - else: - self.failed += 1 - if error: - self.errors[error[:50]] += 1 - - def summary(self): - lat = sorted(self.latencies) - pct = lambda p: lat[int(len(lat) * p / 100)] if lat else 0 - return { - "total": self.total, - "success": self.success, - "failed": self.failed, - "success_rate": self.success / self.total * 100 if self.total else 0, - "avg_ms": sum(lat) / len(lat) if lat else 0, - "p50_ms": pct(50), - "p95_ms": pct(95), - "p99_ms": pct(99), - "errors": dict(self.errors), - } - - -# ============================================================================ -# Workers - Using Simplified Message Format -# ============================================================================ - - -class EchoWorker(Actor): - async def receive(self, msg): - if isinstance(msg, dict) and msg.get("type") == "echo": - return {"echo": msg.get("text", "")} - - -class ComputeWorker(Actor): - async def receive(self, msg): - if isinstance(msg, dict) and msg.get("type") == "compute": - n = msg.get("n", 1000) - return {"result": sum(i * i for i in range(n))} - - -class StreamWorker(Actor): - async def receive(self, msg): - if isinstance(msg, dict) and msg.get("type") == "stream": - count = msg.get("count", 10) - delay = msg.get("delay", 0.01) - - stream_msg, writer = StreamMessage.create("items") - - async def produce(): - try: - for i in range(count): - await writer.write({"index": i, "ts": time.time()}) - await asyncio.sleep(delay) - await writer.close() - except Exception: - pass # Stream closed during shutdown, ignore - - asyncio.create_task(produce()) - return stream_msg - - -class BatchWorker(Actor): - def __init__(self): - self.batch = [] - - async def receive(self, msg): - if isinstance(msg, dict) and msg.get("type") == "batch": - self.batch.append(msg.get("item", 0)) - if len(self.batch) >= 10: - result = sum(self.batch) - self.batch = [] - return {"sum": result} - return {"count": len(self.batch)} - - -class StatefulWorker(Actor): - def __init__(self): - self.state = {} - - async def receive(self, msg): - if isinstance(msg, dict): - if msg.get("type") == "set": - self.state[msg["key"]] = msg["value"] - return {"ok": True} - if msg.get("type") == "get": - return {"value": self.state.get(msg["key"])} - - -WORKERS = { - "echo": EchoWorker, - "compute": ComputeWorker, - "stream": StreamWorker, - "batch": BatchWorker, - "stateful": StatefulWorker, -} - - -# ============================================================================ -# Stress Test -# ============================================================================ - - -async def run_benchmark(worker_refs, stats_req, stats_stream, duration, rate): - end_time = time.time() + duration - interval = 1.0 / rate if rate > 0 else 0 - - # Separate local and remote workers - local = {k: v for k, v in worker_refs.items() if "_remote_" not in k} - remote = {k: v for k, v in worker_refs.items() if "_remote_" in k} - - async def worker_loop(): - while time.time() < end_time: - # 70% remote, 30% local - use_remote = remote and (not local or random.random() < 0.7) - refs = remote if use_remote else local - - if not refs: - await asyncio.sleep(0.1) - continue - - key = random.choice(list(refs.keys())) - base_type = key.split("_remote_")[0] if "_remote_" in key else key - - # 70% single, 30% stream - if random.random() < 0.7 and base_type != "stream": - await send_request(refs[key], base_type, stats_req) - elif base_type == "stream": - await send_stream(refs[key], stats_stream) - else: - await send_request(refs[key], base_type, stats_req) - - if interval: - await asyncio.sleep(interval) - - tasks = [asyncio.create_task(worker_loop()) for _ in range(max(1, int(rate) // 10))] - - # Progress reporting - while time.time() < end_time: - await asyncio.sleep(10) - print(f" Requests: {stats_req.total} (ok: {stats_req.success})") - print(f" Streams: {stats_stream.total} (ok: {stats_stream.success})") - - for t in tasks: - t.cancel() - - -async def send_request(worker, wtype, stats): - start = time.time() - try: - if wtype == "echo": - msg = {"type": "echo", "text": f"msg_{random.randint(1, 1000)}"} - elif wtype == "compute": - msg = {"type": "compute", "n": random.randint(100, 5000)} - elif wtype == "batch": - msg = {"type": "batch", "item": random.randint(1, 100)} - else: # stateful - if random.random() < 0.5: - msg = { - "type": "set", - "key": f"k{random.randint(1, 100)}", - "value": random.randint(1, 1000), - } - else: - msg = {"type": "get", "key": f"k{random.randint(1, 100)}"} - - await worker.ask(msg) - stats.add(True, (time.time() - start) * 1000) - except Exception as e: - stats.add(False, (time.time() - start) * 1000, str(e)) - - -async def send_stream(worker, stats): - start = time.time() - try: - msg = {"type": "stream", "count": random.randint(5, 15), "delay": 0.01} - resp = await worker.ask(msg) - async for _ in resp.stream_reader(): - pass - stats.add(True, (time.time() - start) * 1000) - except Exception as e: - stats.add(False, (time.time() - start) * 1000, str(e)) - - -# ============================================================================ -# Main -# ============================================================================ - - -async def main(): - parser = argparse.ArgumentParser() - parser.add_argument("--duration", type=float, default=300) - parser.add_argument("--rate", type=float, default=100) - parser.add_argument("--seed-nodes", type=str, nargs="+", default=[]) - parser.add_argument("--port", type=int, default=0) - parser.add_argument("--stabilize-timeout", type=float, default=10) - parser.add_argument("--log-dir", type=str, default="benchmark_logs") - args = parser.parse_args() - - # Get torchrun information - rank = int(os.environ.get("RANK", 0)) - world_size = int(os.environ.get("WORLD_SIZE", 1)) - - os.makedirs(args.log_dir, exist_ok=True) - log_file = f"{args.log_dir}/stress_test_rank_{rank}.log" - - # Log output - class Tee: - def __init__(self, path, orig): - self.f = open(path, "w") - self.orig = orig - - def write(self, s): - self.f.write(s) - self.f.flush() - self.orig.write(s) - - def flush(self): - self.f.flush() - self.orig.flush() - - orig_stdout = sys.stdout - sys.stdout = Tee(log_file, orig_stdout) - sys.stderr = sys.stdout - - print(f"\n{'=' * 50}") - print(f"Stress Test - Process {rank}/{world_size}") - print(f"Duration: {args.duration}s, Rate: {args.rate}/s") - print(f"{'=' * 50}\n") - - # Configure system - port = (8000 if args.port == 0 else args.port) + rank - addr = f"0.0.0.0:{port}" - - seeds = None - if args.seed_nodes: - seeds = args.seed_nodes - elif rank > 0: - seeds = [f"127.0.0.1:{8000 + rank - 1}"] - - system = await pul.actor_system(addr=addr, seeds=seeds) - print(f"System started at {system.addr}") - - # Wait for cluster to stabilize - print(f"Waiting {args.stabilize_timeout}s for cluster...") - await asyncio.sleep(args.stabilize_timeout) - - members = await system.members() - print(f"Cluster members: {len(members)}") - - # Create local workers - worker_refs = {} - for name, cls in WORKERS.items(): - ref = await system.spawn(cls(), name=f"{name}_{rank}", public=True) - worker_refs[name] = ref - print(f" Spawned {name}_{rank}") - - await asyncio.sleep(args.stabilize_timeout) - - # Resolve remote workers - print("Resolving remote workers...") - for other_rank in range(world_size): - if other_rank == rank: - continue - for name in WORKERS: - try: - ref = await system.resolve_named(f"{name}_{other_rank}") - worker_refs[f"{name}_remote_{other_rank}"] = ref - except Exception: - pass - - print(f"Total workers: {len(worker_refs)}") - - # Run stress test - stats_req, stats_stream = Stats(), Stats() - try: - await run_benchmark( - worker_refs, stats_req, stats_stream, args.duration, args.rate - ) - except KeyboardInterrupt: - print("\nInterrupted") - - # Results - print(f"\n{'=' * 50}") - print(f"Results - Process {rank}") - print(f"{'=' * 50}") - result = {"requests": stats_req.summary(), "streams": stats_stream.summary()} - print(json.dumps(result, indent=2)) - - with open(f"{args.log_dir}/stress_test_stats_rank_{rank}.json", "w") as f: - json.dump(result, f, indent=2) - - # Wait 3 seconds for ongoing stream tasks to complete - print(f"[Process {rank}] Waiting 3s for streams to complete...") - await asyncio.sleep(3) - - await system.shutdown() - sys.stdout = orig_stdout - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/benchmarks/large_scale_stress_test_pulsing_single.py b/benchmarks/large_scale_stress_test_pulsing_single.py deleted file mode 100644 index 0f93a71bf..000000000 --- a/benchmarks/large_scale_stress_test_pulsing_single.py +++ /dev/null @@ -1,278 +0,0 @@ -#!/usr/bin/env python3 -""" -Pulsing Stress Test Script - Single Process Version - -Usage: - python benchmarks/large_scale_stress_test_pulsing_single.py \ - --duration 300 --rate 100 --num-workers 50 -""" - -import argparse -import asyncio -import json -import os -import random -import time -from collections import defaultdict -from dataclasses import dataclass, field - -import pulsing as pul -from pulsing.core import Actor, StreamMessage, SystemConfig - - -# ============================================================================ -# Statistics -# ============================================================================ - - -@dataclass -class Stats: - total: int = 0 - success: int = 0 - failed: int = 0 - latencies: list = field(default_factory=list) - errors: dict = field(default_factory=lambda: defaultdict(int)) - - def add(self, ok: bool, latency_ms: float, error: str = None): - self.total += 1 - if ok: - self.success += 1 - self.latencies.append(latency_ms) - else: - self.failed += 1 - if error: - self.errors[error[:50]] += 1 - - def summary(self): - lat = sorted(self.latencies) - pct = lambda p: lat[int(len(lat) * p / 100)] if lat else 0 - return { - "total": self.total, - "success": self.success, - "failed": self.failed, - "success_rate": self.success / self.total * 100 if self.total else 0, - "avg_ms": sum(lat) / len(lat) if lat else 0, - "p50_ms": pct(50), - "p95_ms": pct(95), - "p99_ms": pct(99), - "errors": dict(self.errors), - } - - -# ============================================================================ -# Workers - Using Simplified Message Format -# ============================================================================ - - -class EchoWorker(Actor): - async def receive(self, msg): - if isinstance(msg, dict) and msg.get("type") == "echo": - return {"echo": msg.get("text", "")} - - -class ComputeWorker(Actor): - async def receive(self, msg): - if isinstance(msg, dict) and msg.get("type") == "compute": - n = msg.get("n", 1000) - return {"result": sum(i * i for i in range(n))} - - -class StreamWorker(Actor): - async def receive(self, msg): - if isinstance(msg, dict) and msg.get("type") == "stream": - count = msg.get("count", 10) - delay = msg.get("delay", 0.01) - - stream_msg, writer = StreamMessage.create("items") - - async def produce(): - try: - for i in range(count): - await writer.write({"index": i, "ts": time.time()}) - await asyncio.sleep(delay) - await writer.close() - except Exception: - pass # Stream closed during shutdown, ignore - - asyncio.create_task(produce()) - return stream_msg - - -class BatchWorker(Actor): - def __init__(self): - self.batch = [] - - async def receive(self, msg): - if isinstance(msg, dict) and msg.get("type") == "batch": - self.batch.append(msg.get("item", 0)) - if len(self.batch) >= 10: - result = sum(self.batch) - self.batch = [] - return {"sum": result} - return {"count": len(self.batch)} - - -class StatefulWorker(Actor): - def __init__(self): - self.state = {} - - async def receive(self, msg): - if isinstance(msg, dict): - if msg.get("type") == "set": - self.state[msg["key"]] = msg["value"] - return {"ok": True} - if msg.get("type") == "get": - return {"value": self.state.get(msg["key"])} - - -WORKERS = { - "echo": EchoWorker, - "compute": ComputeWorker, - "stream": StreamWorker, - "batch": BatchWorker, - "stateful": StatefulWorker, -} - - -# ============================================================================ -# Stress Test -# ============================================================================ - - -async def run_benchmark(workers, stats_req, stats_stream, duration, rate): - end_time = time.time() + duration - interval = 1.0 / rate if rate > 0 else 0 - - async def worker_loop(): - while time.time() < end_time: - # 70% single, 30% stream - if random.random() < 0.7: - await send_request(workers, stats_req) - else: - await send_stream(workers, stats_stream) - if interval: - await asyncio.sleep(interval) - - tasks = [asyncio.create_task(worker_loop()) for _ in range(max(1, int(rate) // 10))] - - # Progress reporting - while time.time() < end_time: - await asyncio.sleep(10) - print(f" Requests: {stats_req.total} (ok: {stats_req.success})") - print(f" Streams: {stats_stream.total} (ok: {stats_stream.success})") - - for t in tasks: - t.cancel() - - -async def send_request(workers, stats): - wtype = random.choice(["echo", "compute", "batch", "stateful"]) - if wtype not in workers: - return - - worker = random.choice(workers[wtype]) - start = time.time() - - try: - if wtype == "echo": - msg = {"type": "echo", "text": f"msg_{random.randint(1, 1000)}"} - elif wtype == "compute": - msg = {"type": "compute", "n": random.randint(100, 5000)} - elif wtype == "batch": - msg = {"type": "batch", "item": random.randint(1, 100)} - else: # stateful - if random.random() < 0.5: - msg = { - "type": "set", - "key": f"k{random.randint(1, 100)}", - "value": random.randint(1, 1000), - } - else: - msg = {"type": "get", "key": f"k{random.randint(1, 100)}"} - - await worker.ask(msg) - stats.add(True, (time.time() - start) * 1000) - except Exception as e: - stats.add(False, (time.time() - start) * 1000, str(e)) - - -async def send_stream(workers, stats): - if "stream" not in workers: - return - - worker = random.choice(workers["stream"]) - start = time.time() - - try: - msg = {"type": "stream", "count": random.randint(5, 15), "delay": 0.01} - resp = await worker.ask(msg) - async for _ in resp.stream_reader(): - pass - stats.add(True, (time.time() - start) * 1000) - except Exception as e: - stats.add(False, (time.time() - start) * 1000, str(e)) - - -# ============================================================================ -# Main -# ============================================================================ - - -async def main(): - parser = argparse.ArgumentParser() - parser.add_argument("--duration", type=float, default=30) - parser.add_argument("--rate", type=float, default=100) - parser.add_argument("--num-workers", type=int, default=50) - parser.add_argument("--port", type=int, default=8000) - parser.add_argument("--log-dir", type=str, default="benchmark_logs") - args = parser.parse_args() - - os.makedirs(args.log_dir, exist_ok=True) - - print(f"\n{'=' * 50}") - print("Pulsing Stress Test (Single Process)") - print( - f"Duration: {args.duration}s, Rate: {args.rate}/s, Workers: {args.num_workers}" - ) - print(f"{'=' * 50}\n") - - system = await pul.actor_system(addr=f"0.0.0.0:{args.port}") - print(f"System started at {system.addr}") - - # Create workers - workers = {} - for name, cls in WORKERS.items(): - workers[name] = [] - for i in range(args.num_workers): - ref = await system.spawn(cls(), name=f"{name}_{i}") - workers[name].append(ref) - print(f"Created {args.num_workers} {name} workers") - - await asyncio.sleep(1) - - # Run stress test - stats_req, stats_stream = Stats(), Stats() - try: - await run_benchmark(workers, stats_req, stats_stream, args.duration, args.rate) - except KeyboardInterrupt: - print("\nInterrupted") - - # Results - print(f"\n{'=' * 50}") - print("Results") - print(f"{'=' * 50}") - result = {"requests": stats_req.summary(), "streams": stats_stream.summary()} - print(json.dumps(result, indent=2)) - - with open(f"{args.log_dir}/stress_test_pulsing_single.json", "w") as f: - json.dump(result, f, indent=2) - - # Wait 3 seconds for ongoing stream tasks to complete - print("Waiting 3s for streams to complete...") - await asyncio.sleep(3) - - await system.shutdown() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/benchmarks/large_scale_stress_test_ray.py b/benchmarks/large_scale_stress_test_ray.py deleted file mode 100644 index 62078cde9..000000000 --- a/benchmarks/large_scale_stress_test_ray.py +++ /dev/null @@ -1,801 +0,0 @@ -#!/usr/bin/env python3 -""" -Large-Scale Stress Test Script - Ray Version -Equivalent to large_scale_stress_test.py, for performance comparison - -Usage: - torchrun --nproc_per_node=10 benchmarks/large_scale_stress_test_ray.py \ - --duration 300 \ - --rate 100 -""" - -import argparse -import asyncio -import json -import os -import random -import sys -import time -from collections import defaultdict -from dataclasses import dataclass, field - -try: - import ray # type: ignore -except ImportError: - print("Error: Ray is not installed. Please install it with: pip install ray") - sys.exit(1) - - -# ============================================================================ -# Stress Test Statistics -# ============================================================================ - - -@dataclass -class StressTestStats: - """Stress test statistics""" - - total_requests: int = 0 - total_streams: int = 0 - successful_requests: int = 0 - successful_streams: int = 0 - failed_requests: int = 0 - failed_streams: int = 0 - total_latency_ms: float = 0.0 - total_stream_latency_ms: float = 0.0 - request_latencies: list[float] = field(default_factory=list) - stream_latencies: list[float] = field(default_factory=list) - errors: dict[str, int] = field(default_factory=lambda: defaultdict(int)) - health_warnings: list[str] = field(default_factory=list) - - def add_health_warning(self, warning: str): - """Add health warning""" - self.health_warnings.append(f"{time.time()}: {warning}") - - def add_request(self, success: bool, latency_ms: float, error: str | None = None): - self.total_requests += 1 - if success: - self.successful_requests += 1 - self.total_latency_ms += latency_ms - self.request_latencies.append(latency_ms) - else: - self.failed_requests += 1 - if error: - self.errors[error] += 1 - - def add_stream(self, success: bool, latency_ms: float, error: str | None = None): - self.total_streams += 1 - if success: - self.successful_streams += 1 - self.total_stream_latency_ms += latency_ms - self.stream_latencies.append(latency_ms) - else: - self.failed_streams += 1 - if error: - self.errors[error] += 1 - - def get_summary(self) -> dict: - """Get statistics summary""" - avg_latency = ( - self.total_latency_ms / self.successful_requests - if self.successful_requests > 0 - else 0.0 - ) - avg_stream_latency = ( - self.total_stream_latency_ms / self.successful_streams - if self.successful_streams > 0 - else 0.0 - ) - - request_latencies_sorted = sorted(self.request_latencies) - stream_latencies_sorted = sorted(self.stream_latencies) - - def percentile(data: list[float], p: float) -> float: - if not data: - return 0.0 - idx = int(len(data) * p / 100) - return data[min(idx, len(data) - 1)] - - return { - "requests": { - "total": self.total_requests, - "successful": self.successful_requests, - "failed": self.failed_requests, - "success_rate": ( - self.successful_requests / self.total_requests * 100 - if self.total_requests > 0 - else 0.0 - ), - "avg_latency_ms": avg_latency, - "p50_latency_ms": percentile(request_latencies_sorted, 50), - "p95_latency_ms": percentile(request_latencies_sorted, 95), - "p99_latency_ms": percentile(request_latencies_sorted, 99), - }, - "streams": { - "total": self.total_streams, - "successful": self.successful_streams, - "failed": self.failed_streams, - "success_rate": ( - self.successful_streams / self.total_streams * 100 - if self.total_streams > 0 - else 0.0 - ), - "avg_latency_ms": avg_stream_latency, - "p50_latency_ms": percentile(stream_latencies_sorted, 50), - "p95_latency_ms": percentile(stream_latencies_sorted, 95), - "p99_latency_ms": percentile(stream_latencies_sorted, 99), - }, - "errors": dict(self.errors), - "health_warnings": self.health_warnings[-10:], # Keep only last 10 warnings - } - - -# ============================================================================ -# 5 Different Worker Actors (Ray Version) -# ============================================================================ - - -@ray.remote -class EchoWorker: - """Echo Worker - Simple echo""" - - async def echo(self, text: str) -> dict: - """Async method, equivalent to Pulsing version""" - return {"echo": text} - - -@ray.remote -class ComputeWorker: - """Compute Worker - Compute intensive""" - - async def compute(self, n: int) -> dict: - """Async method, equivalent to Pulsing version""" - # Simulate computation - result = sum(i * i for i in range(n)) - return {"result": result} - - -@ray.remote -class StreamWorker: - """Stream Worker - Streamed response""" - - async def generate_stream(self, count: int, delay: float) -> list[dict]: - """Generate streamed data (using async, equivalent to Pulsing version) - - Note: Ray supports async def, can use asyncio.sleep for true async delays. - This is more efficient than time.sleep as it doesn't block threads. - """ - result = [] - for i in range(count): - result.append( - { - "index": i, - "value": f"item_{i}", - "timestamp": time.time(), - } - ) - # Use asyncio.sleep, fully equivalent to Pulsing version - await asyncio.sleep(delay) - return result - - -@ray.remote -class BatchWorker: - """Batch Worker - Batch processing""" - - def __init__(self): - self.batch = [] - self.batch_size = 10 - - async def batch_add(self, item: int) -> dict: - """Async method, equivalent to Pulsing version""" - self.batch.append(item) - - if len(self.batch) >= self.batch_size: - result = sum(self.batch) - self.batch = [] - return {"sum": result} - return {"count": len(self.batch)} - - -@ray.remote -class StatefulWorker: - """Stateful Worker - Stateful processing""" - - def __init__(self): - self.state = {} - self.counter = 0 - - async def set_state(self, key: str, value: int) -> dict: - """Async method, equivalent to Pulsing version""" - self.state[key] = value - self.counter += 1 - return {"counter": self.counter} - - async def get_state(self, key: str) -> dict: - """Async method, equivalent to Pulsing version""" - value = self.state.get(key) - return {"key": key, "value": value} - - -# Worker type mapping -WORKER_TYPES = { - "echo": EchoWorker, - "compute": ComputeWorker, - "stream": StreamWorker, - "batch": BatchWorker, - "stateful": StatefulWorker, -} - - -# ============================================================================ -# Stress Test Client -# ============================================================================ - - -class StressTestClient: - """Stress test client""" - - def __init__( - self, - worker_refs: dict[str, ray.actor.ActorHandle], - stats: StressTestStats, - rate: float = 100.0, - expected_nodes: int = 10, - expected_worker_types: list[str] = None, - ): - self.worker_refs = worker_refs - self.stats = stats - self.rate = rate # Requests per second - self.interval = 1.0 / rate if rate > 0 else 0.0 - self.running = True - self.expected_nodes = expected_nodes - self.expected_worker_types = expected_worker_types or [ - "echo", - "compute", - "stream", - "batch", - "stateful", - ] - self.health_check_interval = 30.0 # Check health every 30 seconds - self.remote_requests = 0 # Remote request count - self.local_requests = 0 # Local request count - - def _extract_base_worker_type(self, worker_type: str) -> str: - """Extract base type from worker_type""" - if "_remote_" in worker_type: - return worker_type.split("_remote_")[0] - - if worker_type in ["echo", "compute", "stream", "batch", "stateful"]: - return worker_type - - parts = worker_type.split("_") - if len(parts) > 0 and parts[0] in [ - "echo", - "compute", - "stream", - "batch", - "stateful", - ]: - return parts[0] - - return worker_type - - async def send_single_request(self, worker_type: str) -> bool: - """Send a single request (async, equivalent to Pulsing version)""" - if worker_type not in self.worker_refs: - return False - - worker_ref = self.worker_refs[worker_type] - start_time = time.time() - - try: - base_type = self._extract_base_worker_type(worker_type) - - if base_type not in ["echo", "compute", "batch", "stateful"]: - return False - - # Generate request parameters - # Ray's remote() returns ObjectRef, for async methods, can directly await ObjectRef - if base_type == "echo": - payload = {"text": f"echo_{random.randint(1, 1000)}"} - result = await worker_ref.echo.remote(payload["text"]) - elif base_type == "compute": - payload = {"n": random.randint(100, 10000)} - result = await worker_ref.compute.remote(payload["n"]) - elif base_type == "batch": - payload = {"item": random.randint(1, 100)} - result = await worker_ref.batch_add.remote(payload["item"]) - elif base_type == "stateful": - msg_type = random.choice(["SetState", "GetState"]) - if msg_type == "SetState": - payload = { - "key": f"key_{random.randint(1, 100)}", - "value": random.randint(1, 1000), - } - result = await worker_ref.set_state.remote( - payload["key"], payload["value"] - ) - else: - payload = {"key": f"key_{random.randint(1, 100)}"} - result = await worker_ref.get_state.remote(payload["key"]) - - if result is None: - raise ValueError("Empty response from actor") - - latency_ms = (time.time() - start_time) * 1000 - self.stats.add_request(True, latency_ms) - return True - - except Exception as e: - latency_ms = (time.time() - start_time) * 1000 - error_msg = str(e)[:100] - self.stats.add_request(False, latency_ms, error_msg) - return False - - async def send_stream_request(self, worker_type: str) -> bool: - """Send a stream request (async, equivalent to Pulsing version)""" - base_type = self._extract_base_worker_type(worker_type) - if base_type != "stream": - return False - - stream_worker_key = None - if worker_type in self.worker_refs and base_type == "stream": - stream_worker_key = worker_type - elif "stream" in self.worker_refs: - stream_worker_key = "stream" - else: - for key in self.worker_refs.keys(): - if self._extract_base_worker_type(key) == "stream": - stream_worker_key = key - break - - if stream_worker_key is None or stream_worker_key not in self.worker_refs: - return False - - worker_ref = self.worker_refs[stream_worker_key] - start_time = time.time() - - try: - count = random.randint(5, 20) - delay = random.uniform(0.01, 0.05) - - # Ray's stream processing: use async methods, equivalent to Pulsing version - # Ray's remote() returns ObjectRef, can directly await to get result - stream_items = await worker_ref.generate_stream.remote(count, delay) - - chunk_count = 0 - for _chunk in stream_items: - chunk_count += 1 - - latency_ms = (time.time() - start_time) * 1000 - self.stats.add_stream(True, latency_ms) - return True - - except Exception as e: - latency_ms = (time.time() - start_time) * 1000 - error_msg = str(e)[:100] - self.stats.add_stream(False, latency_ms, error_msg) - return False - - async def check_cluster_health(self) -> tuple[bool, str]: - """Check cluster health status""" - try: - # Ray cluster information - cluster_resources = ray.cluster_resources() - _available_resources = ray.available_resources() # noqa: F841 - - # Check node count (inferred from resource information) - num_nodes = cluster_resources.get("node:__internal__:__head_node__", 0) - if num_nodes == 0: - # Try other ways to get node count - num_nodes = len( - [k for k in cluster_resources.keys() if k.startswith("node:")] - ) - - # Simplified health check: check if workers are available - missing_workers = [] - for worker_type in self.expected_worker_types: - if worker_type not in self.worker_refs: - missing_workers.append(worker_type) - - if missing_workers: - return False, f"Missing workers: {missing_workers}" - - return True, f"Cluster healthy with {len(self.worker_refs)} workers" - - except Exception as e: - return False, f"Health check error: {e}" - - async def run_stress_test(self, duration: float): - """Run stress test""" - end_time = time.time() + duration - last_health_check = time.time() - report_interval = 10.0 - - print(f"[StressTest] Starting stress test for {duration}s at {self.rate} req/s") - print( - f"[StressTest] Expected: {self.expected_nodes} nodes, {len(self.expected_worker_types)} worker types per node" - ) - - # Initial health check - is_healthy, health_msg = await self.check_cluster_health() - if not is_healthy: - print(f"[StressTest] ⚠️ WARNING: Initial health check failed: {health_msg}") - else: - print(f"[StressTest] ✓ Initial health check passed: {health_msg}") - - async def worker_loop(): - """Worker loop (async version, equivalent to Pulsing version)""" - local_worker_types = ["echo", "compute", "stream", "batch", "stateful"] - local_workers = [wt for wt in local_worker_types if wt in self.worker_refs] - remote_workers = [wt for wt in self.worker_refs.keys() if "_remote_" in wt] - - if not local_workers and not remote_workers: - print("[StressTest] Warning: No workers available!") - return - - use_remote_probability = 0.7 - - while self.running and time.time() < end_time: - # Select worker - if remote_workers and ( - not local_workers or random.random() < use_remote_probability - ): - worker_type = random.choice(remote_workers) - self.remote_requests += 1 - elif local_workers: - worker_type = random.choice(local_workers) - self.local_requests += 1 - else: - worker_type = random.choice(remote_workers) - self.remote_requests += 1 - - # Randomly choose single or stream - if random.random() < 0.7: - await self.send_single_request(worker_type) - else: - base_type = self._extract_base_worker_type(worker_type) - if base_type == "stream": - await self.send_stream_request(worker_type) - else: - await self.send_single_request(worker_type) - - # Control rate (use asyncio.sleep, equivalent to Pulsing version) - if self.interval > 0: - await asyncio.sleep(self.interval) - - # Start multiple concurrent workers (use asyncio coroutines, equivalent to Pulsing version) - num_workers = max(1, int(self.rate / 10)) - tasks = [asyncio.create_task(worker_loop()) for _ in range(num_workers)] - - # Periodic reporting and health checks - async def report_loop(): - nonlocal last_health_check - while self.running and time.time() < end_time: - await asyncio.sleep(report_interval) - summary = self.stats.get_summary() - print("\n[StressTest] Progress Report:") - print( - f" Requests: {summary['requests']['total']} " - f"(success: {summary['requests']['successful']}, " - f"failed: {summary['requests']['failed']})" - ) - print( - f" Streams: {summary['streams']['total']} " - f"(success: {summary['streams']['successful']}, " - f"failed: {summary['streams']['failed']})" - ) - if summary["requests"]["successful"] > 0: - print( - f" Avg Latency: {summary['requests']['avg_latency_ms']:.2f}ms" - ) - - total_worker_requests = self.remote_requests + self.local_requests - if total_worker_requests > 0: - remote_pct = self.remote_requests / total_worker_requests * 100 - local_pct = self.local_requests / total_worker_requests * 100 - print( - f" Worker Selection: {remote_pct:.1f}% remote, {local_pct:.1f}% local" - ) - - if time.time() - last_health_check >= self.health_check_interval: - is_healthy, health_msg = await self.check_cluster_health() - if is_healthy: - print(f" ✓ Cluster Health: {health_msg}") - else: - print(f" ⚠️ Cluster Health Warning: {health_msg}") - self.stats.add_health_warning(health_msg) - last_health_check = time.time() - - report_task = asyncio.create_task(report_loop()) - - # Wait for all tasks to complete (use asyncio, equivalent to Pulsing version) - await asyncio.gather(*tasks, report_task) - - self.running = False - print("\n[StressTest] Stress test completed") - - -# ============================================================================ -# Main Function -# ============================================================================ - - -async def main(): - parser = argparse.ArgumentParser( - description="Large-Scale Stress Test Script - Ray Version" - ) - parser.add_argument( - "--duration", - type=float, - default=300.0, - help="Stress test duration (seconds)", - ) - parser.add_argument( - "--rate", - type=float, - default=100.0, - help="Requests per second (0 means unlimited)", - ) - parser.add_argument( - "--address", - type=str, - default=None, - help="Ray cluster address (e.g., ray://head-node:10001)", - ) - parser.add_argument( - "--local-rank", - type=int, - default=0, - help="Local rank (set automatically by torchrun)", - ) - parser.add_argument( - "--world-size", - type=int, - default=1, - help="Total number of processes (set automatically by torchrun)", - ) - parser.add_argument( - "--stabilize-timeout", - type=float, - default=10.0, - help="Cluster stabilization wait time (seconds), default 10", - ) - parser.add_argument( - "--log-dir", - type=str, - default="benchmark_logs", - help="Log file directory, default benchmark_logs", - ) - - args = parser.parse_args() - - # Get torchrun information from environment variables - local_rank = int(os.environ.get("LOCAL_RANK", args.local_rank)) - world_size = int(os.environ.get("WORLD_SIZE", args.world_size)) - rank = int(os.environ.get("RANK", local_rank)) - - # Setup log file - log_dir = args.log_dir - os.makedirs(log_dir, exist_ok=True) - log_file = os.path.join(log_dir, f"stress_test_ray_rank_{rank}.log") - - # Create file log handler - class TeeOutput: - """Output to both console and file""" - - def __init__(self, file_path, original_stdout): - self.file = open(file_path, "w", encoding="utf-8") - self.original_stdout = original_stdout - - def write(self, text): - try: - self.file.write(text) - self.file.flush() - except Exception: - pass - try: - self.original_stdout.write(text) - self.original_stdout.flush() - except Exception: - pass - - def flush(self): - try: - self.file.flush() - except Exception: - pass - try: - self.original_stdout.flush() - except Exception: - pass - - def fileno(self): - """Return file descriptor (required by Ray)""" - return self.original_stdout.fileno() - - def isatty(self): - """Check if it's a terminal""" - return self.original_stdout.isatty() - - def readable(self): - """Check if readable""" - return False - - def writable(self): - """Check if writable""" - return True - - def seekable(self): - """Check if seekable""" - return False - - def close(self): - try: - self.file.close() - except Exception: - pass - - original_stdout = sys.stdout - original_stderr = sys.stderr - - tee = TeeOutput(log_file, original_stdout) - sys.stdout = tee - sys.stderr = tee - - print(f"\n{'=' * 60}") - print(f"Stress Test Process {rank}/{world_size} (Ray Version)") - print(f"Local Rank: {local_rank}, World Size: {world_size}") - print(f"Log file: {log_file}") - print(f"{'=' * 60}\n") - - # Initialize Ray - # ⚠️ Important: Ray in torchrun multi-process environment, each process is independent - # Each process creates its own Ray instance, causing huge resource consumption - # Solution: Strictly limit resource usage per process - if not ray.is_initialized(): - if args.address: - # Connect to specified Ray cluster (recommended approach) - ray.init(address=args.address, ignore_reinit_error=True) - print(f"[Process {rank}] Connected to Ray cluster at {args.address}") - else: - # Local mode: each process creates independent Ray instance, but strictly limit resources - # Key: limit CPU, memory, disable unnecessary features - # Each process uses at most 1 CPU core to avoid resource exhaustion - num_cpus = 1 - # Limit object store memory to 100MB (very conservative) - object_store_memory = 100_000_000 - - ray.init( - num_cpus=num_cpus, - num_gpus=0, # Don't use GPU - object_store_memory=object_store_memory, - ignore_reinit_error=True, - include_dashboard=False, # Disable dashboard to reduce resource consumption - _temp_dir=f"/tmp/ray_rank_{rank}", # Independent temp directory per process - ) - print( - f"[Process {rank}] Ray initialized: {num_cpus} CPU, " - f"{object_store_memory / 1e6:.0f}MB object store" - ) - - print(f"[Process {rank}] Ray initialized") - print(f"[Process {rank}] Ray cluster resources: {ray.cluster_resources()}") - - # Wait for cluster to stabilize - stabilize_timeout = args.stabilize_timeout - print( - f"[Process {rank}] Waiting for cluster to stabilize ({stabilize_timeout}s)..." - ) - await asyncio.sleep(stabilize_timeout) - - # Create 5 types of workers (each process creates them) - worker_refs = {} - worker_names = ["echo", "compute", "stream", "batch", "stateful"] - - print(f"\n[Process {rank}] Spawning workers...") - for worker_name in worker_names: - try: - worker_class = WORKER_TYPES[worker_name] - worker_ref = worker_class.options(name=f"{worker_name}_{rank}").remote() - worker_refs[worker_name] = worker_ref - print(f" ✓ Spawned {worker_name} worker") - except Exception as e: - print(f" ✗ Failed to spawn {worker_name} worker: {e}") - - # Wait for all processes to start workers - print( - f"[Process {rank}] Waiting for all workers to register ({stabilize_timeout}s)..." - ) - await asyncio.sleep(stabilize_timeout) - - # Try to resolve workers from other processes (for cross-process communication) - print(f"\n[Process {rank}] Resolving remote workers...") - resolved_count = 0 - for other_rank in range(world_size): - if other_rank == rank: - continue - - for worker_name in worker_names: - try: - # Ray gets actor by name - remote_ref = ray.get_actor(f"{worker_name}_{other_rank}") - worker_refs[f"{worker_name}_remote_{other_rank}"] = remote_ref - resolved_count += 1 - if resolved_count <= 5: - print(f" ✓ Resolved {worker_name}_{other_rank}") - except Exception as e: - if resolved_count < 5: - print(f" ✗ Failed to resolve {worker_name}_{other_rank}: {e}") - - if resolved_count > 5: - print(f" ... and {resolved_count - 5} more workers resolved") - - total_expected = (world_size - 1) * len(worker_names) - if resolved_count < total_expected: - print( - f" ⚠️ Warning: Only resolved {resolved_count}/{total_expected} remote workers" - ) - - # Create stress test client - stats = StressTestStats() - client = StressTestClient( - worker_refs, - stats, - rate=args.rate, - expected_nodes=world_size, - expected_worker_types=["echo", "compute", "stream", "batch", "stateful"], - ) - - # Run stress test - try: - await client.run_stress_test(args.duration) - except KeyboardInterrupt: - print(f"\n[Process {rank}] Interrupted by user") - client.running = False - except Exception as e: - print(f"\n[Process {rank}] Error during stress test: {e}") - import traceback - - traceback.print_exc() - raise - - # Print final statistics - print(f"\n{'=' * 60}") - print(f"Final Statistics - Process {rank} (Ray Version)") - print(f"{'=' * 60}") - summary = stats.get_summary() - print(json.dumps(summary, indent=2)) - - # Save statistics to file - stats_dir = args.log_dir - os.makedirs(stats_dir, exist_ok=True) - stats_file = os.path.join(stats_dir, f"stress_test_stats_ray_rank_{rank}.json") - with open(stats_file, "w") as f: - json.dump(summary, f, indent=2) - print(f"\n[Process {rank}] Statistics saved to {stats_file}") - - # Shutdown Ray (optional, as other processes may still be using it) - # ray.shutdown() - print(f"[Process {rank}] Shutdown complete") - - # Restore stdout/stderr and close log file - if hasattr(sys.stdout, "close"): - try: - sys.stdout.close() - except Exception: - pass - sys.stdout = original_stdout - sys.stderr = original_stderr - - -if __name__ == "__main__": - try: - asyncio.run(main()) - except Exception as e: - import traceback - - print(f"\n[FATAL ERROR] Process failed: {e}") - print(traceback.format_exc()) - sys.exit(1) diff --git a/benchmarks/large_scale_stress_test_ray_single.py b/benchmarks/large_scale_stress_test_ray_single.py deleted file mode 100644 index 3f6a584b6..000000000 --- a/benchmarks/large_scale_stress_test_ray_single.py +++ /dev/null @@ -1,444 +0,0 @@ -#!/usr/bin/env python3 -""" -Ray Stress Test Script - Single Process Version (Correct Ray Usage with Generators) - -Ray is designed as a single driver process + multiple Actors, should not use torchrun multi-process mode. -This script creates multiple Actors within a single process, simulating equivalent load to Pulsing. - -This version uses Ray Generators for streaming, providing fair comparison with Pulsing's streaming. - -Usage: - python benchmarks/large_scale_stress_test_ray_single.py \ - --duration 300 \ - --rate 100 \ - --num-workers 50 -""" - -import argparse -import asyncio -import json -import os -import random -import sys -import time -from collections import defaultdict -from dataclasses import dataclass, field - -try: - import ray -except ImportError: - print("Error: Ray is not installed. Please install it with: pip install ray") - sys.exit(1) - - -# ============================================================================ -# Stress Test Statistics -# ============================================================================ - - -@dataclass -class StressTestStats: - """Stress test statistics""" - - total_requests: int = 0 - total_streams: int = 0 - successful_requests: int = 0 - successful_streams: int = 0 - failed_requests: int = 0 - failed_streams: int = 0 - total_latency_ms: float = 0.0 - total_stream_latency_ms: float = 0.0 - request_latencies: list[float] = field(default_factory=list) - stream_latencies: list[float] = field(default_factory=list) - errors: dict[str, int] = field(default_factory=lambda: defaultdict(int)) - - def add_request(self, success: bool, latency_ms: float, error: str | None = None): - self.total_requests += 1 - if success: - self.successful_requests += 1 - self.total_latency_ms += latency_ms - self.request_latencies.append(latency_ms) - else: - self.failed_requests += 1 - if error: - self.errors[error] += 1 - - def add_stream(self, success: bool, latency_ms: float, error: str | None = None): - self.total_streams += 1 - if success: - self.successful_streams += 1 - self.total_stream_latency_ms += latency_ms - self.stream_latencies.append(latency_ms) - else: - self.failed_streams += 1 - if error: - self.errors[error] += 1 - - def get_summary(self) -> dict: - avg_latency = ( - self.total_latency_ms / self.successful_requests - if self.successful_requests > 0 - else 0.0 - ) - avg_stream_latency = ( - self.total_stream_latency_ms / self.successful_streams - if self.successful_streams > 0 - else 0.0 - ) - - request_latencies_sorted = sorted(self.request_latencies) - stream_latencies_sorted = sorted(self.stream_latencies) - - def percentile(data: list[float], p: float) -> float: - if not data: - return 0.0 - idx = int(len(data) * p / 100) - return data[min(idx, len(data) - 1)] - - return { - "requests": { - "total": self.total_requests, - "successful": self.successful_requests, - "failed": self.failed_requests, - "success_rate": ( - self.successful_requests / self.total_requests * 100 - if self.total_requests > 0 - else 0.0 - ), - "avg_latency_ms": avg_latency, - "p50_latency_ms": percentile(request_latencies_sorted, 50), - "p95_latency_ms": percentile(request_latencies_sorted, 95), - "p99_latency_ms": percentile(request_latencies_sorted, 99), - }, - "streams": { - "total": self.total_streams, - "successful": self.successful_streams, - "failed": self.failed_streams, - "success_rate": ( - self.successful_streams / self.total_streams * 100 - if self.total_streams > 0 - else 0.0 - ), - "avg_latency_ms": avg_stream_latency, - "p50_latency_ms": percentile(stream_latencies_sorted, 50), - "p95_latency_ms": percentile(stream_latencies_sorted, 95), - "p99_latency_ms": percentile(stream_latencies_sorted, 99), - }, - "errors": dict(self.errors), - } - - -# ============================================================================ -# Ray Actor Definitions -# ============================================================================ - - -@ray.remote -class EchoWorker: - """Echo Worker - Simple echo""" - - async def echo(self, text: str) -> dict: - return {"echo": text} - - -@ray.remote -class ComputeWorker: - """Compute Worker - Compute intensive""" - - async def compute(self, n: int) -> dict: - result = sum(i * i for i in range(n)) - return {"result": result} - - -@ray.remote -class StreamWorker: - """Stream Worker - Streamed response using Ray Generators""" - - async def generate_stream(self, count: int, delay: float): - """Generate stream using yield (Ray Generator)""" - for i in range(count): - await asyncio.sleep(delay) - yield { - "index": i, - "value": f"item_{i}", - "timestamp": time.time(), - } - - -@ray.remote -class BatchWorker: - """Batch Worker - Batch processing""" - - def __init__(self): - self.batch = [] - self.batch_size = 10 - - async def batch_add(self, item: int) -> dict: - self.batch.append(item) - if len(self.batch) >= self.batch_size: - result = sum(self.batch) - self.batch = [] - return {"sum": result} - return {"count": len(self.batch)} - - -@ray.remote -class StatefulWorker: - """Stateful Worker - Stateful processing""" - - def __init__(self): - self.state = {} - self.counter = 0 - - async def set_state(self, key: str, value: int) -> dict: - self.state[key] = value - self.counter += 1 - return {"counter": self.counter} - - async def get_state(self, key: str) -> dict: - value = self.state.get(key) - return {"key": key, "value": value} - - -WORKER_CLASSES = { - "echo": EchoWorker, - "compute": ComputeWorker, - "stream": StreamWorker, - "batch": BatchWorker, - "stateful": StatefulWorker, -} - - -# ============================================================================ -# Stress Test Client -# ============================================================================ - - -class StressTestClient: - """Stress test client""" - - def __init__( - self, - workers: dict[str, list], # {worker_type: [actor_handles]} - stats: StressTestStats, - rate: float = 100.0, - ): - self.workers = workers - self.stats = stats - self.rate = rate - self.interval = 1.0 / rate if rate > 0 else 0.0 - self.running = True - - async def send_single_request(self) -> bool: - """Send a single request""" - # Randomly select worker type - worker_types = ["echo", "compute", "batch", "stateful"] - worker_type = random.choice(worker_types) - - if worker_type not in self.workers or not self.workers[worker_type]: - return False - - # Randomly select a worker of this type - worker = random.choice(self.workers[worker_type]) - start_time = time.time() - - try: - if worker_type == "echo": - await worker.echo.remote(f"echo_{random.randint(1, 1000)}") - elif worker_type == "compute": - await worker.compute.remote(random.randint(100, 10000)) - elif worker_type == "batch": - await worker.batch_add.remote(random.randint(1, 100)) - elif worker_type == "stateful": - if random.random() < 0.5: - await worker.set_state.remote( - f"key_{random.randint(1, 100)}", random.randint(1, 1000) - ) - else: - await worker.get_state.remote(f"key_{random.randint(1, 100)}") - - latency_ms = (time.time() - start_time) * 1000 - self.stats.add_request(True, latency_ms) - return True - - except Exception as e: - latency_ms = (time.time() - start_time) * 1000 - self.stats.add_request(False, latency_ms, str(e)[:100]) - return False - - async def send_stream_request(self) -> bool: - """Send a stream request using Ray Generators (async for)""" - if "stream" not in self.workers or not self.workers["stream"]: - return False - - worker = random.choice(self.workers["stream"]) - start_time = time.time() - - try: - count = random.randint(5, 15) - delay = 0.01 - - # Use async for to stream results from Ray Generator - # This is the correct way to consume Ray Generators in asyncio - chunk_count = 0 - async for ref in worker.generate_stream.remote(count, delay): - # await the ObjectRef to get the actual value - item = await ref - chunk_count += 1 - # Process item if needed (currently just counting) - - latency_ms = (time.time() - start_time) * 1000 - self.stats.add_stream(True, latency_ms) - return True - - except Exception as e: - latency_ms = (time.time() - start_time) * 1000 - self.stats.add_stream(False, latency_ms, str(e)[:100]) - return False - - async def run_stress_test(self, duration: float): - """Run stress test""" - end_time = time.time() + duration - report_interval = 10.0 - - print(f"[StressTest] Starting stress test for {duration}s at {self.rate} req/s") - - async def worker_loop(): - while self.running and time.time() < end_time: - # 70% single, 30% stream - if random.random() < 0.7: - await self.send_single_request() - else: - await self.send_stream_request() - - if self.interval > 0: - await asyncio.sleep(self.interval) - - # Start multiple concurrent workers - num_workers = max(1, int(self.rate / 10)) - tasks = [asyncio.create_task(worker_loop()) for _ in range(num_workers)] - - # Periodic reporting - async def report_loop(): - while self.running and time.time() < end_time: - await asyncio.sleep(report_interval) - summary = self.stats.get_summary() - print("\n[StressTest] Progress Report:") - print( - f" Requests: {summary['requests']['total']} " - f"(success: {summary['requests']['successful']}, " - f"failed: {summary['requests']['failed']})" - ) - print( - f" Streams: {summary['streams']['total']} " - f"(success: {summary['streams']['successful']}, " - f"failed: {summary['streams']['failed']})" - ) - if summary["requests"]["successful"] > 0: - print( - f" Avg Latency: {summary['requests']['avg_latency_ms']:.2f}ms" - ) - - report_task = asyncio.create_task(report_loop()) - - await asyncio.gather(*tasks, report_task) - - self.running = False - print("\n[StressTest] Stress test completed") - - -# ============================================================================ -# Main Function -# ============================================================================ - - -async def main(): - parser = argparse.ArgumentParser( - description="Ray Stress Test Script - Single Process Version" - ) - parser.add_argument( - "--duration", type=float, default=30.0, help="Stress test duration (seconds)" - ) - parser.add_argument("--rate", type=float, default=100.0, help="Requests per second") - parser.add_argument( - "--num-workers", type=int, default=50, help="Number of workers per type" - ) - parser.add_argument( - "--num-cpus", type=int, default=None, help="Number of CPUs for Ray to use" - ) - parser.add_argument("--address", type=str, default=None, help="Ray cluster address") - parser.add_argument( - "--log-dir", type=str, default="benchmark_logs", help="Log directory" - ) - - args = parser.parse_args() - - # Setup logging - log_dir = args.log_dir - os.makedirs(log_dir, exist_ok=True) - - print(f"\n{'=' * 60}") - print("Ray Stress Test (Single Process Mode)") - print(f"Duration: {args.duration}s, Rate: {args.rate} req/s") - print(f"Workers per type: {args.num_workers}") - print(f"{'=' * 60}\n") - - # Initialize Ray - if not ray.is_initialized(): - if args.address: - ray.init(address=args.address) - print(f"Connected to Ray cluster at {args.address}") - else: - num_cpus = args.num_cpus or os.cpu_count() - ray.init(num_cpus=num_cpus, include_dashboard=False) - print(f"Ray initialized with {num_cpus} CPUs") - - print(f"Ray cluster resources: {ray.cluster_resources()}") - - # Create Workers (simulate 10 nodes × 5 types = 50 Workers) - workers = {} - for worker_type, worker_class in WORKER_CLASSES.items(): - workers[worker_type] = [] - for i in range(args.num_workers): - try: - worker = worker_class.options(name=f"{worker_type}_{i}").remote() - workers[worker_type].append(worker) - except Exception as e: - print(f"Failed to create {worker_type}_{i}: {e}") - print(f"Created {len(workers[worker_type])} {worker_type} workers") - - # Wait for all Workers to be ready - print("Waiting for workers to be ready...") - await asyncio.sleep(2.0) - - # Create stress test client - stats = StressTestStats() - client = StressTestClient(workers, stats, rate=args.rate) - - # Run stress test - try: - await client.run_stress_test(args.duration) - except KeyboardInterrupt: - print("\nInterrupted by user") - client.running = False - - # Print final statistics - print(f"\n{'=' * 60}") - print("Final Statistics (Ray Single Process)") - print(f"{'=' * 60}") - summary = stats.get_summary() - print(json.dumps(summary, indent=2)) - - # Save statistics - stats_file = os.path.join(log_dir, "stress_test_stats_ray_single.json") - with open(stats_file, "w") as f: - json.dump(summary, f, indent=2) - print(f"\nStatistics saved to {stats_file}") - - # Shutdown Ray - ray.shutdown() - print("Shutdown complete") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/benchmarks/queue_benchmark.py b/benchmarks/queue_benchmark.py deleted file mode 100644 index f0c6a01ad..000000000 --- a/benchmarks/queue_benchmark.py +++ /dev/null @@ -1,521 +0,0 @@ -#!/usr/bin/env python3 -""" -Distributed In-Memory Queue Benchmark Script - Multi-Process Version - -Uses torchrun to start multiple processes, each process acts as both producer and consumer. -Uses rank/world_size for distributed consumption, testing cross-node queue performance. - -Usage: - torchrun --nproc_per_node=10 benchmarks/queue_benchmark.py \ - --duration 30 \ - --num-buckets 16 - -Arguments: - --duration: Benchmark duration (seconds), default 30 - --num-buckets: Number of queue buckets, default 16 - --batch-size: Write batch size, default 100 - --record-size: Record data size (bytes), default 100 - --rate-limit: Writes per second per process (None=unlimited) -""" - -import argparse -import asyncio -import json -import os -import random -import string -import sys -import time -from collections import defaultdict -from dataclasses import dataclass, field - -import pulsing as pul -from pulsing.core import SystemConfig -from pulsing.streaming import read_queue, write_queue - - -# ============================================================================ -# Benchmark Statistics -# ============================================================================ - - -@dataclass -class QueueBenchmarkStats: - """Queue benchmark statistics""" - - total_writes: int = 0 - total_reads: int = 0 - successful_writes: int = 0 - successful_reads: int = 0 - failed_writes: int = 0 - failed_reads: int = 0 - total_write_latency_ms: float = 0.0 - total_read_latency_ms: float = 0.0 - write_latencies: list[float] = field(default_factory=list) - read_latencies: list[float] = field(default_factory=list) - bytes_written: int = 0 - records_written: int = 0 - records_read: int = 0 - errors: dict[str, int] = field(default_factory=lambda: defaultdict(int)) - - def add_write( - self, - success: bool, - latency_ms: float, - records: int = 1, - bytes_size: int = 0, - error: str | None = None, - ): - self.total_writes += 1 - if success: - self.successful_writes += 1 - self.total_write_latency_ms += latency_ms - self.write_latencies.append(latency_ms) - self.records_written += records - self.bytes_written += bytes_size - else: - self.failed_writes += 1 - if error: - self.errors[error[:50]] += 1 - - def add_read( - self, - success: bool, - latency_ms: float, - records: int = 0, - error: str | None = None, - ): - self.total_reads += 1 - if success: - self.successful_reads += 1 - self.total_read_latency_ms += latency_ms - self.read_latencies.append(latency_ms) - self.records_read += records - else: - self.failed_reads += 1 - if error: - self.errors[error[:50]] += 1 - - def get_summary(self, duration: float) -> dict: - def percentile(data: list[float], p: float) -> float: - if not data: - return 0.0 - sorted_data = sorted(data) - idx = int(len(sorted_data) * p / 100) - return sorted_data[min(idx, len(sorted_data) - 1)] - - write_throughput = self.records_written / duration if duration > 0 else 0 - read_throughput = self.records_read / duration if duration > 0 else 0 - avg_write_latency = ( - self.total_write_latency_ms / self.successful_writes - if self.successful_writes > 0 - else 0.0 - ) - avg_read_latency = ( - self.total_read_latency_ms / self.successful_reads - if self.successful_reads > 0 - else 0.0 - ) - - return { - "duration_s": duration, - "writes": { - "total_ops": self.total_writes, - "successful": self.successful_writes, - "failed": self.failed_writes, - "success_rate": ( - self.successful_writes / self.total_writes * 100 - if self.total_writes > 0 - else 0.0 - ), - "records_written": self.records_written, - "throughput_records_per_s": write_throughput, - "bytes_written": self.bytes_written, - "throughput_mb_per_s": self.bytes_written / duration / 1024 / 1024 - if duration > 0 - else 0, - "avg_latency_ms": avg_write_latency, - "p50_latency_ms": percentile(self.write_latencies, 50), - "p95_latency_ms": percentile(self.write_latencies, 95), - "p99_latency_ms": percentile(self.write_latencies, 99), - }, - "reads": { - "total_ops": self.total_reads, - "successful": self.successful_reads, - "failed": self.failed_reads, - "success_rate": ( - self.successful_reads / self.total_reads * 100 - if self.total_reads > 0 - else 0.0 - ), - "records_read": self.records_read, - "throughput_records_per_s": read_throughput, - "avg_latency_ms": avg_read_latency, - "p50_latency_ms": percentile(self.read_latencies, 50), - "p95_latency_ms": percentile(self.read_latencies, 95), - "p99_latency_ms": percentile(self.read_latencies, 99), - }, - "errors": dict(self.errors), - } - - -# ============================================================================ -# Data Generation -# ============================================================================ - - -def generate_record(record_size: int = 100) -> dict: - """Generate test record""" - return { - "id": f"user_{random.randint(0, 10000)}", - "timestamp": time.time(), - "value": random.randint(0, 1000000), - "data": "".join(random.choices(string.ascii_letters, k=record_size)), - } - - -def estimate_record_size(record: dict) -> int: - """Estimate record size""" - return len(json.dumps(record)) - - -# ============================================================================ -# Producer -# ============================================================================ - - -async def producer_loop( - writer, - stats: QueueBenchmarkStats, - end_time: float, - record_size: int, - rate_limit: float | None, -): - """Producer loop""" - interval = 1.0 / rate_limit if rate_limit else 0 - - while time.time() < end_time: - record = generate_record(record_size) - record_bytes = estimate_record_size(record) - start = time.time() - - try: - await writer.put(record) - latency_ms = (time.time() - start) * 1000 - stats.add_write(True, latency_ms, records=1, bytes_size=record_bytes) - except Exception as e: - latency_ms = (time.time() - start) * 1000 - stats.add_write(False, latency_ms, error=str(e)) - - if interval > 0: - await asyncio.sleep(interval) - - -# ============================================================================ -# Consumer -# ============================================================================ - - -async def consumer_loop( - reader, - stats: QueueBenchmarkStats, - end_time: float, - read_batch_size: int, -): - """Consumer loop""" - while time.time() < end_time: - start = time.time() - - try: - records = await reader.get(limit=read_batch_size, wait=True, timeout=1.0) - latency_ms = (time.time() - start) * 1000 - - if records: - stats.add_read(True, latency_ms, records=len(records)) - except asyncio.TimeoutError: - pass - except Exception as e: - latency_ms = (time.time() - start) * 1000 - stats.add_read(False, latency_ms, error=str(e)) - - -# ============================================================================ -# Main Function -# ============================================================================ - - -async def main(): - parser = argparse.ArgumentParser( - description="Distributed In-Memory Queue Benchmark (Multi-Process)" - ) - parser.add_argument( - "--duration", type=float, default=30.0, help="Benchmark duration (seconds)" - ) - parser.add_argument( - "--num-buckets", type=int, default=16, help="Number of queue buckets" - ) - parser.add_argument("--batch-size", type=int, default=100, help="Write batch size") - parser.add_argument( - "--read-batch-size", type=int, default=100, help="Read batch size" - ) - parser.add_argument( - "--record-size", type=int, default=100, help="Record data size (bytes)" - ) - parser.add_argument( - "--rate-limit", type=float, default=None, help="Writes per second per process" - ) - parser.add_argument("--port", type=int, default=0, help="Base port (0=auto)") - parser.add_argument( - "--seed-nodes", type=str, nargs="+", default=[], help="Seed nodes" - ) - parser.add_argument( - "--storage-path", - type=str, - default="./queue_benchmark_data", - help="Storage path", - ) - parser.add_argument( - "--log-dir", type=str, default="benchmark_logs", help="Log directory" - ) - parser.add_argument( - "--stabilize-timeout", - type=float, - default=5.0, - help="Cluster stabilization wait time", - ) - - args = parser.parse_args() - - # Get torchrun information from environment variables - local_rank = int(os.environ.get("LOCAL_RANK", 0)) - world_size = int(os.environ.get("WORLD_SIZE", 1)) - rank = int(os.environ.get("RANK", local_rank)) - - # Create log directory - log_dir = args.log_dir - os.makedirs(log_dir, exist_ok=True) - os.makedirs(args.storage_path, exist_ok=True) - - # Log file - log_file = os.path.join(log_dir, f"queue_benchmark_rank_{rank}.log") - - class TeeOutput: - def __init__(self, file_path, original): - self.file = open(file_path, "w", encoding="utf-8") - self.original = original - - def write(self, text): - try: - self.file.write(text) - self.file.flush() - except Exception: - pass - try: - self.original.write(text) - self.original.flush() - except Exception: - pass - - def flush(self): - try: - self.file.flush() - except Exception: - pass - try: - self.original.flush() - except Exception: - pass - - def close(self): - try: - self.file.close() - except Exception: - pass - - original_stdout = sys.stdout - original_stderr = sys.stderr - tee = TeeOutput(log_file, original_stdout) - sys.stdout = tee - sys.stderr = tee - - print(f"\n{'=' * 60}") - print(f"Queue Benchmark - Process {rank}/{world_size}") - print(f"{'=' * 60}") - print(f"Duration: {args.duration}s") - print(f"Buckets: {args.num_buckets}, Batch size: {args.batch_size}") - print(f"Record size: {args.record_size} bytes") - print(f"Log file: {log_file}") - print(f"{'=' * 60}\n") - - # Configure system - if args.port == 0: - base_port = 9000 - port = base_port + rank - else: - port = args.port + rank - - addr = f"0.0.0.0:{port}" - - # Add seed nodes - seeds = None - if args.seed_nodes: - seeds = args.seed_nodes - elif rank > 0: - prev_port = 9000 + (rank - 1) - seeds = [f"127.0.0.1:{prev_port}"] - - # Create system - system = await pul.actor_system(addr=addr, seeds=seeds) - print(f"[Process {rank}] ActorSystem started at {system.addr}") - - # Wait for cluster to stabilize - print( - f"[Process {rank}] Waiting for cluster to stabilize ({args.stabilize_timeout}s)..." - ) - await asyncio.sleep(args.stabilize_timeout) - - # Get cluster members - members = await system.members() - print(f"[Process {rank}] Cluster members: {len(members)}") - for member in members: - print( - f" - Node {member['node_id']}: {member['addr']} [{member.get('status', 'unknown')}]" - ) - - topic = "benchmark_queue" - stats = QueueBenchmarkStats() - - # Create writer (each process can write) - writer = await write_queue( - system, - topic=topic, - bucket_column="id", - num_buckets=args.num_buckets, - batch_size=args.batch_size, - storage_path=args.storage_path, - ) - print(f"[Process {rank}] Writer created") - - # Create reader (use rank/world_size for distributed consumption) - reader = await read_queue( - system, - topic=topic, - rank=rank, - world_size=world_size, - num_buckets=args.num_buckets, - storage_path=args.storage_path, - ) - assigned_buckets = [i for i in range(args.num_buckets) if i % world_size == rank] - print(f"[Process {rank}] Reader created, assigned buckets: {assigned_buckets}") - - # Wait for all processes to be ready - await asyncio.sleep(2.0) - - # Start producer and consumer - print(f"\n[Process {rank}] Starting benchmark...") - start_time = time.time() - end_time = start_time + args.duration - - producer_task = asyncio.create_task( - producer_loop(writer, stats, end_time, args.record_size, args.rate_limit) - ) - consumer_task = asyncio.create_task( - consumer_loop(reader, stats, end_time, args.read_batch_size) - ) - - # Progress reporting - report_interval = 10.0 - - async def report_progress(): - while time.time() < end_time: - await asyncio.sleep(report_interval) - elapsed = time.time() - start_time - summary = stats.get_summary(elapsed) - print(f"\n[Process {rank}] Progress ({elapsed:.0f}s):") - print( - f" Writes: {summary['writes']['records_written']} records " - f"({summary['writes']['throughput_records_per_s']:.0f}/s)" - ) - print( - f" Reads: {summary['reads']['records_read']} records " - f"({summary['reads']['throughput_records_per_s']:.0f}/s)" - ) - print( - f" Write latency: avg={summary['writes']['avg_latency_ms']:.2f}ms, " - f"p99={summary['writes']['p99_latency_ms']:.2f}ms" - ) - - report_task = asyncio.create_task(report_progress()) - - # Wait for completion - try: - await asyncio.gather(producer_task, consumer_task) - except KeyboardInterrupt: - print(f"\n[Process {rank}] Interrupted by user") - - report_task.cancel() - try: - await report_task - except asyncio.CancelledError: - pass - - # Final flush - try: - await writer.flush() - except Exception: - pass - - # Final statistics - actual_duration = time.time() - start_time - summary = stats.get_summary(actual_duration) - - print(f"\n{'=' * 60}") - print(f"Final Statistics - Process {rank}") - print(f"{'=' * 60}") - print(json.dumps(summary, indent=2)) - - # Save results - result_file = os.path.join(log_dir, f"queue_benchmark_rank_{rank}.json") - with open(result_file, "w") as f: - json.dump( - { - "rank": rank, - "world_size": world_size, - "config": { - "duration": args.duration, - "num_buckets": args.num_buckets, - "batch_size": args.batch_size, - "record_size": args.record_size, - "rate_limit": args.rate_limit, - "assigned_buckets": assigned_buckets, - }, - "results": summary, - }, - f, - indent=2, - ) - print(f"\n[Process {rank}] Results saved to {result_file}") - - # Cleanup - await system.shutdown() - print(f"[Process {rank}] Benchmark complete") - - # Restore stdout/stderr - if hasattr(sys.stdout, "close"): - try: - sys.stdout.close() - except Exception: - pass - sys.stdout = original_stdout - sys.stderr = original_stderr - - -if __name__ == "__main__": - try: - asyncio.run(main()) - except Exception as e: - import traceback - - print(f"\n[FATAL ERROR] Process failed: {e}") - print(traceback.format_exc()) - sys.exit(1) diff --git a/benchmarks/run_baseline_throughput.sh b/benchmarks/run_baseline_throughput.sh deleted file mode 100644 index c07be5d41..000000000 --- a/benchmarks/run_baseline_throughput.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -# -# 运行 Queue & Topic 基线吞吐 Benchmark(单节点) -# -# Usage: -# ./benchmarks/run_baseline_throughput.sh -# DURATION=15 ./benchmarks/run_baseline_throughput.sh -# python benchmarks/baseline_throughput.py --topic-only --topic-subscribers 3 -# - -set -e - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" - -cd "$PROJECT_ROOT" - -DURATION=${DURATION:-10} -OUTPUT=${OUTPUT:-} - -echo "==========================================" -echo "Baseline Throughput (Queue + Topic)" -echo "==========================================" -echo "Duration: ${DURATION}s per benchmark" -echo "==========================================" - -if [ -n "$OUTPUT" ]; then - python benchmarks/baseline_throughput.py --duration "$DURATION" --output "$OUTPUT" -else - python benchmarks/baseline_throughput.py --duration "$DURATION" -fi diff --git a/benchmarks/run_concurrency_sweep.sh b/benchmarks/run_concurrency_sweep.sh deleted file mode 100644 index e909750e9..000000000 --- a/benchmarks/run_concurrency_sweep.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash -# -# 多并发扫描:不同 生产者/消费者 组合下的吞吐 -# -# Usage: -# ./benchmarks/run_concurrency_sweep.sh -# DURATION=5 ./benchmarks/run_concurrency_sweep.sh -# python benchmarks/concurrency_sweep.py --producers 1 2 4 --consumers 1 2 4 --output sweep.json -# - -set -e - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" - -cd "$PROJECT_ROOT" - -DURATION=${DURATION:-8} -OUTPUT=${OUTPUT:-} - -echo "==========================================" -echo "Concurrency Sweep (P producers, C consumers)" -echo "==========================================" -echo "Duration per (P,C): ${DURATION}s" -echo "Producers/Consumers: 1,2,4,8 (default)" -echo "==========================================" - -if [ -n "$OUTPUT" ]; then - python benchmarks/concurrency_sweep.py --duration "$DURATION" --output "$OUTPUT" -else - python benchmarks/concurrency_sweep.py --duration "$DURATION" -fi diff --git a/benchmarks/run_queue_benchmark.sh b/benchmarks/run_queue_benchmark.sh deleted file mode 100755 index 84ea00de0..000000000 --- a/benchmarks/run_queue_benchmark.sh +++ /dev/null @@ -1,105 +0,0 @@ -#!/bin/bash -# -# 分布式内存队列压测脚本 -# -# 使用 torchrun 启动 10 个进程,每个进程同时作为生产者和消费者 -# - -set -e - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" - -cd "$PROJECT_ROOT" - -# 默认参数 -NPROC=${NPROC:-10} -DURATION=${DURATION:-30} -NUM_BUCKETS=${NUM_BUCKETS:-16} -BATCH_SIZE=${BATCH_SIZE:-100} -RECORD_SIZE=${RECORD_SIZE:-100} - -echo "==========================================" -echo "Distributed Queue Benchmark" -echo "==========================================" -echo "Processes: ${NPROC}" -echo "Duration: ${DURATION}s" -echo "Buckets: ${NUM_BUCKETS}" -echo "Batch size: ${BATCH_SIZE}" -echo "Record size: ${RECORD_SIZE} bytes" -echo "==========================================" -echo "" - -# 清理旧数据 -rm -rf ./queue_benchmark_data -rm -rf ./benchmark_logs/queue_benchmark_*.log -rm -rf ./benchmark_logs/queue_benchmark_*.json - -# 运行压测 -torchrun --nproc_per_node="$NPROC" benchmarks/queue_benchmark.py \ - --duration "$DURATION" \ - --num-buckets "$NUM_BUCKETS" \ - --batch-size "$BATCH_SIZE" \ - --record-size "$RECORD_SIZE" \ - --log-dir benchmark_logs - -echo "" -echo "==========================================" -echo "Aggregating results..." -echo "==========================================" - -# 汇总结果 -python3 -c " -import json -import os -import glob - -log_dir = 'benchmark_logs' -result_files = glob.glob(os.path.join(log_dir, 'queue_benchmark_rank_*.json')) - -if not result_files: - print('No result files found') - exit(1) - -total_writes = 0 -total_reads = 0 -total_write_latency = 0 -total_read_latency = 0 -successful_writes = 0 -successful_reads = 0 -duration = 0 - -for f in result_files: - with open(f) as fp: - data = json.load(fp) - r = data['results'] - total_writes += r['writes']['records_written'] - total_reads += r['reads']['records_read'] - total_write_latency += r['writes']['avg_latency_ms'] * r['writes']['successful'] - total_read_latency += r['reads']['avg_latency_ms'] * r['reads']['successful'] - successful_writes += r['writes']['successful'] - successful_reads += r['reads']['successful'] - duration = max(duration, r['duration_s']) - -avg_write_latency = total_write_latency / successful_writes if successful_writes > 0 else 0 -avg_read_latency = total_read_latency / successful_reads if successful_reads > 0 else 0 - -print(f'Total processes: {len(result_files)}') -print(f'Duration: {duration:.1f}s') -print() -print('=== Writes ===') -print(f' Total records: {total_writes}') -print(f' Throughput: {total_writes / duration:.0f} records/s') -print(f' Avg latency: {avg_write_latency:.2f}ms') -print() -print('=== Reads ===') -print(f' Total records: {total_reads}') -print(f' Throughput: {total_reads / duration:.0f} records/s') -print(f' Avg latency: {avg_read_latency:.2f}ms') -" - -# 清理数据 -rm -rf ./queue_benchmark_data - -echo "" -echo "Benchmark finished! Results in benchmark_logs/" diff --git a/benchmarks/run_stress_multiprocessing.sh b/benchmarks/run_stress_multiprocessing.sh deleted file mode 100644 index 638b3c746..000000000 --- a/benchmarks/run_stress_multiprocessing.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash -# -# 多进程压测(multiprocessing,不依赖 torchrun) -# -# Usage: -# ./benchmarks/run_stress_multiprocessing.sh -# NPROCS=8 DURATION=30 ./benchmarks/run_stress_multiprocessing.sh -# - -set -e - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" - -cd "$PROJECT_ROOT" - -NPROCS=${NPROCS:-4} -DURATION=${DURATION:-20} -OUTPUT=${OUTPUT:-} - -echo "==========================================" -echo "Multiprocessing Stress (Queue + Topic)" -echo "==========================================" -echo "Processes: $NPROCS" -echo "Duration: ${DURATION}s" -echo "==========================================" - -if [ -n "$OUTPUT" ]; then - python benchmarks/stress_multiprocessing.py --nprocs "$NPROCS" --duration "$DURATION" --output "$OUTPUT" -else - python benchmarks/stress_multiprocessing.py --nprocs "$NPROCS" --duration "$DURATION" -fi diff --git a/benchmarks/run_stress_test.sh b/benchmarks/run_stress_test.sh deleted file mode 100755 index a415c77c3..000000000 --- a/benchmarks/run_stress_test.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/bin/bash -# 大规模压测启动脚本 - -set -e - -# 默认参数 -DURATION=${DURATION:-30} -RATE=${RATE:-100} -SEED_NODES=${SEED_NODES:-""} - -# 解析参数 -ARGS="" -if [ -n "$SEED_NODES" ]; then - ARGS="--seed-nodes $SEED_NODES" -fi - -echo "==========================================" -echo "Large Scale Stress Test" -echo "==========================================" -echo "Duration: ${DURATION}s" -echo "Rate: ${RATE} req/s" -echo "Processes: 10" -echo "Workers: 5 types (echo, compute, stream, batch, stateful)" -echo "==========================================" -echo "" - -# 使用torchrun启动10个进程 -# 注意:大规模压测时,增加稳定等待时间以避免节点被误判为失败 -# 如果端口被占用,可以设置 MASTER_PORT 环境变量使用不同端口 -MASTER_PORT=${MASTER_PORT:-29500} - -# 检查端口是否被占用 -if command -v lsof >/dev/null 2>&1; then - if lsof -Pi :$MASTER_PORT -sTCP:LISTEN -t >/dev/null 2>&1; then - echo "⚠️ Warning: Port $MASTER_PORT is already in use!" - echo " You can set MASTER_PORT environment variable to use a different port:" - echo " MASTER_PORT=29501 ./benchmarks/run_stress_test.sh" - echo "" - echo " Or kill the process using the port:" - echo " lsof -ti :$MASTER_PORT | xargs kill -9" - echo "" - read -p "Continue anyway? (y/N): " -n 1 -r - echo - if [[ ! $REPLY =~ ^[Yy]$ ]]; then - exit 1 - fi - fi -fi - -torchrun \ - --nproc_per_node=10 \ - --nnodes=1 \ - --node_rank=0 \ - --master_addr=127.0.0.1 \ - --master_port=$MASTER_PORT \ - benchmarks/large_scale_stress_test.py \ - --duration $DURATION \ - --rate $RATE \ - --stabilize-timeout 5 \ - $ARGS - -echo "" -echo "==========================================" -echo "Stress test completed!" -echo "==========================================" -echo "Logs: benchmark_logs/stress_test_rank_*.log" -echo "Stats: benchmark_logs/stress_test_stats_rank_*.json" -echo "" -echo "View logs:" -echo " ./benchmarks/view_logs.sh all - Show all logs" -echo " ./benchmarks/view_logs.sh errors - Show errors" -echo " ./benchmarks/view_logs.sh summary - Show summary" -echo " ./benchmarks/view_logs.sh 0 - Show rank 0 log" -echo "==========================================" diff --git a/benchmarks/run_stress_test_pulsing_single.sh b/benchmarks/run_stress_test_pulsing_single.sh deleted file mode 100755 index 88401086b..000000000 --- a/benchmarks/run_stress_test_pulsing_single.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -# Pulsing 压测启动脚本 - 单进程版本(与 Ray 单进程版本等价对比) - -set -e - -DURATION=${DURATION:-30} -RATE=${RATE:-100} -NUM_WORKERS=${NUM_WORKERS:-50} - -echo "==========================================" -echo "Pulsing Stress Test (Single Process Mode)" -echo "==========================================" -echo "Duration: ${DURATION}s" -echo "Rate: ${RATE} req/s" -echo "Workers per type: ${NUM_WORKERS}" -echo "Total Workers: $((NUM_WORKERS * 5))" -echo "==========================================" -echo "" - -python benchmarks/large_scale_stress_test_pulsing_single.py \ - --duration $DURATION \ - --rate $RATE \ - --num-workers $NUM_WORKERS - -echo "" -echo "==========================================" -echo "Stress test completed!" -echo "==========================================" -echo "Log: benchmark_logs/stress_test_pulsing_single.log" -echo "Stats: benchmark_logs/stress_test_stats_pulsing_single.json" -echo "==========================================" diff --git a/benchmarks/run_stress_test_ray.sh b/benchmarks/run_stress_test_ray.sh deleted file mode 100755 index 1499eb335..000000000 --- a/benchmarks/run_stress_test_ray.sh +++ /dev/null @@ -1,65 +0,0 @@ -#!/bin/bash -# 大规模压测启动脚本 - Ray版本 - -set -e - -# 默认参数 -DURATION=${DURATION:-30} -RATE=${RATE:-100} -MASTER_PORT=${MASTER_PORT:-29500} - -# 解析参数 -ARGS="" -if [ -n "$RAY_ADDRESS" ]; then - ARGS="--address $RAY_ADDRESS" -fi - -echo "==========================================" -echo "Large Scale Stress Test (Ray Version)" -echo "==========================================" -echo "Duration: ${DURATION}s" -echo "Rate: ${RATE} req/s" -echo "Processes: 10" -echo "Workers: 5 types (echo, compute, stream, batch, stateful)" -echo "Master Port: ${MASTER_PORT}" -echo "==========================================" -echo "" - -# 检查端口是否被占用 -if command -v lsof >/dev/null 2>&1; then - if lsof -Pi :$MASTER_PORT -sTCP:LISTEN -t >/dev/null 2>&1; then - echo "⚠️ Warning: Port $MASTER_PORT is already in use!" - echo " You can set MASTER_PORT environment variable to use a different port:" - echo " MASTER_PORT=29501 ./benchmarks/run_stress_test_ray.sh" - echo "" - echo " Or kill the process using the port:" - echo " lsof -ti :$MASTER_PORT | xargs kill -9" - echo "" - read -p "Continue anyway? (y/N): " -n 1 -r - echo - if [[ ! $REPLY =~ ^[Yy]$ ]]; then - exit 1 - fi - fi -fi - -# 使用torchrun启动10个进程 -torchrun \ - --nproc_per_node=10 \ - --nnodes=1 \ - --node_rank=0 \ - --master_addr=127.0.0.1 \ - --master_port=$MASTER_PORT \ - benchmarks/large_scale_stress_test_ray.py \ - --duration $DURATION \ - --rate $RATE \ - --stabilize-timeout 5 \ - $ARGS - -echo "" -echo "==========================================" -echo "Stress test completed!" -echo "==========================================" -echo "Logs: benchmark_logs/stress_test_ray_rank_*.log" -echo "Stats: benchmark_logs/stress_test_stats_ray_rank_*.json" -echo "==========================================" diff --git a/benchmarks/run_stress_test_ray_single.sh b/benchmarks/run_stress_test_ray_single.sh deleted file mode 100755 index 5ec128a05..000000000 --- a/benchmarks/run_stress_test_ray_single.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -# Ray 压测启动脚本 - 单进程版本(正确的 Ray 使用方式) -# -# Ray 设计为单 driver 进程 + 多 Actor,不应使用 torchrun 多进程模式。 - -set -e - -DURATION=${DURATION:-30} -RATE=${RATE:-100} -NUM_WORKERS=${NUM_WORKERS:-50} - -echo "==========================================" -echo "Ray Stress Test (Single Process Mode)" -echo "==========================================" -echo "Duration: ${DURATION}s" -echo "Rate: ${RATE} req/s" -echo "Workers per type: ${NUM_WORKERS}" -echo "Total Workers: $((NUM_WORKERS * 5))" -echo "==========================================" -echo "" - -python benchmarks/large_scale_stress_test_ray_single.py \ - --duration $DURATION \ - --rate $RATE \ - --num-workers $NUM_WORKERS - -echo "" -echo "==========================================" -echo "Stress test completed!" -echo "==========================================" -echo "Log: benchmark_logs/stress_test_ray_single.log" -echo "Stats: benchmark_logs/stress_test_stats_ray_single.json" -echo "==========================================" diff --git a/benchmarks/stress_multiprocessing.py b/benchmarks/stress_multiprocessing.py deleted file mode 100644 index ead4ea849..000000000 --- a/benchmarks/stress_multiprocessing.py +++ /dev/null @@ -1,318 +0,0 @@ -#!/usr/bin/env python3 -""" -多进程压测:用 multiprocessing 启动 N 个进程,每进程一个 ActorSystem 节点,组成集群, -对 Queue 与 Topic 做多进程压力测试(不依赖 torchrun)。 - -Usage: - python benchmarks/stress_multiprocessing.py --nprocs 4 --duration 20 - python benchmarks/stress_multiprocessing.py --nprocs 8 --queue-only --num-buckets 16 -""" - -from __future__ import annotations - -import argparse -import asyncio -import json -import multiprocessing as mp -import os -import shutil -import tempfile -import time -from multiprocessing import Queue - -import pulsing as pul -from pulsing.streaming import ( - read_queue, - write_queue, - PublishMode, - read_topic, - write_topic, -) - - -# ============================================================================= -# 单进程内异步压测逻辑(Queue + Topic) -# ============================================================================= - - -async def _run_worker( - rank: int, - world_size: int, - seed_queue: Queue, - result_queue: Queue, - config: dict, -) -> None: - """单进程 worker:加入集群后跑 Queue 与 Topic 压测,结果放入 result_queue.""" - base_port = config.get("base_port", 9100) - duration = config["duration"] - num_buckets = config["num_buckets"] - record_size = config["record_size"] - storage_path = config["storage_path"] - run_queue_bench = config.get("queue", True) - run_topic_bench = config.get("topic", True) - stabilize = config.get("stabilize_timeout", 4.0) - - # rank 0 先起节点并 bind,再往 queue 里放 seed,供其余 (world_size-1) 个进程各 get 一次 - system = None - if rank == 0: - addr = f"127.0.0.1:{base_port}" - system = await pul.actor_system(addr=addr) - for _ in range(world_size - 1): - seed_queue.put(addr) - else: - seed_addr = seed_queue.get(timeout=60.0) - await asyncio.sleep(0.5) - system = await pul.actor_system( - addr=f"127.0.0.1:{base_port + rank}", - seeds=[seed_addr], - ) - - await asyncio.sleep(stabilize) - - result = {"rank": rank, "world_size": world_size, "queue": None, "topic": None} - - if run_queue_bench: - topic_q = f"mp_queue_{world_size}" - writer = await write_queue( - system, - topic=topic_q, - bucket_column="id", - num_buckets=num_buckets, - storage_path=storage_path, - ) - reader = await read_queue( - system, - topic=topic_q, - rank=rank, - world_size=world_size, - num_buckets=num_buckets, - storage_path=storage_path, - ) - written = 0 - read_count = 0 - end_time = time.monotonic() + duration - while time.monotonic() < end_time: - try: - await writer.put( - {"id": f"r{rank}_{written}", "payload": "x" * record_size} - ) - written += 1 - except Exception: - pass - try: - await writer.flush() - except Exception: - pass - while time.monotonic() < end_time + 2: - try: - batch = await reader.get(limit=100, wait=True, timeout=0.5) - if batch: - read_count += len(batch) - else: - break - except asyncio.TimeoutError: - break - except Exception: - break - result["queue"] = { - "records_written": written, - "records_read": read_count, - "write_rec_s": written / duration if duration > 0 else 0, - "read_rec_s": read_count / duration if duration > 0 else 0, - } - - if run_topic_bench: - topic_t = f"mp_topic_{world_size}" - recv_count = [0] - reader = await read_topic(system, topic_t, reader_id=f"mp_{rank}") - - def on_msg(_): - recv_count[0] += 1 - - reader.add_callback(on_msg) - await reader.start() - writer = await write_topic(system, topic_t, writer_id=f"mp_{rank}") - published = 0 - end_time = time.monotonic() + duration - while time.monotonic() < end_time: - try: - await writer.publish( - {"seq": published, "payload": "x" * record_size}, - mode=PublishMode.FIRE_AND_FORGET, - ) - published += 1 - except Exception: - pass - await asyncio.sleep(0.5) - await reader.stop() - result["topic"] = { - "messages_published": published, - "messages_delivered": recv_count[0], - "publish_msg_s": published / duration if duration > 0 else 0, - "delivered_msg_s": recv_count[0] / duration if duration > 0 else 0, - } - - await system.shutdown() - result_queue.put(result) - - -def _worker_entry( - rank: int, - world_size: int, - seed_queue: Queue, - result_queue: Queue, - config: dict, -) -> None: - asyncio.run(_run_worker(rank, world_size, seed_queue, result_queue, config)) - - -# ============================================================================= -# Main:spawn 多进程并汇总 -# ============================================================================= - - -def main(): - parser = argparse.ArgumentParser( - description="多进程 Queue & Topic 压测(multiprocessing)" - ) - parser.add_argument("--nprocs", type=int, default=4, help="进程数(集群节点数)") - parser.add_argument("--duration", type=float, default=20.0, help="压测时长(秒)") - parser.add_argument("--num-buckets", type=int, default=8, help="Queue 桶数") - parser.add_argument( - "--record-size", type=int, default=100, help="单条 payload 字节数" - ) - parser.add_argument( - "--base-port", type=int, default=9100, help="首节点端口,其余 base_port+rank" - ) - parser.add_argument( - "--stabilize-timeout", type=float, default=4.0, help="集群稳定等待时间" - ) - parser.add_argument("--queue-only", action="store_true", help="仅压 Queue") - parser.add_argument("--topic-only", action="store_true", help="仅压 Topic") - parser.add_argument("--output", type=str, default=None, help="汇总结果 JSON 路径") - args = parser.parse_args() - - nprocs = args.nprocs - run_queue = not args.topic_only - run_topic = not args.queue_only - - storage_path = os.path.abspath(tempfile.mkdtemp(prefix="stress_mp_")) - config = { - "duration": args.duration, - "num_buckets": args.num_buckets, - "record_size": args.record_size, - "storage_path": storage_path, - "base_port": args.base_port, - "stabilize_timeout": args.stabilize_timeout, - "queue": run_queue, - "topic": run_topic, - } - - seed_queue = mp.Queue() - result_queue = mp.Queue() - - procs = [] - for rank in range(nprocs): - p = mp.Process( - target=_worker_entry, - args=(rank, nprocs, seed_queue, result_queue, config), - ) - procs.append(p) - - print("Starting %d processes (cluster size=%d)..." % (nprocs, nprocs)) - for p in procs: - p.start() - for p in procs: - p.join(timeout=args.duration + 60) - if p.is_alive(): - p.terminate() - p.join(timeout=5) - - shutil.rmtree(storage_path, ignore_errors=True) - - results = [] - while not result_queue.empty(): - try: - results.append(result_queue.get_nowait()) - except Exception: - break - - if len(results) != nprocs: - print("WARNING: got %d results, expected %d" % (len(results), nprocs)) - - # 汇总 - print() - print("=" * 60) - print("Multiprocessing Stress Summary (cluster size=%d)" % nprocs) - print("=" * 60) - - agg = {"queue": None, "topic": None} - if run_queue and results: - total_write = sum( - r["queue"]["records_written"] for r in results if r.get("queue") - ) - total_read = sum(r["queue"]["records_read"] for r in results if r.get("queue")) - dur = args.duration - agg["queue"] = { - "total_records_written": total_write, - "total_records_read": total_read, - "write_throughput_rec_s": total_write / dur if dur > 0 else 0, - "read_throughput_rec_s": total_read / dur if dur > 0 else 0, - } - print("\n--- Queue ---") - print( - " Total written: %d (%.0f rec/s)" - % (total_write, agg["queue"]["write_throughput_rec_s"]) - ) - print( - " Total read: %d (%.0f rec/s)" - % (total_read, agg["queue"]["read_throughput_rec_s"]) - ) - - if run_topic and results: - total_pub = sum( - r["topic"]["messages_published"] for r in results if r.get("topic") - ) - total_del = sum( - r["topic"]["messages_delivered"] for r in results if r.get("topic") - ) - dur = args.duration - agg["topic"] = { - "total_published": total_pub, - "total_delivered": total_del, - "publish_throughput_msg_s": total_pub / dur if dur > 0 else 0, - "delivered_throughput_msg_s": total_del / dur if dur > 0 else 0, - } - print("\n--- Topic ---") - print( - " Total published: %d (%.0f msg/s)" - % (total_pub, agg["topic"]["publish_throughput_msg_s"]) - ) - print( - " Total delivered: %d (%.0f msg/s)" - % (total_del, agg["topic"]["delivered_throughput_msg_s"]) - ) - - print("\n" + "=" * 60) - - if args.output: - with open(args.output, "w") as f: - json.dump( - { - "nprocs": nprocs, - "config": { - "duration": args.duration, - "num_buckets": args.num_buckets, - "record_size": args.record_size, - }, - "aggregate": agg, - "per_rank": results, - }, - f, - indent=2, - ) - print("Results written to %s" % args.output) - - -if __name__ == "__main__": - main() diff --git a/crates/pulsing-actor/Cargo.toml b/crates/pulsing-actor/Cargo.toml index d54097160..ee6933ed1 100644 --- a/crates/pulsing-actor/Cargo.toml +++ b/crates/pulsing-actor/Cargo.toml @@ -105,9 +105,5 @@ name = "http2_pool_expand" path = "../../examples/rust/http2_pool_expand.rs" -[[bench]] -name = "tracing_overhead" -harness = false - [lints] workspace = true diff --git a/crates/pulsing-actor/benches/tracing_overhead.rs b/crates/pulsing-actor/benches/tracing_overhead.rs deleted file mode 100644 index 26f0cb460..000000000 --- a/crates/pulsing-actor/benches/tracing_overhead.rs +++ /dev/null @@ -1,333 +0,0 @@ -//! Benchmark: memtable write overhead for each tracing store. -//! -//! Measures the **per-operation cost** of writing to the four memtable-backed -//! stores, so we know how much overhead tracing adds to actor messaging. -//! -//! Run: `cargo bench -p pulsing-actor --bench tracing_overhead` - -use std::hint::black_box; -use std::time::Instant; - -use probing_memtable::discover::ExposedHashTable; -use probing_memtable::discover::ExposedTable; -use probing_memtable::{DType, Schema, Value}; - -// ── Helpers ─────────────────────────────────────────────────────────── - -fn bench_loop(name: &str, iterations: u64, mut f: impl FnMut(u64)) { - // Warmup - for i in 0..iterations.min(1000) { - f(i); - } - - let start = Instant::now(); - for i in 0..iterations { - f(i); - } - let elapsed = start.elapsed(); - - let per_op = elapsed / iterations as u32; - let ops_sec = if elapsed.as_secs_f64() > 0.0 { - iterations as f64 / elapsed.as_secs_f64() - } else { - f64::INFINITY - }; - - println!(" {name:<40} {elapsed:>10.3?} {per_op:>8.0?}/op {ops_sec:>12.0} ops/s",); -} - -// ── Span store (MEMT ring buffer, wide row) ────────────────────────── - -fn bench_span_write() { - let mut schema = Schema::new() - .col("trace_id", DType::Str) - .col("span_id", DType::Str) - .col("parent_span_id", DType::Str) - .col("name", DType::Str) - .col("kind", DType::Str) - .col("start_us", DType::I64) - .col("end_us", DType::I64) - .col("duration_us", DType::I64) - .col("status_code", DType::Str) - .col("instrumentation_scope", DType::Str); - for name in &[ - "attr_actor_name", - "attr_message_type", - "attr_target_addr", - "attr_target_path", - "attr_pulsing_op", - "attr_http_method", - "attr_http_route", - "attr_http_url", - "attr_http_peer", - ] { - schema = schema.col(name, DType::Str); - } - schema = schema - .col("events_json", DType::Str) - .col("links_json", DType::Str); - - let mut table = ExposedTable::create("__bench_spans", &schema, 65536, 16).unwrap(); - - let n = 100_000u64; - bench_loop("span_write (MEMT, 21-col row)", n, |i| { - let tid = format!("trace-{i:08x}"); - let sid = format!("span-{i:08x}"); - let row: Vec = vec![ - Value::Str(&tid), - Value::Str(&sid), - Value::Str(""), - Value::Str("actor.ask"), - Value::Str("INTERNAL"), - Value::I64(1_700_000_000_000_000 + i as i64), - Value::I64(1_700_000_000_001_000 + i as i64), - Value::I64(1000), - Value::Str("OK"), - Value::Str("pulsing"), - Value::Str("actors/counter_0"), - Value::Str("ask"), - Value::Str(""), - Value::Str(""), - Value::Str("ask"), - Value::Str(""), - Value::Str(""), - Value::Str(""), - Value::Str(""), - Value::Str("[]"), - Value::Str("[]"), - ]; - let mut w = table.writer(); - w.push_row(black_box(&row)); - }); -} - -// ── Actor store (MEMH hash table) ──────────────────────────────────── - -fn bench_actor_upsert() { - let mut table = ExposedHashTable::create("__bench_actors", 256, 65536, 0).unwrap(); - - let names: Vec = (0..256).map(|i| format!("actors/worker_{i}")).collect(); - let n = 100_000u64; - - bench_loop("actor_upsert (MEMH, 256 actors)", n, |i| { - let key = &names[(i % 256) as usize]; - let val = format!("{i}|1|Worker|mymod"); - let mut w = table.writer(); - let _ = w.insert(black_box(key), black_box(&Value::Str(&val))); - }); -} - -fn bench_actor_remove() { - let mut table = ExposedHashTable::create("__bench_actors_rm", 256, 65536, 0).unwrap(); - - let names: Vec = (0..256).map(|i| format!("actors/worker_{i}")).collect(); - - // Pre-populate - { - let mut w = table.writer(); - for name in &names { - let _ = w.insert(name, &Value::Str("0|1|Worker|mymod")); - } - } - - let n = 100_000u64; - bench_loop("actor_remove (MEMH, 256 actors)", n, |i| { - let key = &names[(i % 256) as usize]; - let mut w = table.writer(); - w.remove(black_box(key)); - // Re-insert so next remove has something to do - let _ = w.insert(key, &Value::Str("0|1|Worker|mymod")); - }); -} - -// ── Metrics store (MEMT ring buffer) ───────────────────────────────── - -fn bench_metrics_write() { - let schema = Schema::new() - .col("timestamp_us", DType::I64) - .col("node_id", DType::Str) - .col("actors_count", DType::I64) - .col("messages_total", DType::I64) - .col("actors_created", DType::I64) - .col("actors_stopped", DType::I64) - .col("uptime_secs", DType::I64); - - let mut table = ExposedTable::create("__bench_metrics", &schema, 65536, 16).unwrap(); - - let n = 100_000u64; - bench_loop("metrics_write (MEMT, 7-col row)", n, |i| { - let row: Vec = vec![ - Value::I64(1_700_000_000_000_000 + i as i64), - Value::Str("node-1"), - Value::I64(42), - Value::I64(i as i64), - Value::I64(100), - Value::I64(5), - Value::I64(3600), - ]; - let mut w = table.writer(); - w.push_row(black_box(&row)); - }); -} - -// ── Members store (MEMH hash table) ────────────────────────────────── - -fn bench_member_upsert() { - let mut table = ExposedHashTable::create("__bench_members", 64, 16384, 0).unwrap(); - - let keys: Vec = (0..32).map(|i| format!("{i}")).collect(); - let n = 100_000u64; - - bench_loop("member_upsert (MEMH, 32 nodes)", n, |i| { - let key = &keys[(i % 32) as usize]; - let val = format!("10.0.0.{}:9000|online|{}", i % 32, i); - let mut w = table.writer(); - let _ = w.insert(black_box(key), black_box(&Value::Str(&val))); - }); -} - -// ── Span write with u64 IDs (no format!) ───────────────────────────── - -fn bench_span_write_u64_ids() { - let mut schema = Schema::new() - .col("trace_id_hi", DType::U64) - .col("trace_id_lo", DType::U64) - .col("span_id", DType::U64) - .col("parent_span_id", DType::U64) - .col("name", DType::Str) - .col("kind", DType::Str) - .col("start_us", DType::I64) - .col("end_us", DType::I64) - .col("duration_us", DType::I64) - .col("status_code", DType::Str) - .col("instrumentation_scope", DType::Str); - for name in &[ - "attr_actor_name", - "attr_message_type", - "attr_target_addr", - "attr_target_path", - "attr_pulsing_op", - "attr_http_method", - "attr_http_route", - "attr_http_url", - "attr_http_peer", - ] { - schema = schema.col(name, DType::Str); - } - schema = schema - .col("events_json", DType::Str) - .col("links_json", DType::Str); - - let mut table = ExposedTable::create("__bench_spans_u64", &schema, 65536, 16).unwrap(); - - let n = 100_000u64; - bench_loop("span_write (MEMT, u64 IDs)", n, |i| { - let row: Vec = vec![ - Value::U64(0xdeadbeef00000000 + i), // trace_id_hi - Value::U64(i), // trace_id_lo - Value::U64(i * 7), // span_id - Value::U64(0), // parent_span_id - Value::Str("actor.ask"), - Value::Str("INTERNAL"), - Value::I64(1_700_000_000_000_000 + i as i64), - Value::I64(1_700_000_000_001_000 + i as i64), - Value::I64(1000), - Value::Str("OK"), - Value::Str("pulsing"), - Value::Str("actors/counter_0"), - Value::Str("ask"), - Value::Str(""), - Value::Str(""), - Value::Str("ask"), - Value::Str(""), - Value::Str(""), - Value::Str(""), - Value::Str(""), - Value::Str("[]"), - Value::Str("[]"), - ]; - let mut w = table.writer(); - w.push_row(black_box(&row)); - }); -} - -// ── Isolate: format! cost alone ────────────────────────────────────── - -fn bench_format_overhead() { - let n = 100_000u64; - bench_loop("format!(trace_id + span_id) only", n, |i| { - let _tid = black_box(format!("trace-{i:08x}")); - let _sid = black_box(format!("span-{i:08x}")); - }); -} - -// ── Isolate: raw MEMT push_row (no alloc) ──────────────────────────── - -fn bench_memt_raw_push() { - let schema = Schema::new() - .col("a", DType::I64) - .col("b", DType::I64) - .col("c", DType::Str); - - let mut table = ExposedTable::create("__bench_raw_push", &schema, 65536, 16).unwrap(); - let n = 100_000u64; - bench_loop("memt_push (new writer each time)", n, |i| { - let row = [Value::I64(i as i64), Value::I64(42), Value::Str("hello")]; - let mut w = table.writer(); - w.push_row(black_box(&row)); - }); -} - -fn bench_memt_direct_push() { - let schema = Schema::new() - .col("a", DType::I64) - .col("b", DType::I64) - .col("c", DType::Str); - - let mut table = ExposedTable::create("__bench_direct_push", &schema, 65536, 16).unwrap(); - let n = 100_000u64; - bench_loop("memt_push (ExposedTable::push_row)", n, |i| { - let row = [Value::I64(i as i64), Value::I64(42), Value::Str("hello")]; - table.push_row(black_box(&row)); - }); -} - -// ── Baseline: mutex acquire/release ────────────────────────────────── - -fn bench_mutex_baseline() { - let m = std::sync::Mutex::new(0u64); - let n = 1_000_000u64; - bench_loop("mutex lock/unlock (baseline)", n, |_| { - let mut g = m.lock().unwrap(); - *g = black_box(*g + 1); - }); -} - -// ── Main ───────────────────────────────────────────────────────────── - -fn main() { - println!(); - println!("Pulsing tracing overhead benchmark"); - println!("==================================="); - println!(); - println!( - " {:<40} {:>10} {:>10} {:>12}", - "test", "total", "latency", "throughput" - ); - println!(" {}", "-".repeat(76)); - - bench_mutex_baseline(); - bench_format_overhead(); - bench_memt_raw_push(); - bench_memt_direct_push(); - println!(); - bench_span_write(); - bench_span_write_u64_ids(); - bench_metrics_write(); - println!(); - bench_actor_upsert(); - bench_actor_remove(); - bench_member_upsert(); - - println!(); -} diff --git a/crates/pulsing-actor/src/policies/cache_aware.rs b/crates/pulsing-actor/src/policies/cache_aware.rs deleted file mode 100644 index 32e8dfd89..000000000 --- a/crates/pulsing-actor/src/policies/cache_aware.rs +++ /dev/null @@ -1,492 +0,0 @@ -//! Cache-aware load balancing policy -//! -//! This router combines two strategies to optimize both cache utilization and request distribution: -//! -//! 1. Cache-Aware Routing (Approximate Tree) -//! - Maintains an approximate radix tree for each worker based on request history -//! - Routes requests to workers with highest prefix match (cache hit potential) -//! -//! 2. Load Balancing (Shortest Queue with Balance Thresholds) -//! - Tracks pending request counts per worker -//! - Routes to least busy worker when load is imbalanced -//! -//! The router dynamically switches between these strategies based on load conditions: -//! - Uses load balancing when the system is imbalanced -//! - Uses cache-aware routing when the system is balanced -//! -//! A system is considered imbalanced if both conditions are met: -//! 1. (max - min) > abs_threshold -//! 2. max > rel_threshold * min - -use super::{get_healthy_worker_indices, LoadBalancingPolicy, RequestHeaders, Tree, Worker}; -use std::any::Any; -use std::collections::HashMap; -use std::sync::{Arc, Mutex}; -use std::thread; -use std::time::Duration; -use tracing::debug; - -/// Configuration for cache-aware policy -#[derive(Debug, Clone)] -pub struct CacheAwareConfig { - /// Minimum prefix match ratio to use highest-match routing (0.0 to 1.0) - pub cache_threshold: f32, - /// Absolute difference threshold for load imbalance detection - pub balance_abs_threshold: usize, - /// Relative ratio threshold for load imbalance detection - pub balance_rel_threshold: f32, - /// Interval between LRU eviction cycles (seconds, 0 to disable) - pub eviction_interval_secs: u64, - /// Maximum nodes per tree before eviction - pub max_tree_size: usize, -} - -impl Default for CacheAwareConfig { - fn default() -> Self { - Self { - cache_threshold: 0.5, - balance_abs_threshold: 32, - balance_rel_threshold: 1.0001, - eviction_interval_secs: 60, - max_tree_size: 100000, - } - } -} - -/// Cache-aware routing policy -/// -/// Routes requests based on cache affinity when load is balanced, -/// switches to shortest-queue routing when load is imbalanced. -/// Maintains separate trees per model for multi-model support. -#[derive(Debug)] -pub struct CacheAwarePolicy { - config: CacheAwareConfig, - trees: Arc>>, - eviction_handle: Option>, -} - -impl CacheAwarePolicy { - /// Create a new cache-aware policy with default config - pub fn new() -> Self { - Self::with_config(CacheAwareConfig::default()) - } - - /// Create a new cache-aware policy with custom config - pub fn with_config(config: CacheAwareConfig) -> Self { - let trees = Arc::new(Mutex::new(HashMap::::new())); - - // Start background eviction thread if configured - let eviction_handle = if config.eviction_interval_secs > 0 { - let trees_clone = Arc::clone(&trees); - let max_tree_size = config.max_tree_size; - let interval = config.eviction_interval_secs; - - Some(thread::spawn(move || loop { - thread::sleep(Duration::from_secs(interval)); - - if let Ok(mut trees_guard) = trees_clone.lock() { - for (model_id, tree) in trees_guard.iter_mut() { - tree.evict_tenant_by_size(max_tree_size); - debug!( - "Cache eviction completed for model {}, max_size: {}", - model_id, max_tree_size - ); - } - } - })) - } else { - None - }; - - Self { - config, - trees, - eviction_handle, - } - } - - /// Initialize the tree with worker URLs - pub fn init_workers(&self, workers: &[Arc]) { - if let Ok(mut trees) = self.trees.lock() { - // Group workers by model - let mut model_workers: HashMap>> = HashMap::new(); - for worker in workers { - let model_id = worker.model_id(); - let tree_key = if model_id.is_empty() || model_id == "unknown" { - "default".to_string() - } else { - model_id.to_string() - }; - model_workers.entry(tree_key).or_default().push(worker); - } - - // Initialize tree for each model - for (tree_key, model_workers) in model_workers { - let tree = trees.entry(tree_key).or_insert_with(Tree::new); - for worker in model_workers { - tree.insert("", worker.url()); - } - } - } - } - - /// Add a single worker to the tree - pub fn add_worker(&self, worker: &dyn Worker) { - if let Ok(mut trees) = self.trees.lock() { - let model_id = worker.model_id(); - let tree_key = if model_id.is_empty() || model_id == "unknown" { - "default".to_string() - } else { - model_id.to_string() - }; - let tree = trees.entry(tree_key).or_insert_with(Tree::new); - tree.insert("", worker.url()); - } - } - - /// Add a worker by URL and model - pub fn add_worker_by_url(&self, url: &str, model_id: &str) { - if let Ok(mut trees) = self.trees.lock() { - let tree = trees.entry(model_id.to_string()).or_insert_with(Tree::new); - tree.insert("", url); - } - } - - /// Remove a worker from the tree - pub fn remove_worker(&self, worker: &dyn Worker) { - if let Ok(mut trees) = self.trees.lock() { - let model_id = worker.model_id(); - let tree_key = if model_id.is_empty() || model_id == "unknown" { - "default".to_string() - } else { - model_id.to_string() - }; - if let Some(tree) = trees.get_mut(&tree_key) { - tree.remove_tenant(worker.url()); - } - } - } - - /// Remove a worker by URL - pub fn remove_worker_by_url(&self, url: &str) { - if let Ok(mut trees) = self.trees.lock() { - for tree in trees.values_mut() { - tree.remove_tenant(url); - } - } - } - - /// Run cache eviction to prevent unbounded growth - pub fn evict_cache(&self, max_size: usize) { - if let Ok(mut trees) = self.trees.lock() { - for (model_id, tree) in trees.iter_mut() { - tree.evict_tenant_by_size(max_size); - debug!( - "Cache eviction for model {}, max_size: {}", - model_id, max_size - ); - } - } - } -} - -impl LoadBalancingPolicy for CacheAwarePolicy { - fn select_worker_with_headers( - &self, - workers: &[Arc], - request_text: Option<&str>, - _headers: Option<&RequestHeaders>, - ) -> Option { - let healthy_indices = get_healthy_worker_indices(workers); - - if healthy_indices.is_empty() { - return None; - } - - // Group workers by model - let mut model_workers: HashMap> = HashMap::new(); - for idx in &healthy_indices { - let model_id = workers[*idx].model_id(); - let tree_key = if model_id.is_empty() || model_id == "unknown" { - "default".to_string() - } else { - model_id.to_string() - }; - model_workers.entry(tree_key).or_default().push(*idx); - } - - // Get current load statistics - let loads: Vec = workers.iter().map(|w| w.load()).collect(); - let max_load = *loads.iter().max().unwrap_or(&0); - let min_load = *loads.iter().min().unwrap_or(&0); - - // Check if load is imbalanced - let is_imbalanced = max_load.saturating_sub(min_load) > self.config.balance_abs_threshold - && (max_load as f32) > (min_load as f32 * self.config.balance_rel_threshold); - - if is_imbalanced { - debug!( - "Load balancing triggered | max: {} | min: {}", - max_load, min_load - ); - - // Use shortest queue when imbalanced - let min_load_idx = healthy_indices - .iter() - .min_by_key(|&&idx| workers[idx].load()) - .copied()?; - - // Still update tree to maintain cache state - if let Some(text) = request_text { - if let Ok(mut trees) = self.trees.lock() { - let model_id = workers[min_load_idx].model_id(); - let tree_key = if model_id.is_empty() || model_id == "unknown" { - "default".to_string() - } else { - model_id.to_string() - }; - let tree = trees.entry(tree_key).or_insert_with(Tree::new); - tree.insert(text, workers[min_load_idx].url()); - } - } - - return Some(min_load_idx); - } - - // Use cache-aware routing when balanced - let text = request_text.unwrap_or(""); - - if let Ok(mut trees) = self.trees.lock() { - let mut best_match_idx: Option = None; - let mut best_match_rate: f32 = 0.0; - - // Find best match across all models - for (model_id, worker_indices) in &model_workers { - let tree = trees.entry(model_id.clone()).or_insert_with(Tree::new); - - let (matched_text, matched_worker) = tree.prefix_match(text); - let match_rate = if text.is_empty() { - 0.0 - } else { - matched_text.chars().count() as f32 / text.chars().count() as f32 - }; - - if match_rate > best_match_rate { - if let Some(idx) = worker_indices - .iter() - .find(|&&idx| workers[idx].url() == matched_worker) - { - best_match_idx = Some(*idx); - best_match_rate = match_rate; - } - } - } - - // Select worker based on cache threshold - let selected_idx = if let (Some(idx), true) = ( - best_match_idx, - best_match_rate > self.config.cache_threshold, - ) { - debug!("Cache hit with match rate {:.2}", best_match_rate); - idx - } else { - debug!("Cache miss with match rate {:.2}", best_match_rate); - - // Find model with smallest tree (most cache capacity) - let mut smallest_tree_model = String::new(); - let mut smallest_tree_size = usize::MAX; - - for model_id in model_workers.keys() { - let tree = trees.entry(model_id.clone()).or_insert_with(Tree::new); - let size = tree.get_used_size_per_tenant().values().sum::(); - if size < smallest_tree_size { - smallest_tree_size = size; - smallest_tree_model = model_id.clone(); - } - } - - // Select least loaded worker from model with most cache capacity - if let Some(worker_indices) = model_workers.get(&smallest_tree_model) { - worker_indices - .iter() - .min_by_key(|&&idx| workers[idx].load()) - .copied() - .unwrap_or(healthy_indices[0]) - } else { - healthy_indices[0] - } - }; - - // Update the tree with this request - let model_id = workers[selected_idx].model_id(); - let tree_key = if model_id.is_empty() || model_id == "unknown" { - "default".to_string() - } else { - model_id.to_string() - }; - let tree = trees.entry(tree_key).or_insert_with(Tree::new); - tree.insert(text, workers[selected_idx].url()); - - return Some(selected_idx); - } - - // Fallback to first healthy worker - healthy_indices.first().copied() - } - - fn name(&self) -> &'static str { - "cache_aware" - } - - fn needs_request_text(&self) -> bool { - true - } - - fn on_request_complete(&self, worker_url: &str, success: bool) { - if !success { - debug!( - "Request to {} completed with success={}", - worker_url, success - ); - } - } - - fn as_any(&self) -> &dyn Any { - self - } - - fn select_worker_pair_with_headers( - &self, - prefill_workers: &[Arc], - decode_workers: &[Arc], - request_text: Option<&str>, - headers: Option<&RequestHeaders>, - ) -> Option<(usize, usize)> { - // In PD mode: - // - Prefill: Use cache-aware routing for better cache utilization - // - Decode: Use least-load routing for better load distribution - - let prefill_idx = - self.select_worker_with_headers(prefill_workers, request_text, headers)?; - - // Select decode worker using least-load logic - let healthy_decode = get_healthy_worker_indices(decode_workers); - if healthy_decode.is_empty() { - return None; - } - - let decode_idx = healthy_decode - .iter() - .min_by_key(|&&idx| decode_workers[idx].load()) - .copied()?; - - Some((prefill_idx, decode_idx)) - } -} - -impl Default for CacheAwarePolicy { - fn default() -> Self { - Self::new() - } -} - -impl Drop for CacheAwarePolicy { - fn drop(&mut self) { - // Note: The eviction thread will continue until the program exits - // In production, we'd use a channel or atomic flag to signal shutdown - if let Some(handle) = self.eviction_handle.take() { - drop(handle); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::policies::BasicWorker; - - #[test] - fn test_cache_aware_with_balanced_load() { - let config = CacheAwareConfig { - eviction_interval_secs: 0, // Disable eviction thread for testing - ..Default::default() - }; - let policy = CacheAwarePolicy::with_config(config); - let workers: Vec> = vec![ - Arc::new(BasicWorker::new("http://w1:8000".to_string())), - Arc::new(BasicWorker::new("http://w2:8000".to_string())), - ]; - - policy.init_workers(&workers); - - // First request - let idx1 = policy.select_worker(&workers, Some("hello world")).unwrap(); - - // Same request should go to same worker (cache hit) - let idx2 = policy.select_worker(&workers, Some("hello world")).unwrap(); - assert_eq!(idx1, idx2); - - // Similar request should also go to same worker - let idx3 = policy.select_worker(&workers, Some("hello")).unwrap(); - assert_eq!(idx1, idx3); - } - - #[test] - fn test_cache_aware_with_imbalanced_load() { - let policy = CacheAwarePolicy::with_config(CacheAwareConfig { - cache_threshold: 0.5, - balance_abs_threshold: 5, - balance_rel_threshold: 2.0, - eviction_interval_secs: 0, - max_tree_size: 10000, - }); - - let worker1 = BasicWorker::new("http://w1:8000".to_string()); - let worker2 = BasicWorker::new("http://w2:8000".to_string()); - - // Create significant load imbalance - for _ in 0..20 { - worker1.increment_load(); - } - // worker2 has load 0 - - let workers: Vec> = vec![Arc::new(worker1), Arc::new(worker2)]; - policy.init_workers(&workers); - - // Should select worker2 (lower load) despite cache affinity - for _ in 0..5 { - let idx = policy.select_worker(&workers, Some("test")).unwrap(); - assert_eq!(idx, 1); // Should always pick worker2 - } - } - - #[test] - fn test_cache_aware_worker_removal() { - let config = CacheAwareConfig { - eviction_interval_secs: 0, - ..Default::default() - }; - let policy = CacheAwarePolicy::with_config(config); - let workers: Vec> = vec![ - Arc::new(BasicWorker::new("http://w1:8000".to_string())), - Arc::new(BasicWorker::new("http://w2:8000".to_string())), - ]; - - policy.init_workers(&workers); - - // Route some requests - policy.select_worker(&workers, Some("test1")); - policy.select_worker(&workers, Some("test2")); - - // Remove a worker - policy.remove_worker_by_url("http://w1:8000"); - - if let Some(w) = workers[0].as_any().downcast_ref::() { - w.set_health(false); - } - - // All requests should now go to worker2 - let idx = policy.select_worker(&workers, Some("test1")).unwrap(); - assert_eq!(idx, 1); - } -} diff --git a/crates/pulsing-actor/src/policies/consistent_hash.rs b/crates/pulsing-actor/src/policies/consistent_hash.rs index fa196ad07..1951fbe15 100644 --- a/crates/pulsing-actor/src/policies/consistent_hash.rs +++ b/crates/pulsing-actor/src/policies/consistent_hash.rs @@ -43,13 +43,10 @@ impl ConsistentHashPolicy { let mut h = (seed as u64) ^ ((key.len() as u64).wrapping_mul(M)); // Process 8-byte chunks - let chunks = key.chunks_exact(8); - let remainder = chunks.remainder(); + let (chunks, remainder) = key.as_chunks::<8>(); for chunk in chunks { - let mut k = u64::from_le_bytes([ - chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7], - ]); + let mut k = u64::from_le_bytes(*chunk); k = k.wrapping_mul(M); k ^= k >> R; @@ -484,20 +481,6 @@ impl LoadBalancingPolicy for ConsistentHashPolicy { fn as_any(&self) -> &dyn Any { self } - - fn select_worker_pair_with_headers( - &self, - prefill_workers: &[Arc], - decode_workers: &[Arc], - request_text: Option<&str>, - headers: Option<&RequestHeaders>, - ) -> Option<(usize, usize)> { - // For PD mode, use consistent hashing for both prefill and decode - let prefill_idx = - self.select_worker_with_headers(prefill_workers, request_text, headers)?; - let decode_idx = self.select_worker_with_headers(decode_workers, request_text, headers)?; - Some((prefill_idx, decode_idx)) - } } impl Default for ConsistentHashPolicy { diff --git a/crates/pulsing-actor/src/policies/mod.rs b/crates/pulsing-actor/src/policies/mod.rs index 1778e88e9..9534689e9 100644 --- a/crates/pulsing-actor/src/policies/mod.rs +++ b/crates/pulsing-actor/src/policies/mod.rs @@ -10,7 +10,6 @@ //! - [`RoundRobinPolicy`]: Sequential selection cycling through healthy workers //! - [`PowerOfTwoPolicy`]: Power-of-two choices for better load distribution //! - [`ConsistentHashPolicy`]: Session/user affinity using consistent hashing -//! - [`CacheAwarePolicy`]: Cache-aware routing with radix tree prefix matching //! //! # Example //! @@ -24,19 +23,15 @@ //! } //! ``` -mod cache_aware; mod consistent_hash; mod power_of_two; mod random; mod round_robin; -mod tree; -pub use cache_aware::{CacheAwareConfig, CacheAwarePolicy}; pub use consistent_hash::ConsistentHashPolicy; pub use power_of_two::PowerOfTwoPolicy; pub use random::RandomPolicy; pub use round_robin::RoundRobinPolicy; -pub use tree::Tree; use std::any::Any; use std::collections::HashMap; @@ -74,11 +69,6 @@ pub trait Worker: Send + Sync + std::fmt::Debug { /// Get the total number of processed requests fn processed(&self) -> u64; - /// Get the model ID this worker serves (for multi-model support) - fn model_id(&self) -> &str { - "default" - } - /// Check if the circuit breaker allows execution fn circuit_breaker_allows(&self) -> bool { true @@ -147,31 +137,6 @@ pub trait LoadBalancingPolicy: Send + Sync + std::fmt::Debug { /// Callback when a request completes fn on_request_complete(&self, _worker_url: &str, _success: bool) {} - /// Select a pair of workers for prefill-decode disaggregated serving - fn select_worker_pair( - &self, - prefill_workers: &[Arc], - decode_workers: &[Arc], - request_text: Option<&str>, - ) -> Option<(usize, usize)> { - self.select_worker_pair_with_headers(prefill_workers, decode_workers, request_text, None) - } - - /// Select a pair of workers with headers for PD mode - fn select_worker_pair_with_headers( - &self, - prefill_workers: &[Arc], - decode_workers: &[Arc], - request_text: Option<&str>, - headers: Option<&RequestHeaders>, - ) -> Option<(usize, usize)> { - // Default implementation: select independently - let prefill_idx = - self.select_worker_with_headers(prefill_workers, request_text, headers)?; - let decode_idx = self.select_worker_with_headers(decode_workers, request_text, headers)?; - Some((prefill_idx, decode_idx)) - } - /// Get self as Any for downcasting fn as_any(&self) -> &dyn Any; } @@ -190,7 +155,6 @@ pub fn get_healthy_worker_indices(workers: &[Arc]) -> Vec { #[derive(Debug)] pub struct BasicWorker { url: String, - model_id: String, healthy: std::sync::atomic::AtomicBool, load: std::sync::atomic::AtomicUsize, processed: std::sync::atomic::AtomicU64, @@ -201,18 +165,6 @@ impl BasicWorker { pub fn new(url: String) -> Self { Self { url, - model_id: "default".to_string(), - healthy: std::sync::atomic::AtomicBool::new(true), - load: std::sync::atomic::AtomicUsize::new(0), - processed: std::sync::atomic::AtomicU64::new(0), - } - } - - /// Create a new worker with a model ID - pub fn with_model(url: String, model_id: String) -> Self { - Self { - url, - model_id, healthy: std::sync::atomic::AtomicBool::new(true), load: std::sync::atomic::AtomicUsize::new(0), processed: std::sync::atomic::AtomicU64::new(0), @@ -255,10 +207,6 @@ impl Worker for BasicWorker { self.processed.load(std::sync::atomic::Ordering::Relaxed) } - fn model_id(&self) -> &str { - &self.model_id - } - fn as_any(&self) -> &dyn Any { self } @@ -320,20 +268,6 @@ mod tests { assert_eq!(worker.url(), "http://localhost:9000"); } - #[test] - fn test_basic_worker_with_model() { - let worker = - BasicWorker::with_model("http://localhost:8000".to_string(), "llama-7b".to_string()); - assert_eq!(worker.url(), "http://localhost:8000"); - assert_eq!(worker.model_id(), "llama-7b"); - } - - #[test] - fn test_basic_worker_default_model() { - let worker = BasicWorker::new("http://localhost:8000".to_string()); - assert_eq!(worker.model_id(), "default"); - } - #[test] fn test_basic_worker_load_increment_decrement() { let worker = BasicWorker::new("http://localhost:8000".to_string()); diff --git a/crates/pulsing-actor/src/policies/tree.rs b/crates/pulsing-actor/src/policies/tree.rs deleted file mode 100644 index a5a6470bb..000000000 --- a/crates/pulsing-actor/src/policies/tree.rs +++ /dev/null @@ -1,649 +0,0 @@ -//! Thread-safe multi-tenant radix tree for cache-aware routing -//! -//! This module provides a radix tree implementation that: -//! - Stores data for multiple tenants (workers) with overlapping prefixes -//! - Uses node-level locking for concurrent access -//! - Supports LRU eviction based on tenant access time -//! -//! The tree is used by CacheAwarePolicy to track request history and -//! make routing decisions based on prefix matching. - -use std::cmp::Reverse; -use std::collections::{BinaryHeap, HashMap, VecDeque}; -use std::sync::{Arc, RwLock}; -use std::time::{SystemTime, UNIX_EPOCH}; -use tracing::debug; - -type NodeRef = Arc; - -#[derive(Debug)] -struct Node { - children: RwLock>, - text: RwLock, - tenant_last_access_time: RwLock>, - parent: RwLock>, -} - -/// Thread-safe multi-tenant radix tree -/// -/// Stores request history for multiple workers (tenants) and supports -/// prefix matching for cache-aware routing decisions. -#[derive(Debug)] -pub struct Tree { - root: NodeRef, - pub tenant_char_count: RwLock>, -} - -// Eviction entry for priority queue -struct EvictionEntry { - timestamp: u128, - tenant: String, - node: NodeRef, -} - -impl Eq for EvictionEntry {} - -impl PartialOrd for EvictionEntry { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for EvictionEntry { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.timestamp.cmp(&other.timestamp) - } -} - -impl PartialEq for EvictionEntry { - fn eq(&self, other: &Self) -> bool { - self.timestamp == other.timestamp - } -} - -// UTF-8 character utilities -fn shared_prefix_count(a: &str, b: &str) -> usize { - let mut i = 0; - let mut a_iter = a.chars(); - let mut b_iter = b.chars(); - - loop { - match (a_iter.next(), b_iter.next()) { - (Some(a_char), Some(b_char)) if a_char == b_char => { - i += 1; - } - _ => break, - } - } - - i -} - -fn slice_by_chars(s: &str, start: usize, end: usize) -> String { - s.chars().skip(start).take(end - start).collect() -} - -impl Default for Tree { - fn default() -> Self { - Self::new() - } -} - -impl Tree { - /// Create a new empty tree - pub fn new() -> Self { - Tree { - root: Arc::new(Node { - children: RwLock::new(HashMap::new()), - text: RwLock::new(String::new()), - tenant_last_access_time: RwLock::new(HashMap::new()), - parent: RwLock::new(None), - }), - tenant_char_count: RwLock::new(HashMap::new()), - } - } - - /// Insert text into tree with given tenant (worker URL) - pub fn insert(&self, text: &str, tenant: &str) { - let mut curr = Arc::clone(&self.root); - let mut curr_idx = 0; - - let timestamp_ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_millis(); - - // Update root's tenant access time - { - let mut access_times = curr.tenant_last_access_time.write().unwrap(); - access_times.insert(tenant.to_string(), timestamp_ms); - } - - // Initialize tenant char count if not exists - { - let mut counts = self.tenant_char_count.write().unwrap(); - counts.entry(tenant.to_string()).or_insert(0); - } - - let mut prev = Arc::clone(&self.root); - let text_count = text.chars().count(); - - while curr_idx < text_count { - let first_char = text.chars().nth(curr_idx).unwrap(); - curr = prev; - - let child = { - let children = curr.children.read().unwrap(); - children.get(&first_char).cloned() - }; - - match child { - None => { - // No match - create new node - let curr_text = slice_by_chars(text, curr_idx, text_count); - let curr_text_count = curr_text.chars().count(); - - let new_node = Arc::new(Node { - children: RwLock::new(HashMap::new()), - text: RwLock::new(curr_text), - tenant_last_access_time: RwLock::new(HashMap::new()), - parent: RwLock::new(Some(Arc::clone(&curr))), - }); - - // Update tenant char count - { - let mut counts = self.tenant_char_count.write().unwrap(); - counts - .entry(tenant.to_string()) - .and_modify(|count| *count += curr_text_count) - .or_insert(curr_text_count); - } - - // Set tenant access time on new node - { - let mut access_times = new_node.tenant_last_access_time.write().unwrap(); - access_times.insert(tenant.to_string(), timestamp_ms); - } - - // Add to parent's children - { - let mut children = curr.children.write().unwrap(); - children.insert(first_char, Arc::clone(&new_node)); - } - - prev = new_node; - curr_idx = text_count; - } - Some(matched_node) => { - let matched_node_text = matched_node.text.read().unwrap().clone(); - let matched_node_text_count = matched_node_text.chars().count(); - - let curr_text = slice_by_chars(text, curr_idx, text_count); - let shared_count = shared_prefix_count(&matched_node_text, &curr_text); - - if shared_count < matched_node_text_count { - // Split the matched node - let matched_text = slice_by_chars(&matched_node_text, 0, shared_count); - let contracted_text = slice_by_chars( - &matched_node_text, - shared_count, - matched_node_text_count, - ); - let matched_text_count = matched_text.chars().count(); - - // Clone tenant access times from matched node - let cloned_access_times = { - let times = matched_node.tenant_last_access_time.read().unwrap(); - times.clone() - }; - - let new_node = Arc::new(Node { - text: RwLock::new(matched_text), - children: RwLock::new(HashMap::new()), - parent: RwLock::new(Some(Arc::clone(&curr))), - tenant_last_access_time: RwLock::new(cloned_access_times), - }); - - // Add matched node as child of new node - let first_new_char = contracted_text.chars().next().unwrap(); - { - let mut children = new_node.children.write().unwrap(); - children.insert(first_new_char, Arc::clone(&matched_node)); - } - - // Update parent's children - { - let mut children = curr.children.write().unwrap(); - children.insert(first_char, Arc::clone(&new_node)); - } - - // Update matched node - { - let mut text = matched_node.text.write().unwrap(); - *text = contracted_text; - } - { - let mut parent = matched_node.parent.write().unwrap(); - *parent = Some(Arc::clone(&new_node)); - } - - prev = Arc::clone(&new_node); - - // Update tenant access time on new node - { - let mut access_times = prev.tenant_last_access_time.write().unwrap(); - let is_new = !access_times.contains_key(tenant); - access_times.insert(tenant.to_string(), timestamp_ms); - - if is_new { - let mut counts = self.tenant_char_count.write().unwrap(); - counts - .entry(tenant.to_string()) - .and_modify(|count| *count += matched_text_count) - .or_insert(matched_text_count); - } - } - - curr_idx += shared_count; - } else { - // Full match - move to next node - prev = Arc::clone(&matched_node); - - // Update tenant access time - { - let mut access_times = prev.tenant_last_access_time.write().unwrap(); - let is_new = !access_times.contains_key(tenant); - access_times.insert(tenant.to_string(), timestamp_ms); - - if is_new { - let mut counts = self.tenant_char_count.write().unwrap(); - counts - .entry(tenant.to_string()) - .and_modify(|count| *count += matched_node_text_count) - .or_insert(matched_node_text_count); - } - } - - curr_idx += shared_count; - } - } - } - } - } - - /// Find the longest prefix match and return (matched_text, tenant) - pub fn prefix_match(&self, text: &str) -> (String, String) { - let mut curr_idx = 0; - - let mut prev = Arc::clone(&self.root); - let text_count = text.chars().count(); - - while curr_idx < text_count { - let first_char = text.chars().nth(curr_idx).unwrap(); - let curr_text = slice_by_chars(text, curr_idx, text_count); - - let curr = prev.clone(); - - let child = { - let children = curr.children.read().unwrap(); - children.get(&first_char).cloned() - }; - - if let Some(matched_node) = child { - let matched_text = matched_node.text.read().unwrap().clone(); - let shared_count = shared_prefix_count(&matched_text, &curr_text); - let matched_node_text_count = matched_text.chars().count(); - - if shared_count == matched_node_text_count { - // Full match, continue to next node - curr_idx += shared_count; - prev = Arc::clone(&matched_node); - } else { - // Partial match, stop here - curr_idx += shared_count; - prev = Arc::clone(&matched_node); - break; - } - } else { - // No match found - break; - } - } - - let curr = prev; - - // Select the first tenant (or most recently accessed) - let tenant = { - let access_times = curr.tenant_last_access_time.read().unwrap(); - access_times - .iter() - .max_by_key(|(_, &time)| time) - .map(|(t, _)| t.clone()) - .unwrap_or_else(|| "empty".to_string()) - }; - - // Update access times along the path - if tenant != "empty" { - let timestamp_ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_millis(); - - let mut current_node = Some(curr); - while let Some(node) = current_node { - { - let mut access_times = node.tenant_last_access_time.write().unwrap(); - access_times.insert(tenant.clone(), timestamp_ms); - } - current_node = node.parent.read().unwrap().clone(); - } - } - - let ret_text = slice_by_chars(text, 0, curr_idx); - (ret_text, tenant) - } - - /// Get leaf tenants for a node (tenants that don't have children) - fn leaf_of(node: &NodeRef) -> Vec { - let mut candidates: HashMap = { - let access_times = node.tenant_last_access_time.read().unwrap(); - access_times.keys().map(|k| (k.clone(), true)).collect() - }; - - let children = node.children.read().unwrap(); - for child in children.values() { - let child_times = child.tenant_last_access_time.read().unwrap(); - for tenant in child_times.keys() { - candidates.insert(tenant.clone(), false); - } - } - - candidates - .into_iter() - .filter(|(_, is_leaf)| *is_leaf) - .map(|(tenant, _)| tenant) - .collect() - } - - /// Evict tenant data by size limit using LRU - pub fn evict_tenant_by_size(&self, max_size: usize) { - // Collect leaves into priority queue - let mut stack = vec![Arc::clone(&self.root)]; - let mut pq = BinaryHeap::new(); - - while let Some(curr) = stack.pop() { - let children = curr.children.read().unwrap(); - for child in children.values() { - stack.push(Arc::clone(child)); - } - drop(children); - - for tenant in Tree::leaf_of(&curr) { - let access_times = curr.tenant_last_access_time.read().unwrap(); - if let Some(×tamp) = access_times.get(&tenant) { - pq.push(Reverse(EvictionEntry { - timestamp, - tenant: tenant.clone(), - node: Arc::clone(&curr), - })); - } - } - } - - debug!( - "Before eviction - tenant char counts: {:?}", - self.tenant_char_count.read().unwrap() - ); - - // Process eviction - while let Some(Reverse(entry)) = pq.pop() { - let EvictionEntry { tenant, node, .. } = entry; - - let used_size = { - let counts = self.tenant_char_count.read().unwrap(); - counts.get(&tenant).copied().unwrap_or(0) - }; - - if used_size <= max_size { - continue; - } - - // Decrement count when removing tenant from node - { - let access_times = node.tenant_last_access_time.read().unwrap(); - if access_times.contains_key(&tenant) { - let node_len = node.text.read().unwrap().chars().count(); - let mut counts = self.tenant_char_count.write().unwrap(); - counts.entry(tenant.clone()).and_modify(|count| { - *count = count.saturating_sub(node_len); - }); - } - } - - // Remove tenant from node - { - let mut access_times = node.tenant_last_access_time.write().unwrap(); - access_times.remove(&tenant); - } - - // Get parent reference before checking if node should be removed - let parent_ref = node.parent.read().unwrap().clone(); - - // Remove empty nodes - { - let children = node.children.read().unwrap(); - let access_times = node.tenant_last_access_time.read().unwrap(); - if children.is_empty() && access_times.is_empty() { - drop(children); - drop(access_times); - - if let Some(ref parent) = parent_ref { - let text = node.text.read().unwrap(); - if let Some(first_char) = text.chars().next() { - let mut parent_children = parent.children.write().unwrap(); - parent_children.remove(&first_char); - } - } - } - } - - // Add parent to queue if it becomes a leaf - if let Some(ref parent) = parent_ref { - if Tree::leaf_of(parent).contains(&tenant) { - let access_times = parent.tenant_last_access_time.read().unwrap(); - if let Some(×tamp) = access_times.get(&tenant) { - pq.push(Reverse(EvictionEntry { - timestamp, - tenant: tenant.clone(), - node: Arc::clone(parent), - })); - } - } - } - } - - debug!( - "After eviction - tenant char counts: {:?}", - self.tenant_char_count.read().unwrap() - ); - } - - /// Remove all data for a tenant - pub fn remove_tenant(&self, tenant: &str) { - // Find all leaves for the tenant - let mut stack = vec![Arc::clone(&self.root)]; - let mut queue = VecDeque::new(); - - while let Some(curr) = stack.pop() { - let children = curr.children.read().unwrap(); - for child in children.values() { - stack.push(Arc::clone(child)); - } - drop(children); - - if Tree::leaf_of(&curr).contains(&tenant.to_string()) { - queue.push_back(Arc::clone(&curr)); - } - } - - // Traverse up from leaves, removing tenant - while let Some(curr) = queue.pop_front() { - { - let mut access_times = curr.tenant_last_access_time.write().unwrap(); - access_times.remove(tenant); - } - - // Remove empty nodes - let children = curr.children.read().unwrap(); - let access_times = curr.tenant_last_access_time.read().unwrap(); - if children.is_empty() && access_times.is_empty() { - drop(children); - drop(access_times); - - if let Some(parent) = curr.parent.read().unwrap().as_ref() { - let text = curr.text.read().unwrap(); - if let Some(first_char) = text.chars().next() { - let mut parent_children = parent.children.write().unwrap(); - parent_children.remove(&first_char); - } - } - } else { - drop(children); - drop(access_times); - } - - // Add parent to queue if it becomes a leaf - if let Some(parent) = curr.parent.read().unwrap().as_ref() { - if Tree::leaf_of(parent).contains(&tenant.to_string()) { - queue.push_back(Arc::clone(parent)); - } - } - } - - // Remove from char count - { - let mut counts = self.tenant_char_count.write().unwrap(); - counts.remove(tenant); - } - } - - /// Get the tenant with smallest tree size - pub fn get_smallest_tenant(&self) -> String { - let counts = self.tenant_char_count.read().unwrap(); - - if counts.is_empty() { - return "empty".to_string(); - } - - counts - .iter() - .min_by_key(|(_, &count)| count) - .map(|(tenant, _)| tenant.clone()) - .unwrap_or_else(|| "empty".to_string()) - } - - /// Get the used size per tenant - pub fn get_used_size_per_tenant(&self) -> HashMap { - self.tenant_char_count.read().unwrap().clone() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_cold_start() { - let tree = Tree::new(); - let (matched_text, tenant) = tree.prefix_match("hello"); - assert_eq!(matched_text, ""); - assert_eq!(tenant, "empty"); - } - - #[test] - fn test_exact_match() { - let tree = Tree::new(); - tree.insert("hello", "tenant1"); - tree.insert("apple", "tenant2"); - tree.insert("banana", "tenant3"); - - let (matched_text, tenant) = tree.prefix_match("hello"); - assert_eq!(matched_text, "hello"); - assert_eq!(tenant, "tenant1"); - - let (matched_text, tenant) = tree.prefix_match("apple"); - assert_eq!(matched_text, "apple"); - assert_eq!(tenant, "tenant2"); - - let (matched_text, tenant) = tree.prefix_match("banana"); - assert_eq!(matched_text, "banana"); - assert_eq!(tenant, "tenant3"); - } - - #[test] - fn test_prefix_match() { - let tree = Tree::new(); - tree.insert("hello world", "tenant1"); - - let (matched_text, tenant) = tree.prefix_match("hello"); - assert_eq!(matched_text, "hello"); - assert_eq!(tenant, "tenant1"); - - let (matched_text, tenant) = tree.prefix_match("hello world!"); - assert_eq!(matched_text, "hello world"); - assert_eq!(tenant, "tenant1"); - } - - #[test] - fn test_shared_prefix() { - let tree = Tree::new(); - tree.insert("apple", "tenant1"); - tree.insert("application", "tenant2"); - - let (matched_text, tenant) = tree.prefix_match("app"); - assert_eq!(matched_text, "app"); - // Should return one of the tenants - assert!(tenant == "tenant1" || tenant == "tenant2"); - } - - #[test] - fn test_tenant_removal() { - let tree = Tree::new(); - tree.insert("hello", "tenant1"); - tree.insert("hello", "tenant2"); - - tree.remove_tenant("tenant1"); - - let (matched_text, tenant) = tree.prefix_match("hello"); - assert_eq!(matched_text, "hello"); - assert_eq!(tenant, "tenant2"); - } - - #[test] - fn test_get_smallest_tenant() { - let tree = Tree::new(); - - assert_eq!(tree.get_smallest_tenant(), "empty"); - - tree.insert("hello", "tenant1"); - tree.insert("world", "tenant1"); - tree.insert("hi", "tenant2"); - - // tenant2 has 2 chars, tenant1 has 10 chars - assert_eq!(tree.get_smallest_tenant(), "tenant2"); - } - - #[test] - fn test_utf8_support() { - let tree = Tree::new(); - tree.insert("你好", "tenant1"); - tree.insert("你好世界", "tenant2"); - - let (matched_text, _tenant) = tree.prefix_match("你好"); - assert_eq!(matched_text, "你好"); - - let (matched_text, tenant) = tree.prefix_match("你好世界"); - assert_eq!(matched_text, "你好世界"); - assert_eq!(tenant, "tenant2"); - } -} diff --git a/crates/pulsing-actor/src/system_actor/service.rs b/crates/pulsing-actor/src/system_actor/service.rs index 7d0dd0e48..87fdf97fe 100644 --- a/crates/pulsing-actor/src/system_actor/service.rs +++ b/crates/pulsing-actor/src/system_actor/service.rs @@ -2,7 +2,7 @@ //! //! A service is a governed node capability, not a resource owner. The host owns //! resources, the component owns lifecycle hooks, and the handler owns request -//! semantics. Keeping those roles separate allows future Forge and agent +//! semantics. Keeping those roles separate allows application //! extensions without turning SystemRoot into a service locator. use super::lifecycle::NodeState; diff --git a/crates/pulsing-bench-py/Cargo.toml b/crates/pulsing-bench-py/Cargo.toml deleted file mode 100644 index 035214050..000000000 --- a/crates/pulsing-bench-py/Cargo.toml +++ /dev/null @@ -1,35 +0,0 @@ -[package] -name = "pulsing-bench-py" -version.workspace = true -edition = "2021" -authors.workspace = true -license.workspace = true -description = "Python bindings for Pulsing Benchmark" - -[lib] -name = "_bench" -crate-type = ["cdylib"] - -[dependencies] -pulsing-bench = { path = "../pulsing-bench" } - -# Serialization -serde_json = { workspace = true } - -# Logging -tracing = { workspace = true } -tracing-subscriber = { workspace = true } - -# PyO3 dependencies -pyo3 = { version = "0.23.4", default-features = false, features = [ - "macros", - "experimental-async", - "extension-module", - "py-clone", - "abi3-py310", -] } -pyo3-async-runtimes = { version = "0.23.0", default-features = false, features = [ - "attributes", - "tokio-runtime", - "unstable-streams", -] } diff --git a/crates/pulsing-bench-py/pyproject.toml b/crates/pulsing-bench-py/pyproject.toml deleted file mode 100644 index 0707135dd..000000000 --- a/crates/pulsing-bench-py/pyproject.toml +++ /dev/null @@ -1,21 +0,0 @@ -[project] -name = "pulsing-bench" -version = "0.1.3" -description = "Pulsing Benchmark - LLM Inference Benchmark Tool" -readme = "../../README.md" -authors = [ - { name = "Reiase", email = "reiase@gmail.com" } -] -license = "Apache-2.0" -requires-python = ">=3.10" -dependencies = ["pulsing"] # Requires core pulsing package - -[build-system] -requires = ["maturin>=1.0,<2.0"] -build-backend = "maturin" - -# Extension-only wheel: install ``pulsing/_bench.*`` next to the main package. -# Do NOT set python-packages/python-source — a stub pulsing/__init__.py in this -# crate used to overwrite the real package when CI ran ``pip install dist/*.whl``. -[tool.maturin] -module-name = "pulsing._bench" diff --git a/crates/pulsing-bench-py/src/lib.rs b/crates/pulsing-bench-py/src/lib.rs deleted file mode 100644 index 8c4192754..000000000 --- a/crates/pulsing-bench-py/src/lib.rs +++ /dev/null @@ -1,132 +0,0 @@ -//! Python bindings for Pulsing Benchmark - -use pulsing_bench::{parse_duration, run_benchmark, BenchmarkArgs}; -use pyo3::exceptions::{PyRuntimeError, PyValueError}; -use pyo3::prelude::*; -use pyo3::types::PyDict; - -// Helper functions for parsing config dict -fn get_opt_str(dict: &Bound<'_, PyDict>, key: &str) -> PyResult> { - match dict.get_item(key)? { - Some(v) => Ok(v.extract::().ok()), - None => Ok(None), - } -} - -fn get_opt pyo3::FromPyObject<'a>>( - dict: &Bound<'_, PyDict>, - key: &str, -) -> PyResult> { - match dict.get_item(key)? { - Some(v) => Ok(v.extract::().ok()), - None => Ok(None), - } -} - -/// Run benchmark -/// -/// Args: -/// config: Dictionary with benchmark configuration -/// - url: str (default: "http://localhost:8000") -/// - api_key: str (default: "") -/// - model_name: str (required) -/// - tokenizer_name: str (optional, defaults to model_name) -/// - hf_token: str (optional, for private models) -/// - max_vus: int (default: 128) -/// - duration: str (default: "120s") -/// - warmup: str (default: "30s") -/// - benchmark_kind: str (default: "throughput") -/// - num_rates: int (default: 10) -/// - rates: list[float] (optional) -/// - num_workers: int (default: 4) -/// -/// Returns: -/// JSON string with benchmark report -#[pyfunction] -fn benchmark_main<'py>(py: Python<'py>, config: PyObject) -> PyResult> { - let config_dict = config.bind(py).downcast::()?; - - // Parse configuration - let url = - get_opt_str(config_dict, "url")?.unwrap_or_else(|| "http://localhost:8000".to_string()); - - let api_key = get_opt_str(config_dict, "api_key")?.unwrap_or_default(); - - // model_name is required - let model_name = config_dict - .get_item("model_name")? - .ok_or_else(|| PyValueError::new_err("model_name is required"))? - .extract::()?; - - // tokenizer_name is optional, defaults to model_name - let tokenizer_name = get_opt_str(config_dict, "tokenizer_name")?; - - // hf_token for private models - let hf_token = get_opt_str(config_dict, "hf_token")?; - - let max_vus = get_opt::(config_dict, "max_vus")?.unwrap_or(128); - - let duration_str = get_opt_str(config_dict, "duration")?.unwrap_or_else(|| "120s".to_string()); - let duration_secs = parse_duration(&duration_str) - .map_err(|e| PyValueError::new_err(format!("Invalid duration: {}", e)))? - .as_secs(); - - let warmup_str = get_opt_str(config_dict, "warmup")?.unwrap_or_else(|| "30s".to_string()); - let warmup_secs = parse_duration(&warmup_str) - .map_err(|e| PyValueError::new_err(format!("Invalid warmup duration: {}", e)))? - .as_secs(); - - let benchmark_kind = - get_opt_str(config_dict, "benchmark_kind")?.unwrap_or_else(|| "throughput".to_string()); - - let num_rates = get_opt::(config_dict, "num_rates")?.unwrap_or(10); - - let rates: Option> = get_opt::>(config_dict, "rates")?; - - let num_workers = get_opt::(config_dict, "num_workers")?.unwrap_or(4); - - let args = BenchmarkArgs { - url, - api_key, - model_name, - tokenizer_name, - hf_token, - max_vus, - duration_secs, - warmup_secs, - benchmark_kind, - num_rates, - rates, - num_workers, - }; - - pyo3_async_runtimes::tokio::future_into_py(py, async move { - let report = run_benchmark(args) - .await - .map_err(|e| PyRuntimeError::new_err(e.to_string()))?; - - // Convert report to JSON string for Python - let json = serde_json::to_string_pretty(&report) - .map_err(|e| PyRuntimeError::new_err(format!("Failed to serialize report: {}", e)))?; - - Ok(json) - }) -} - -/// Pulsing Benchmark Python module -#[pymodule] -fn _bench(m: &Bound<'_, PyModule>) -> PyResult<()> { - // Initialize tracing for logging - tracing_subscriber::fmt() - .with_env_filter( - tracing_subscriber::EnvFilter::from_default_env() - .add_directive(tracing::Level::INFO.into()), - ) - .try_init() - .ok(); - - m.add_function(wrap_pyfunction!(benchmark_main, m)?)?; - m.add("__version__", env!("CARGO_PKG_VERSION"))?; - - Ok(()) -} diff --git a/crates/pulsing-bench/Cargo.toml b/crates/pulsing-bench/Cargo.toml deleted file mode 100644 index d8874d1ee..000000000 --- a/crates/pulsing-bench/Cargo.toml +++ /dev/null @@ -1,72 +0,0 @@ -[package] -name = "pulsing-bench" -version = "1.1.0" -edition.workspace = true -authors.workspace = true -license.workspace = true -repository.workspace = true -readme = "README.md" -description = "Actor-based LLM inference benchmark tool" - -[features] -default = [] -python = ["pyo3", "pyo3-async-runtimes", "tracing-subscriber"] - -[dependencies] -# Core -tokio = { workspace = true } -anyhow = { workspace = true } -async-trait = { workspace = true } -futures-util = { workspace = true } - -# HTTP -reqwest = { workspace = true } -reqwest-eventsource = { workspace = true } - -# Serialization -serde = { workspace = true } -serde_json = { workspace = true } - -# Logging -log = { workspace = true } -tracing = { workspace = true } -tracing-subscriber = { workspace = true, optional = true } - -# Utilities -uuid = { workspace = true } -humantime = { workspace = true } -colored = { workspace = true } -chrono = { workspace = true } -rand = { workspace = true } - -# Tokenizer for accurate token counting -tokenizers = { workspace = true } -hf-hub = { workspace = true } - -# Pulsing Actor System -pulsing-actor = { workspace = true } - -# PyO3 dependencies (optional, for python bindings) -pyo3 = { version = "0.23.4", default-features = false, features = [ - "macros", - "experimental-async", - "extension-module", - "py-clone", - "abi3-py310", -], optional = true } -pyo3-async-runtimes = { version = "0.23.0", default-features = false, features = [ - "attributes", - "tokio-runtime", - "unstable-streams", -], optional = true } - -[build-dependencies] -vergen-gitcl = { workspace = true } - -[lib] -name = "pulsing_bench" -path = "src/lib.rs" -crate-type = ["rlib", "cdylib"] - -[lints] -workspace = true diff --git a/crates/pulsing-bench/README.md b/crates/pulsing-bench/README.md deleted file mode 100644 index e720fde77..000000000 --- a/crates/pulsing-bench/README.md +++ /dev/null @@ -1,274 +0,0 @@ -# Inference Benchmarker -**The best tool for benchmarking inference engines and LLM performance** - - -Benchmarking inference servers for text generation models presents unique challenges. -The performance of LLM models can vary greatly depending on factors like input prompts, -decoding strategies, hardware specifications, and server configurations. - -**Inference Benchmarker** is designed to streamline this process by providing a comprehensive benchmarking tool -that evaluates the real-world performance of text generation models and servers. -With **Inference Benchmarker**, you can easily test your model's throughput and efficiency under various workloads, -identify performance bottlenecks, and optimize your deployment for production environments. - -It can be used to benchmark any text generation server that exposes an OpenAI-compliant API. - -## Features - -* Broad Compatibility: Benchmarks any text generation server with an OpenAPI-compliant chat API. -* Automatic Sweep Mode: Detects maximum throughput and sweeps in-between. -* Open-Loop Benchmarking: Uses constant arrival rates to simulate real-world workloads. -* Benchmark profiles: Presets to benchmark for different model use cases (eg. chat, summarization, code completion...). -* High-Performance: Built with Rust 🦀 for high-performance benchmarking. -* JSON Output: Delivers performance results in a structured, easy-to-analyze format. - -![ui.png](assets/ui.png) - -## Table of contents - - -* [Inference Benchmarker](#inference-benchmarker) - * [Features](#features) - * [Table of contents](#table-of-contents) - * [Get started](#get-started) - * [Run a benchmark](#run-a-benchmark) - * [1. Start an inference server](#1-start-an-inference-server) - * [2. Run a benchmark using Docker image](#2-run-a-benchmark-using-docker-image) - * [Configure your benchmark](#configure-your-benchmark) - * [Profiles](#profiles) - * [Benchmark mode](#benchmark-mode) - * [Dataset configuration](#dataset-configuration) - * [Prompt configuration](#prompt-configuration) - * [Decode options](#decode-options) - * [Deploy on Kubernetes](#deploy-on-kubernetes) - * [Deploy on Slurm](#deploy-on-slurm) - * [Visualize the results](#visualize-the-results) - * [Development](#development) - * [Frequently Asked Questions](#frequently-asked-questions) - - -## Get started - -### Install - -If you have [cargo](https://rustup.rs/) already installed: -```bash -cargo install --git https://github.com/huggingface/inference-benchmarker/ -``` - -Or download the [latest released binary](https://github.com/huggingface/inference-benchmarker/releases/latest) - -Or you can run docker images. - -### Run a benchmark - -#### 1. Start an inference server - -**TGI** - -```bash -MODEL=meta-llama/Llama-3.1-8B-Instruct -HF_TOKEN= - -docker run --gpus all --shm-size 1g -p 8080:80 -e "HF_TOKEN=$HF_TOKEN" \ - ghcr.io/huggingface/text-generation-inference:3.2.1 --model-id $MODEL -``` - -**vLLM** - -```bash -MODEL=meta-llama/Llama-3.1-8B-Instruct -HF_TOKEN= -docker run --runtime nvidia --gpus all \ - --env "HUGGING_FACE_HUB_TOKEN=$HF_TOKEN" \ - -p 8080:8000 \ - --ipc=host \ - vllm/vllm-openai:latest \ - --model $MODEL -``` - - -#### 2. Run a benchmark - -```shell -inference-benchmarker \ - --tokenizer-name "meta-llama/Llama-3.1-8B-Instruct" \ - --url http://localhost:8080 \ - --profile chat -``` - -Results will be saved in JSON format in current directory. - -### Configure your benchmark - -#### Profiles - -Profiles are presets to benchmark for different model use cases. Available profiles: -- `chat` - Simulates a multi-turn chat scenario in which the model answers to successive user prompts. - The model is prompted with the whole conversation history at each turn. Prefix caching will have a significant impact - on the performance of this benchmark. -- `code-generation` - Simulates code-complete scenarios. Model is given large code snippets and asked to complete them with a few tokens - (e.g. a function name, a few code lines). -- `classification` - Simulates cases where the model is fed with large chunks of business data or document repeatedly and users - ask simple questions about the content (summarization, classification...). - Those use cases benefit a lot from prefix caching and chunked prefill. -- `fixed-length` - Model is sent fixed-length prompts to void the impact of variable-length tokenization on the benchmark. - This is a technical benchmark to evaluate the raw throughput of the model. - -#### Benchmark mode - -In default mode, tool runs a `sweep` benchmark. It first runs a throughput test to find the maximum throughput, then -sweeps on QPS values up to the maximum throughput. - -Available modes: - -- `sweep`: runs a sweep benchmark -- `rate`: runs a benchmark at a fixed request rate -- `throughput`: runs a benchmark at a fixed throughput (constant VUs) - -Example running a benchmark at a fixed request rates: - -```shell -inference-benchmarker \ - --tokenizer-name "meta-llama/Llama-3.1-8B-Instruct" \ - --max-vus 800 \ - --duration 120s \ - --url http://localhost:8080 \ - --warmup 30s \ - --benchmark-kind rate \ - --rates 1.0 \ - --rates 5.0 \ - --rates 10.0 \ - --prompt-options "num_tokens=200,max_tokens=220,min_tokens=180,variance=10" \ - --decode-options "num_tokens=200,max_tokens=220,min_tokens=180,variance=10" -``` - -#### Dataset configuration - -Prompts are sampled for a Hugging Face dataset file, using a [subset of ShareGPT -as default](https://huggingface.co/datasets/hlarcher/share_gpt_small). You can specify a different dataset file using -the -`--dataset` and `--dataset-file` option. - -Dataset is expected to be JSON with the following format: - -```json -[ - { - "conversations": [ - { - "role": "user", - "content": "rewrite that entire paragraph in the same style like this one: " - } - ] - } -] -``` - -To benchmark with prefix caching, you can use a system prompt that will be sent with each request from a discussion. - -```json -[ - { - "conversations": [ - { - "role": "system", - "content": "You are a helpful assistant that makes jokes at each response." - }, - { - "role": "user", - "content": "rewrite that entire paragraph in the same style like this one:" - } - ] - } -] -``` - -#### Prompt configuration - -For consistent results you can configure the token count and variance. The tool will sample prompts with the specified -values, sampling token counts from a normal distribution with the specified variance. - -```shell ---prompt-options "num_tokens=50,max_tokens=60,min_tokens=40,variance=10" -``` - -### Decode options - -You can also configure the decoding options for the model. The tool will sample decoding options with the specified -values, sampling token counts from a normal distribution with the specified variance. - -```shell ---decode-options "num_tokens=50,max_tokens=60,min_tokens=40,variance=10" -``` - -## Deploy on Kubernetes - -You can deploy the benchmarking tool on Kubernetes using the provided Helm chart. - -Review the values (especially model, HF token and resources), and install the chart: -```shell -$ helm install inference-benchmarker ./extra/k8s/inference-benchmarker -``` - -## Deploy on Slurm - -Slurm example is provided in `extra/slurm`. - -## Visualize the results - -You can use the provided Gradio app to quickly visualize the results. -Considering that JSON results files are in `/path/to/results/dir`: -```shell -$ poetry install -$ cd extra/dashboard -$ poetry run python app.py --from-results-dir /path/to/results/dir -``` - -![dashboard.png](assets/dashboard.png) - -## Development - -You need [Rust](https://rustup.rs/) installed to build the benchmarking tool. - -```shell -$ make build -``` - -## Frequently Asked Questions - -* **What's the difference between constant arrival rate and constant virtual user count?** - * **Constant virtual user count** means that the number of virtual users is fixed. Each virtual user can send a - single requests and waits for server response. It's basically simulating a fixed number of users querying the - server. - * **Constant arrival rate** means that the rate of requests is fixed and the number of virtual users is adjusted to - maintain that rate. Queries hit the server independently of responses performances. - - **Constant virtual user count** is a closed loop model where the server's response time dictates the number of - iterations. **Constant arrival rate** is an open-loop model more representative of real-life workloads. - - -* **Why do I get high error rate when running `throughput` benchmark?** - - Throughput bench tries to saturate the server with a high request rate. The error rate is high because the server is - not able to handle the request rate or rate limiting the requests. - In the case of TGI, this is controlled by the `--max-concurrent-requests` option. - - -* **What is the influence of CUDA graphs?** - - CUDA graphs are used to optimize the GPU usage by minimizing the overhead of launching kernels. This can lead to - better performance in some cases, but can also lead to worse performance in others. - If your CUDA graphs are not evenly distributed, you may see a performance drop at some request rates as batch size may - fall in a bigger CUDA graph batch size leading to a lost of compute due to excessive padding. - -* **I get less tokens generated than expected in a benchmark.** - - Inference servers use `max_tokens` parameter to limit the number of tokens generated. If the model - generates an end-of-sequence token before reaching `max_tokens`, the generation will stop. - There is currently no way to guarantee a fixed number of tokens generated without modifying the inference server. - So you may have `(successful requests) * max_tokens < generated tokens`. diff --git a/crates/pulsing-bench/build.rs b/crates/pulsing-bench/build.rs deleted file mode 100644 index c8b938eeb..000000000 --- a/crates/pulsing-bench/build.rs +++ /dev/null @@ -1,30 +0,0 @@ -use std::error::Error; -use vergen_gitcl::{Emitter, GitclBuilder}; - -fn main() -> Result<(), Box> { - // Try to get the git sha from the local git repository - match GitclBuilder::all_git() { - Ok(gitcl) => match Emitter::default().fail_on_error().add_instructions(&gitcl) { - Ok(emitter) => { - if emitter.emit().is_err() { - fallback_git_sha(); - } - } - Err(_) => { - fallback_git_sha(); - } - }, - Err(_) => { - fallback_git_sha(); - } - }; - Ok(()) -} - -fn fallback_git_sha() { - // Unable to get the git sha - if let Ok(sha) = std::env::var("GIT_SHA") { - // Set it from an env var - println!("cargo:rustc-env=VERGEN_GIT_SHA={sha}"); - } -} diff --git a/crates/pulsing-bench/src/actors/console_renderer.rs b/crates/pulsing-bench/src/actors/console_renderer.rs deleted file mode 100644 index 81efa9f08..000000000 --- a/crates/pulsing-bench/src/actors/console_renderer.rs +++ /dev/null @@ -1,607 +0,0 @@ -//! Console Renderer Actor - handles terminal display -//! -//! This actor is responsible for: -//! - Receiving display updates from MetricsAggregator -//! - Rendering benchmark progress to the terminal -//! - Displaying tables, progress bars, and log messages -//! -//! Separation from metrics collection allows: -//! - Easy replacement with other output formats (JSON, Web UI, etc.) -//! - Testing metrics logic without terminal dependencies -//! - Clean separation of concerns - -use super::messages::*; -use super::metrics_aggregator::{DisplayUpdate, FinalReport, PhaseDisplayData}; -use async_trait::async_trait; -use colored::Colorize; -use pulsing_actor::prelude::*; -use std::io::{self, Write}; -use tracing::info; - -/// Console Renderer Actor - pure display logic -pub struct ConsoleRendererActor { - /// Enable display - enabled: bool, - /// Last received config - config: Option, - /// Has printed header - header_printed: bool, -} - -impl ConsoleRendererActor { - pub fn new() -> Self { - Self { - enabled: true, - config: None, - header_printed: false, - } - } - - pub fn with_enabled(mut self, enabled: bool) -> Self { - self.enabled = enabled; - self - } - - fn handle_display_update(&mut self, update: DisplayUpdate) { - if !self.enabled { - return; - } - - // Store config if provided - if update.config.is_some() { - self.config = update.config.clone(); - } - - // Print header on first update with config - if !self.header_printed { - if let Some(ref config) = self.config { - self.print_header(config); - self.header_printed = true; - } - } - - // Render the display - self.render_progress(&update); - } - - fn print_header(&self, config: &BenchmarkConfig) { - println!("{}", "=".repeat(80).blue()); - println!("{}", "🚀 PULSING BENCHMARK (Actor Edition)".blue().bold()); - println!("{}", "=".repeat(80).blue()); - - println!( - "{}", - format!( - "Target: {} | Model: {} | Max VUs: {} | Duration: {}s | Warmup: {}s | Kind: {}", - config.url, - config.model_name, - config.max_vus, - config.duration_secs, - config.warmup_secs, - config.benchmark_kind - ) - .cyan() - .bold() - ); - - println!("{}", "=".repeat(80).blue()); - println!(); - } - - fn render_progress(&self, update: &DisplayUpdate) { - // Clear screen and move cursor to top - print!("\x1B[2J\x1B[1;1H"); - - // Re-print header if we have config - if let Some(ref config) = self.config { - self.print_header(config); - } - - // Print benchmark progress header - println!("{}", "BENCHMARK PROGRESS".blue().bold()); - println!("{}", "-".repeat(120).blue()); - - // Print table header - println!( - "{:<20} {:<10} {:>6} {:>6} {:>12} {:>18} {:>18} {:>10} {:>10} {:>12}", - "Bench".blue().bold(), - "Status".blue().bold(), - "%".blue().bold(), - "Err%".blue().bold(), - "Throughput".blue().bold(), - "TTFT".blue().bold(), - "TPOT".blue().bold(), - "In tok/s".blue().bold(), - "Out tok/s".blue().bold(), - "Total tok/s".blue().bold() - ); - println!("{}", "-".repeat(120).blue()); - - // Print completed phases - for phase in &update.completed_phases { - self.print_phase_row(phase); - } - - // Print current phase - if let Some(ref phase) = update.current_phase { - self.print_phase_row(phase); - - // Progress bar for running phase - if phase.progress_pct < 100.0 { - println!( - " {} {}", - "Progress:".dimmed(), - create_progress_bar(phase.progress_pct) - ); - } - } - - println!(); - - // Print recent messages - if !update.messages.is_empty() { - println!("{}", "RECENT MESSAGES".blue().bold()); - println!("{}", "-".repeat(80).blue()); - - for message in update.messages.iter().rev().take(5) { - let level_str = match message.level.as_str() { - "INFO" => "INFO".green(), - "WARN" | "WARNING" => "WARN".yellow(), - "ERROR" => "ERROR".red(), - _ => message.level.normal(), - }; - println!( - "{} {} {}", - message.timestamp.bright_black(), - level_str, - message.message.white() - ); - } - println!(); - } - - io::stdout().flush().unwrap(); - } - - fn print_phase_row(&self, phase: &PhaseDisplayData) { - let status = if phase.is_completed { - "Completed".green().bold() - } else { - "Running".yellow().bold() - }; - - let error_str = if phase.error_rate > 0.0 { - format!("{:.1}%", phase.error_rate).red().bold() - } else { - "0%".green().normal() - }; - - let ttft_display = match (phase.avg_ttft_ms, phase.ttft_std_ms) { - (Some(mean), Some(std)) => format!("{:.1}±{:.1}ms", mean, std), - (Some(mean), None) => format!("{:.1}ms", mean), - _ => "N/A".to_string(), - }; - - let tpot_display = match (phase.avg_tpot_ms, phase.tpot_std_ms) { - (Some(mean), Some(std)) => format!("{:.2}±{:.2}ms", mean, std), - (Some(mean), None) => format!("{:.2}ms", mean), - _ => "N/A".to_string(), - }; - - let input_tput = phase - .input_throughput - .map_or("N/A".to_string(), |t| format!("{:.1}", t)); - let output_tput = phase - .output_throughput - .map_or("N/A".to_string(), |t| format!("{:.1}", t)); - let total_tput = phase - .total_throughput - .map_or("N/A".to_string(), |t| format!("{:.1}", t)); - - println!( - "{:<20} {:<10} {:>5.0}% {:>6} {:>10.2} r/s {:>18} {:>18} {:>10} {:>10} {:>12}", - truncate(&phase.phase_name, 20).white(), - status, - phase.progress_pct, - error_str, - phase.request_rate, - ttft_display.cyan(), - tpot_display.magenta(), - input_tput.blue(), - output_tput.yellow(), - total_tput.green() - ); - } - - fn handle_final_report(&self, final_report: FinalReport) { - if !self.enabled { - return; - } - - let report = &final_report.report; - - println!(); - println!( - "{}", - "╔══════════════════════════════════════════════════════════════════════════════╗" - .bright_green() - .bold() - ); - println!( - "{}", - "║ BENCHMARK COMPLETE ║" - .bright_green() - .bold() - ); - println!( - "{}", - "╚══════════════════════════════════════════════════════════════════════════════╝" - .bright_green() - .bold() - ); - println!(); - - // Print results table - println!( - "{:<20} {:>12} {:>14} {:>14} {:>14} {:>12} {:>10}", - "Phase".bold(), - "QPS".bold(), - "E2E Latency".bold(), - "TTFT (avg)".bold(), - "TPOT (avg)".bold(), - "Throughput".bold(), - "Error %".bold() - ); - println!("{}", "─".repeat(100)); - - for phase in &report.phases { - let metrics = &phase.metrics; - let e2e = metrics - .avg_latency_ms - .map_or("N/A".to_string(), |v| format!("{:.0}ms", v)); - let ttft = metrics - .avg_ttft_ms - .map_or("N/A".to_string(), |v| format!("{:.1}ms", v)); - let tpot = metrics - .avg_tpot_ms - .map_or("N/A".to_string(), |v| format!("{:.2}ms", v)); - let throughput = metrics - .total_throughput - .map_or("N/A".to_string(), |v| format!("{:.0} t/s", v)); - - let total = metrics.successful_requests + metrics.failed_requests; - let error_pct = if total > 0 { - metrics.failed_requests as f64 / total as f64 * 100.0 - } else { - 0.0 - }; - - println!( - "{:<20} {:>10.2}/s {:>14} {:>14} {:>14} {:>12} {:>9.1}%", - truncate(&phase.phase_name, 20), - metrics.request_rate, - e2e, - ttft, - tpot, - throughput, - error_pct - ); - } - - println!("{}", "─".repeat(100)); - - let total_requests: u64 = report - .phases - .iter() - .map(|p| p.metrics.successful_requests) - .sum(); - println!( - "{}", - format!( - "Total duration: {:.1}s | Total requests: {}", - report.total_duration_secs, total_requests - ) - .dimmed() - ); - println!(); - - io::stdout().flush().unwrap(); - } -} - -impl Default for ConsoleRendererActor { - fn default() -> Self { - Self::new() - } -} - -/// Helper function to truncate strings -fn truncate(s: &str, max_len: usize) -> String { - if s.len() > max_len { - format!("{}...", &s[..max_len - 3]) - } else { - s.to_string() - } -} - -/// Helper function to create a progress bar -fn create_progress_bar(progress: f64) -> String { - let width = 30; - let filled = (progress / 100.0 * width as f64) as usize; - let empty = width - filled; - - let filled_bar = "█".repeat(filled); - let empty_bar = "░".repeat(empty); - - format!( - "[{}{}] {:>5.1}%", - filled_bar.green(), - empty_bar.dimmed(), - progress - ) -} - -#[async_trait] -impl Actor for ConsoleRendererActor { - async fn on_start(&mut self, ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - info!("ConsoleRenderer started with actor_id {:?}", ctx.id()); - Ok(()) - } - - async fn on_stop(&mut self, _ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - info!("ConsoleRenderer stopped"); - Ok(()) - } - - async fn receive( - &mut self, - msg: Message, - _ctx: &mut ActorContext, - ) -> pulsing_actor::error::Result { - let msg_type = msg.msg_type(); - - if msg_type.ends_with("DisplayUpdate") { - let update: DisplayUpdate = msg.unpack()?; - self.handle_display_update(update); - return Message::pack(&AckMessage::ok()); - } - - if msg_type.ends_with("FinalReport") { - let report: FinalReport = msg.unpack()?; - self.handle_final_report(report); - return Message::pack(&AckMessage::ok()); - } - - // Ignore unknown messages silently - renderer is fire-and-forget - Message::pack(&AckMessage::ok()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::actors::metrics_aggregator::DisplayMessage; - - #[test] - fn test_truncate() { - assert_eq!(truncate("hello", 10), "hello"); - assert_eq!(truncate("hello world", 8), "hello..."); - } - - #[test] - fn test_progress_bar() { - let bar = create_progress_bar(50.0); - assert!(bar.contains("50.0%")); - } - - #[test] - fn test_renderer_creation() { - let renderer = ConsoleRendererActor::new(); - assert!(renderer.enabled); - assert!(!renderer.header_printed); - } - - #[test] - fn test_truncate_exact_length() { - assert_eq!(truncate("hello", 5), "hello"); - } - - #[test] - fn test_truncate_empty() { - assert_eq!(truncate("", 10), ""); - } - - #[test] - fn test_truncate_short_max() { - // When max_len is very short, we still try to truncate - assert_eq!(truncate("hello world", 8), "hello..."); - } - - #[test] - fn test_progress_bar_zero() { - let bar = create_progress_bar(0.0); - assert!(bar.contains("0.0%")); - // Should have all empty blocks - assert!(bar.contains("░")); - } - - #[test] - fn test_progress_bar_full() { - let bar = create_progress_bar(100.0); - assert!(bar.contains("100.0%")); - // Should have all filled blocks - assert!(bar.contains("█")); - } - - #[test] - fn test_progress_bar_partial() { - let bar = create_progress_bar(75.0); - assert!(bar.contains("75.0%")); - // Should have both filled and empty blocks - assert!(bar.contains("█")); - assert!(bar.contains("░")); - } - - #[test] - fn test_renderer_default() { - let renderer = ConsoleRendererActor::default(); - assert!(renderer.enabled); - assert!(!renderer.header_printed); - assert!(renderer.config.is_none()); - } - - #[test] - fn test_renderer_with_enabled() { - let renderer = ConsoleRendererActor::new().with_enabled(false); - assert!(!renderer.enabled); - } - - #[test] - fn test_renderer_disabled_display_update() { - let mut renderer = ConsoleRendererActor::new().with_enabled(false); - let update = DisplayUpdate { - config: Some(BenchmarkConfig::default()), - completed_phases: vec![], - current_phase: None, - messages: vec![], - }; - - // Should not panic even when disabled - renderer.handle_display_update(update); - // Config should not be stored when disabled - assert!(renderer.config.is_none()); - } - - #[test] - fn test_renderer_disabled_final_report() { - let renderer = ConsoleRendererActor::new().with_enabled(false); - let report = BenchmarkReport { - run_id: "test".to_string(), - config: BenchmarkConfig::default(), - phases: vec![], - start_time: "".to_string(), - end_time: "".to_string(), - total_duration_secs: 60.0, - }; - - // Should not panic when disabled - renderer.handle_final_report(FinalReport { report }); - } - - #[test] - fn test_phase_display_data_formatting() { - let phase = PhaseDisplayData { - phase_id: "phase-1".to_string(), - phase_name: "Test Phase".to_string(), - is_completed: true, - progress_pct: 100.0, - error_rate: 5.0, - request_rate: 50.0, - avg_ttft_ms: Some(100.0), - ttft_std_ms: Some(10.0), - avg_tpot_ms: Some(8.0), - tpot_std_ms: Some(1.5), - input_throughput: Some(500.0), - output_throughput: Some(1000.0), - total_throughput: Some(1500.0), - }; - - assert!(phase.is_completed); - assert_eq!(phase.progress_pct, 100.0); - assert_eq!(phase.error_rate, 5.0); - } - - #[test] - fn test_phase_display_data_none_values() { - let phase = PhaseDisplayData { - phase_id: "phase-1".to_string(), - phase_name: "Test Phase".to_string(), - is_completed: false, - progress_pct: 50.0, - error_rate: 0.0, - request_rate: 25.0, - avg_ttft_ms: None, - ttft_std_ms: None, - avg_tpot_ms: None, - tpot_std_ms: None, - input_throughput: None, - output_throughput: None, - total_throughput: None, - }; - - assert!(!phase.is_completed); - assert!(phase.avg_ttft_ms.is_none()); - assert!(phase.total_throughput.is_none()); - } - - #[test] - fn test_display_update_with_config() { - let mut renderer = ConsoleRendererActor::new(); - let config = BenchmarkConfig::default(); - let update = DisplayUpdate { - config: Some(config.clone()), - completed_phases: vec![], - current_phase: None, - messages: vec![], - }; - - renderer.handle_display_update(update); - - // Config should be stored - assert!(renderer.config.is_some()); - assert_eq!(renderer.config.as_ref().unwrap().url, config.url); - } - - #[test] - fn test_display_update_preserves_config() { - let mut renderer = ConsoleRendererActor::new(); - - // First update with config - let config = BenchmarkConfig { - url: "http://test.com".to_string(), - ..Default::default() - }; - renderer.handle_display_update(DisplayUpdate { - config: Some(config), - completed_phases: vec![], - current_phase: None, - messages: vec![], - }); - - // Second update without config - renderer.handle_display_update(DisplayUpdate { - config: None, - completed_phases: vec![], - current_phase: None, - messages: vec![], - }); - - // Config should still be preserved - assert!(renderer.config.is_some()); - assert_eq!(renderer.config.as_ref().unwrap().url, "http://test.com"); - } - - #[test] - fn test_display_message_levels() { - let info_msg = DisplayMessage { - message: "Info message".to_string(), - timestamp: "12:00:00".to_string(), - level: "INFO".to_string(), - }; - assert_eq!(info_msg.level, "INFO"); - - let warn_msg = DisplayMessage { - message: "Warning message".to_string(), - timestamp: "12:00:01".to_string(), - level: "WARN".to_string(), - }; - assert_eq!(warn_msg.level, "WARN"); - - let error_msg = DisplayMessage { - message: "Error message".to_string(), - timestamp: "12:00:02".to_string(), - level: "ERROR".to_string(), - }; - assert_eq!(error_msg.level, "ERROR"); - } -} diff --git a/crates/pulsing-bench/src/actors/coordinator.rs b/crates/pulsing-bench/src/actors/coordinator.rs deleted file mode 100644 index 6e4a99a78..000000000 --- a/crates/pulsing-bench/src/actors/coordinator.rs +++ /dev/null @@ -1,546 +0,0 @@ -//! Coordinator Actor - orchestrates the benchmark lifecycle -//! -//! This actor is responsible for: -//! - Managing actor lifecycle (spawn/stop workers, scheduler, metrics, renderer) -//! - Orchestrating benchmark phases -//! - Handling start/stop commands -//! -//! Refactored to use unified phase execution logic. - -use super::messages::*; -use super::scheduler::{RequestGenerator, SimpleRequestGenerator, TokenizedRequestGenerator}; -use super::{ConsoleRendererActor, MetricsAggregatorActor, SchedulerActor, WorkerActor}; -use crate::tokenizer::TokenCounter; -use async_trait::async_trait; -use pulsing_actor::error::{PulsingError, RuntimeError}; -use pulsing_actor::prelude::*; -use std::sync::Arc; -use std::time::Duration; -use tracing::info; - -/// Coordinator state -#[derive(Debug, Clone, PartialEq)] -enum CoordinatorState { - Idle, - Running(String), // run_id - Stopping, -} - -/// Phase definition - describes how to run a benchmark phase -#[derive(Debug, Clone)] -struct PhaseDefinition { - phase_id: String, - phase_name: String, - scheduler_type: SchedulerType, - max_vus: u64, - duration_secs: u64, - rate: Option, -} - -/// Coordinator Actor - manages the entire benchmark lifecycle -pub struct CoordinatorActor { - /// Actor system reference - system: Option>, - /// Current state - state: CoordinatorState, - /// Current phase - phase: Option, - /// Current configuration - config: Option, - /// Worker references - workers: Vec, - /// Scheduler reference - scheduler_ref: Option, - /// Metrics aggregator reference - metrics_ref: Option, - /// Console renderer reference - renderer_ref: Option, - /// Number of workers to spawn - num_workers: u32, - /// Request generator - request_gen: Arc, - /// Token counter for accurate token counting - token_counter: Option, - /// Enable console display - display_enabled: bool, - /// Cached final report (saved before cleanup) - final_report: Option, -} - -impl CoordinatorActor { - pub fn new() -> Self { - Self { - system: None, - state: CoordinatorState::Idle, - phase: None, - config: None, - workers: Vec::new(), - scheduler_ref: None, - metrics_ref: None, - renderer_ref: None, - num_workers: 4, - request_gen: Arc::new(SimpleRequestGenerator::default_prompts()), - token_counter: None, - display_enabled: true, - final_report: None, - } - } - - pub fn with_system(mut self, system: Arc) -> Self { - self.system = Some(system); - self - } - - pub fn with_num_workers(mut self, num: u32) -> Self { - self.num_workers = num; - self - } - - pub fn with_request_generator(mut self, gen: Arc) -> Self { - self.request_gen = gen; - self - } - - pub fn with_token_counter(mut self, tc: TokenCounter) -> Self { - self.token_counter = Some(tc); - self - } - - pub fn with_display(mut self, enabled: bool) -> Self { - self.display_enabled = enabled; - self - } - - /// Start a new benchmark run - async fn start_benchmark(&mut self, start: StartBenchmark) -> anyhow::Result { - if self.state != CoordinatorState::Idle { - return Ok(AckMessage::error("Benchmark already running")); - } - - let system = self - .system - .as_ref() - .ok_or_else(|| anyhow::anyhow!("ActorSystem not configured"))?; - - info!("Starting benchmark run: {}", start.run_id); - self.config = Some(start.config.clone()); - self.state = CoordinatorState::Running(start.run_id.clone()); - self.phase = Some(BenchmarkPhase::Initializing); - - // Spawn Console Renderer first (if enabled) - if self.display_enabled { - let renderer = ConsoleRendererActor::new(); - let renderer_ref = system - .spawn_named(format!("renderer-{}", start.run_id), renderer) - .await?; - self.renderer_ref = Some(renderer_ref); - } - - // Spawn Metrics Aggregator - let mut metrics = MetricsAggregatorActor::new(); - if let Some(ref renderer) = self.renderer_ref { - metrics = metrics.with_renderer(renderer.clone()); - } - let metrics_ref = system - .spawn_named(format!("metrics-{}", start.run_id), metrics) - .await?; - self.metrics_ref = Some(metrics_ref.clone()); - - // Register run with metrics - let register = RegisterRun { - run_id: start.run_id.clone(), - config: start.config.clone(), - }; - metrics_ref.tell(register).await?; - - // Spawn Workers - self.workers.clear(); - for i in 0..self.num_workers { - let worker = - WorkerActor::new(format!("worker-{}", i)).with_metrics(metrics_ref.clone()); - let worker_ref = system - .spawn_named(format!("worker-{}-{}", start.run_id, i), worker) - .await?; - self.workers.push(worker_ref); - } - - // Spawn Scheduler with appropriate request generator - let request_gen: Arc = if let Some(ref tc) = self.token_counter { - Arc::new(TokenizedRequestGenerator::new(tc.clone())) - } else { - self.request_gen.clone() - }; - - let scheduler = SchedulerActor::new() - .with_workers(self.workers.clone()) - .with_metrics(metrics_ref.clone()) - .with_request_generator(request_gen) - .with_target( - start.config.url.clone(), - start.config.api_key.clone(), - start.config.model_name.clone(), - ); - let scheduler_ref = system - .spawn_named(format!("scheduler-{}", start.run_id), scheduler) - .await?; - self.scheduler_ref = Some(scheduler_ref); - - info!( - "Initialized {} workers, scheduler, metrics for run {}", - self.num_workers, start.run_id - ); - - // Run benchmark phases - let result = self.run_benchmark_phases(&start).await; - - // Get and cache final report before cleanup - if let Some(ref metrics) = self.metrics_ref { - let get_report = GetReport { - run_id: start.run_id.clone(), - }; - if let Ok(report) = metrics.ask::<_, BenchmarkReport>(get_report).await { - self.final_report = Some(report); - } - } - - // Cleanup - self.cleanup(&start.run_id).await; - - match result { - Ok(()) => { - self.phase = Some(BenchmarkPhase::Completed); - Ok(AckMessage::ok()) - } - Err(e) => { - self.phase = Some(BenchmarkPhase::Failed(e.to_string())); - Ok(AckMessage::error(e.to_string())) - } - } - } - - async fn run_benchmark_phases(&mut self, start: &StartBenchmark) -> anyhow::Result<()> { - let config = &start.config; - - // Phase 1: Warmup - self.phase = Some(BenchmarkPhase::Warmup); - info!("Starting warmup phase"); - - let warmup = PhaseDefinition { - phase_id: "warmup".to_string(), - phase_name: "Warmup".to_string(), - scheduler_type: SchedulerType::ConstantVUs, - max_vus: 1, - duration_secs: config.warmup_secs, - rate: None, - }; - self.run_phase(&start.run_id, &warmup).await?; - - // Phase 2: Main benchmark - self.phase = Some(BenchmarkPhase::Running); - info!("Starting main benchmark phase"); - - let phases = self.generate_phases(config); - for phase_def in phases { - self.run_phase(&start.run_id, &phase_def).await?; - } - - // Phase 3: Cooldown - self.phase = Some(BenchmarkPhase::Cooldown); - info!("Cooldown phase"); - tokio::time::sleep(Duration::from_secs(2)).await; - - Ok(()) - } - - /// Generate phase definitions based on benchmark kind - fn generate_phases(&self, config: &BenchmarkConfig) -> Vec { - match config.benchmark_kind.as_str() { - "throughput" => vec![PhaseDefinition { - phase_id: "throughput".to_string(), - phase_name: "Max Throughput".to_string(), - scheduler_type: SchedulerType::ConstantVUs, - max_vus: config.max_vus, - duration_secs: config.duration_secs, - rate: None, - }], - - "sweep" => { - // Sweep needs to first discover max rate, then run rate tests - // For simplicity, use num_rates evenly distributed - let mut phases = vec![ - // First: throughput discovery - PhaseDefinition { - phase_id: "throughput-discovery".to_string(), - phase_name: "Throughput Discovery".to_string(), - scheduler_type: SchedulerType::ConstantVUs, - max_vus: config.max_vus, - duration_secs: config.duration_secs, - rate: None, - }, - ]; - - // Rate sweep phases (will be dynamically adjusted) - for i in 1..=config.num_rates { - let rate_ratio = i as f64 / config.num_rates as f64; - phases.push(PhaseDefinition { - phase_id: format!("rate-{}", i), - phase_name: format!("Rate Sweep {}/{}", i, config.num_rates), - scheduler_type: SchedulerType::ConstantArrivalRate, - max_vus: config.max_vus, - duration_secs: config.duration_secs, - rate: Some(rate_ratio * 100.0), // Placeholder, will be adjusted - }); - } - phases - } - - "rate" => config - .rates - .clone() - .unwrap_or_default() - .into_iter() - .map(|rate| PhaseDefinition { - phase_id: format!("rate@{:.1}reqs", rate), - phase_name: format!("Rate {:.1} req/s", rate), - scheduler_type: SchedulerType::ConstantArrivalRate, - max_vus: config.max_vus, - duration_secs: config.duration_secs, - rate: Some(rate), - }) - .collect(), - - "csweep" => { - let levels = self.generate_concurrency_levels(config.max_vus); - levels - .into_iter() - .map(|vus| PhaseDefinition { - phase_id: format!("concurrency#{}vus", vus), - phase_name: format!("Concurrency {} VUs", vus), - scheduler_type: SchedulerType::ConstantVUs, - max_vus: vus, - duration_secs: config.duration_secs, - rate: None, - }) - .collect() - } - - _ => vec![PhaseDefinition { - phase_id: "unknown".to_string(), - phase_name: "Unknown".to_string(), - scheduler_type: SchedulerType::ConstantVUs, - max_vus: config.max_vus, - duration_secs: config.duration_secs, - rate: None, - }], - } - } - - /// Generate concurrency levels for sweep - fn generate_concurrency_levels(&self, max_vus: u64) -> Vec { - let mut levels = vec![1u64]; - let mut level = 2; - while level <= max_vus { - levels.push(level); - if level < 10 { - level += 1; - } else if level < 50 { - level += 5; - } else if level < 100 { - level += 10; - } else { - level += 20; - } - } - if !levels.contains(&max_vus) { - levels.push(max_vus); - } - levels - } - - /// Unified phase execution - reduces code duplication - async fn run_phase(&self, run_id: &str, phase: &PhaseDefinition) -> anyhow::Result<()> { - let scheduler_ref = self - .scheduler_ref - .as_ref() - .ok_or_else(|| anyhow::anyhow!("Scheduler not initialized"))?; - let metrics_ref = self - .metrics_ref - .as_ref() - .ok_or_else(|| anyhow::anyhow!("Metrics not initialized"))?; - - info!("Running phase: {}", phase.phase_name); - - // Step 1: Configure scheduler - let config_msg = ConfigureScheduler { - scheduler_type: phase.scheduler_type.clone(), - max_vus: phase.max_vus, - duration_secs: phase.duration_secs, - rate: phase.rate, - }; - scheduler_ref.tell(config_msg).await?; - - // Step 2: Notify metrics of phase start - let start_phase = StartPhase { - run_id: run_id.to_string(), - phase_id: phase.phase_id.clone(), - phase_name: phase.phase_name.clone(), - scheduler_type: phase.scheduler_type.clone(), - target_rate: phase.rate, - }; - metrics_ref.tell(start_phase).await?; - - // Step 3: Start scheduling and wait for completion - let start_msg = StartScheduling { - phase_id: phase.phase_id.clone(), - }; - scheduler_ref.ask::<_, AckMessage>(start_msg).await?; - - // Step 4: Notify metrics of phase end - let end_phase = EndPhase { - run_id: run_id.to_string(), - phase_id: phase.phase_id.clone(), - }; - metrics_ref.tell(end_phase).await?; - - info!("Phase {} completed", phase.phase_name); - Ok(()) - } - - async fn cleanup(&mut self, run_id: &str) { - let system = match &self.system { - Some(s) => s, - None => return, - }; - - info!("Cleaning up actors for run {}", run_id); - - // Stop scheduler - if self.scheduler_ref.is_some() { - let _ = system.stop(format!("scheduler-{}", run_id)).await; - } - - // Stop workers - for i in 0..self.num_workers { - let _ = system.stop(format!("worker-{}-{}", run_id, i)).await; - } - - // Stop metrics (this will trigger final report to renderer) - if self.metrics_ref.is_some() { - let _ = system.stop(format!("metrics-{}", run_id)).await; - } - - // Stop renderer - if self.renderer_ref.is_some() { - // Give renderer time to process final report - tokio::time::sleep(Duration::from_millis(100)).await; - let _ = system.stop(format!("renderer-{}", run_id)).await; - } - - self.scheduler_ref = None; - self.metrics_ref = None; - self.renderer_ref = None; - self.workers.clear(); - self.state = CoordinatorState::Idle; - } - - async fn stop_benchmark(&mut self, stop: StopBenchmark) -> AckMessage { - if let CoordinatorState::Running(ref run_id) = self.state { - if *run_id != stop.run_id { - return AckMessage::error("Run ID mismatch"); - } - - info!("Stopping benchmark: {}", stop.reason); - self.state = CoordinatorState::Stopping; - - // Signal scheduler to stop - if let Some(ref scheduler) = self.scheduler_ref { - let _ = scheduler.tell(PauseScheduling).await; - } - - self.cleanup(&stop.run_id).await; - AckMessage::ok() - } else { - AckMessage::error("No benchmark running") - } - } - - fn get_status(&self) -> CoordinatorStatus { - let (run_id, phase) = match &self.state { - CoordinatorState::Running(id) => (Some(id.clone()), self.phase.clone()), - _ => (None, None), - }; - - CoordinatorStatus { - run_id, - phase, - workers: self.workers.len() as u32, - active_requests: 0, // Could aggregate from metrics - } - } -} - -impl Default for CoordinatorActor { - fn default() -> Self { - Self::new() - } -} - -#[async_trait] -impl Actor for CoordinatorActor { - async fn on_start(&mut self, ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - info!("Coordinator started with actor_id {:?}", ctx.id()); - Ok(()) - } - - async fn on_stop(&mut self, _ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - info!("Coordinator stopped"); - Ok(()) - } - - async fn receive( - &mut self, - msg: Message, - _ctx: &mut ActorContext, - ) -> pulsing_actor::error::Result { - let msg_type = msg.msg_type(); - - if msg_type.ends_with("StartBenchmark") { - let start: StartBenchmark = msg.unpack()?; - let result = self - .start_benchmark(start) - .await - .map_err(|e| PulsingError::from(RuntimeError::Other(e.to_string())))?; - return Message::pack(&result); - } - - if msg_type.ends_with("StopBenchmark") { - let stop: StopBenchmark = msg.unpack()?; - let result = self.stop_benchmark(stop).await; - return Message::pack(&result); - } - - if msg_type.ends_with("CoordinatorStatus") || msg_type.ends_with("GetStatus") { - return Message::pack(&self.get_status()); - } - - if msg_type.ends_with("GetReport") { - // Try to get from metrics actor first - if let Some(ref metrics) = self.metrics_ref { - let report: GetReport = msg.unpack()?; - return metrics.send(Message::pack(&report)?).await; - } - // Fall back to cached report - if let Some(ref report) = self.final_report { - return Message::pack(report); - } - return Err(PulsingError::from(RuntimeError::Other( - "No report available".into(), - ))); - } - - Err(PulsingError::from(RuntimeError::Other(format!( - "Unknown message type: {}", - msg_type - )))) - } -} diff --git a/crates/pulsing-bench/src/actors/messages.rs b/crates/pulsing-bench/src/actors/messages.rs deleted file mode 100644 index 6c0c2b420..000000000 --- a/crates/pulsing-bench/src/actors/messages.rs +++ /dev/null @@ -1,566 +0,0 @@ -//! Message definitions for the benchmark actor system - -use serde::{Deserialize, Serialize}; - -// ============================================================================ -// Configuration Messages -// ============================================================================ - -/// Benchmark configuration -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct BenchmarkConfig { - /// Target URL - pub url: String, - /// API key for authentication - pub api_key: String, - /// Model name - pub model_name: String, - /// Tokenizer name (HuggingFace model name) - pub tokenizer_name: Option, - /// Maximum virtual users (concurrent requests) - pub max_vus: u64, - /// Test duration in seconds - pub duration_secs: u64, - /// Target request rate (requests per second), None for max throughput - pub rate: Option, - /// Warmup duration in seconds - pub warmup_secs: u64, - /// Benchmark kind: "throughput", "sweep", "rate", "csweep" - pub benchmark_kind: String, - /// Number of rate steps for sweep - pub num_rates: u64, - /// Specific rates for rate benchmark - pub rates: Option>, -} - -impl Default for BenchmarkConfig { - fn default() -> Self { - Self { - url: "http://localhost:8000".to_string(), - api_key: String::new(), - model_name: "gpt2".to_string(), - tokenizer_name: None, - max_vus: 128, - duration_secs: 120, - rate: None, - warmup_secs: 30, - benchmark_kind: "throughput".to_string(), - num_rates: 10, - rates: None, - } - } -} - -/// Request template for generating requests -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RequestTemplate { - /// Request ID - pub id: String, - /// Prompt text - pub prompt: String, - /// Number of prompt tokens - pub num_prompt_tokens: u64, - /// Target decode tokens (optional) - pub num_decode_tokens: Option, -} - -// ============================================================================ -// Coordinator Messages -// ============================================================================ - -/// Start a benchmark run -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct StartBenchmark { - pub config: BenchmarkConfig, - pub run_id: String, -} - -/// Stop the current benchmark -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct StopBenchmark { - pub run_id: String, - pub reason: String, -} - -/// Benchmark phase transition -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PhaseTransition { - pub run_id: String, - pub phase: BenchmarkPhase, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub enum BenchmarkPhase { - Initializing, - Warmup, - Running, - Cooldown, - Completed, - Failed(String), -} - -/// Coordinator status response -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CoordinatorStatus { - pub run_id: Option, - pub phase: Option, - pub workers: u32, - pub active_requests: u64, -} - -// ============================================================================ -// Scheduler Messages -// ============================================================================ - -/// Configure the scheduler -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ConfigureScheduler { - pub scheduler_type: SchedulerType, - pub max_vus: u64, - pub duration_secs: u64, - pub rate: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] -pub enum SchedulerType { - /// Constant number of virtual users - #[default] - ConstantVUs, - /// Constant arrival rate - ConstantArrivalRate, -} - -/// Start scheduling requests -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct StartScheduling { - pub phase_id: String, -} - -/// Pause scheduling -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PauseScheduling; - -/// Resume scheduling -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ResumeScheduling; - -/// Scheduler progress update (sent to Coordinator) -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SchedulerProgress { - pub phase_id: String, - pub progress_pct: f64, - pub sent_requests: u64, - pub active_vus: u64, - pub elapsed_secs: f64, -} - -// ============================================================================ -// Worker Messages -// ============================================================================ - -/// Send a request (from Scheduler to Worker) -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SendRequest { - pub request_id: String, - pub template: RequestTemplate, - pub target_url: String, - pub api_key: String, - pub model_name: String, -} - -/// Request completed (from Worker to Collector) -#[derive(Debug, Clone, Serialize, Deserialize, Default)] -pub struct RequestCompleted { - pub request_id: String, - pub success: bool, - pub error: Option, - /// Time to first token in milliseconds - pub ttft_ms: Option, - /// Total latency in milliseconds - pub latency_ms: f64, - /// Number of generated tokens - pub generated_tokens: u64, - /// Number of prompt tokens - pub prompt_tokens: u64, - /// Time per output token in milliseconds - pub tpot_ms: Option, - /// Token timestamps for detailed analysis - pub token_times_ms: Vec, -} - -/// Worker ready notification -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct WorkerReady { - pub worker_id: String, -} - -/// Worker status -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct WorkerStatus { - pub worker_id: String, - pub active_requests: u32, - pub completed_requests: u64, - pub failed_requests: u64, -} - -// ============================================================================ -// Collector Messages -// ============================================================================ - -/// Register a new run -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RegisterRun { - pub run_id: String, - pub config: BenchmarkConfig, -} - -/// Start a new phase -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct StartPhase { - pub run_id: String, - pub phase_id: String, - pub phase_name: String, - pub scheduler_type: SchedulerType, - pub target_rate: Option, -} - -/// End current phase -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EndPhase { - pub run_id: String, - pub phase_id: String, -} - -/// Get current metrics -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct GetMetrics { - pub run_id: String, -} - -/// Get final report -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct GetReport { - pub run_id: String, -} - -/// Real-time metrics snapshot -#[derive(Debug, Clone, Serialize, Deserialize, Default)] -pub struct MetricsSnapshot { - pub phase_id: String, - pub phase_name: String, - pub progress_pct: f64, - pub elapsed_secs: f64, - pub successful_requests: u64, - pub failed_requests: u64, - pub request_rate: f64, - pub avg_ttft_ms: Option, - pub avg_tpot_ms: Option, - pub ttft_std_ms: Option, - pub tpot_std_ms: Option, - pub avg_latency_ms: Option, - pub p50_latency_ms: Option, - pub p95_latency_ms: Option, - pub p99_latency_ms: Option, - pub input_throughput: Option, - pub output_throughput: Option, - pub total_throughput: Option, -} - -/// Final benchmark report -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct BenchmarkReport { - pub run_id: String, - pub config: BenchmarkConfig, - pub phases: Vec, - pub start_time: String, - pub end_time: String, - pub total_duration_secs: f64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PhaseReport { - pub phase_id: String, - pub phase_name: String, - pub duration_secs: f64, - pub metrics: MetricsSnapshot, -} - -// ============================================================================ -// Common Response Messages -// ============================================================================ - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct AckMessage { - pub success: bool, - pub message: String, -} - -impl AckMessage { - pub fn ok() -> Self { - Self { - success: true, - message: "OK".to_string(), - } - } - - pub fn error(msg: impl Into) -> Self { - Self { - success: false, - message: msg.into(), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_benchmark_config_default() { - let config = BenchmarkConfig::default(); - assert_eq!(config.url, "http://localhost:8000"); - assert_eq!(config.model_name, "gpt2"); - assert_eq!(config.max_vus, 128); - assert_eq!(config.duration_secs, 120); - assert_eq!(config.warmup_secs, 30); - assert!(config.rate.is_none()); - assert_eq!(config.benchmark_kind, "throughput"); - } - - #[test] - fn test_benchmark_config_serialization() { - let config = BenchmarkConfig { - url: "http://test.com".to_string(), - api_key: "key".to_string(), - model_name: "model".to_string(), - tokenizer_name: Some("tokenizer".to_string()), - max_vus: 10, - duration_secs: 60, - rate: Some(5.0), - warmup_secs: 10, - benchmark_kind: "rate".to_string(), - num_rates: 5, - rates: Some(vec![1.0, 2.0]), - }; - - let json = serde_json::to_string(&config).unwrap(); - let deserialized: BenchmarkConfig = serde_json::from_str(&json).unwrap(); - assert_eq!(deserialized.url, config.url); - assert_eq!(deserialized.rate, Some(5.0)); - assert_eq!(deserialized.rates, Some(vec![1.0, 2.0])); - } - - #[test] - fn test_request_template() { - let template = RequestTemplate { - id: "req-1".to_string(), - prompt: "Hello world".to_string(), - num_prompt_tokens: 2, - num_decode_tokens: Some(100), - }; - - assert_eq!(template.id, "req-1"); - assert_eq!(template.num_prompt_tokens, 2); - assert_eq!(template.num_decode_tokens, Some(100)); - } - - #[test] - fn test_ack_message_ok() { - let ack = AckMessage::ok(); - assert!(ack.success); - assert_eq!(ack.message, "OK"); - } - - #[test] - fn test_ack_message_error() { - let ack = AckMessage::error("Something went wrong"); - assert!(!ack.success); - assert_eq!(ack.message, "Something went wrong"); - } - - #[test] - fn test_ack_message_error_string() { - let error_msg = String::from("Error from string"); - let ack = AckMessage::error(error_msg); - assert!(!ack.success); - assert_eq!(ack.message, "Error from string"); - } - - #[test] - fn test_benchmark_phase_equality() { - assert_eq!(BenchmarkPhase::Initializing, BenchmarkPhase::Initializing); - assert_eq!(BenchmarkPhase::Warmup, BenchmarkPhase::Warmup); - assert_eq!(BenchmarkPhase::Running, BenchmarkPhase::Running); - assert_eq!(BenchmarkPhase::Cooldown, BenchmarkPhase::Cooldown); - assert_eq!(BenchmarkPhase::Completed, BenchmarkPhase::Completed); - assert_ne!(BenchmarkPhase::Running, BenchmarkPhase::Completed); - } - - #[test] - fn test_benchmark_phase_failed() { - let failed = BenchmarkPhase::Failed("Connection error".to_string()); - if let BenchmarkPhase::Failed(msg) = failed { - assert_eq!(msg, "Connection error"); - } else { - panic!("Expected Failed variant"); - } - } - - #[test] - fn test_scheduler_type_default() { - let scheduler_type = SchedulerType::default(); - assert_eq!(scheduler_type, SchedulerType::ConstantVUs); - } - - #[test] - fn test_scheduler_type_equality() { - assert_eq!(SchedulerType::ConstantVUs, SchedulerType::ConstantVUs); - assert_eq!( - SchedulerType::ConstantArrivalRate, - SchedulerType::ConstantArrivalRate - ); - assert_ne!( - SchedulerType::ConstantVUs, - SchedulerType::ConstantArrivalRate - ); - } - - #[test] - fn test_request_completed_default() { - let completed = RequestCompleted::default(); - assert!(completed.request_id.is_empty()); - assert!(!completed.success); - assert!(completed.error.is_none()); - assert!(completed.ttft_ms.is_none()); - assert_eq!(completed.latency_ms, 0.0); - assert_eq!(completed.generated_tokens, 0); - assert_eq!(completed.prompt_tokens, 0); - assert!(completed.tpot_ms.is_none()); - assert!(completed.token_times_ms.is_empty()); - } - - #[test] - fn test_request_completed_success() { - let completed = RequestCompleted { - request_id: "req-123".to_string(), - success: true, - error: None, - ttft_ms: Some(50.0), - latency_ms: 500.0, - generated_tokens: 100, - prompt_tokens: 10, - tpot_ms: Some(4.5), - token_times_ms: vec![50.0, 54.5, 59.0], - }; - - assert!(completed.success); - assert_eq!(completed.ttft_ms, Some(50.0)); - assert_eq!(completed.latency_ms, 500.0); - } - - #[test] - fn test_metrics_snapshot_default() { - let snapshot = MetricsSnapshot::default(); - assert!(snapshot.phase_id.is_empty()); - assert_eq!(snapshot.progress_pct, 0.0); - assert_eq!(snapshot.successful_requests, 0); - assert!(snapshot.avg_ttft_ms.is_none()); - } - - #[test] - fn test_coordinator_status() { - let status = CoordinatorStatus { - run_id: Some("run-123".to_string()), - phase: Some(BenchmarkPhase::Running), - workers: 4, - active_requests: 10, - }; - - assert_eq!(status.run_id, Some("run-123".to_string())); - assert_eq!(status.workers, 4); - assert_eq!(status.active_requests, 10); - } - - #[test] - fn test_start_benchmark() { - let config = BenchmarkConfig::default(); - let start = StartBenchmark { - config: config.clone(), - run_id: "test-run".to_string(), - }; - - assert_eq!(start.run_id, "test-run"); - assert_eq!(start.config.url, config.url); - } - - #[test] - fn test_stop_benchmark() { - let stop = StopBenchmark { - run_id: "test-run".to_string(), - reason: "User interrupted".to_string(), - }; - - assert_eq!(stop.run_id, "test-run"); - assert_eq!(stop.reason, "User interrupted"); - } - - #[test] - fn test_configure_scheduler() { - let config = ConfigureScheduler { - scheduler_type: SchedulerType::ConstantArrivalRate, - max_vus: 50, - duration_secs: 120, - rate: Some(10.0), - }; - - assert_eq!(config.scheduler_type, SchedulerType::ConstantArrivalRate); - assert_eq!(config.max_vus, 50); - assert_eq!(config.rate, Some(10.0)); - } - - #[test] - fn test_worker_status() { - let status = WorkerStatus { - worker_id: "worker-1".to_string(), - active_requests: 5, - completed_requests: 100, - failed_requests: 2, - }; - - assert_eq!(status.worker_id, "worker-1"); - assert_eq!(status.active_requests, 5); - assert_eq!(status.completed_requests, 100); - assert_eq!(status.failed_requests, 2); - } - - #[test] - fn test_scheduler_progress() { - let progress = SchedulerProgress { - phase_id: "phase-1".to_string(), - progress_pct: 75.5, - sent_requests: 1000, - active_vus: 10, - elapsed_secs: 45.0, - }; - - assert_eq!(progress.phase_id, "phase-1"); - assert_eq!(progress.progress_pct, 75.5); - assert_eq!(progress.sent_requests, 1000); - } - - #[test] - fn test_benchmark_report() { - let report = BenchmarkReport { - run_id: "run-123".to_string(), - config: BenchmarkConfig::default(), - phases: vec![], - start_time: "2024-01-01T00:00:00Z".to_string(), - end_time: "2024-01-01T00:01:00Z".to_string(), - total_duration_secs: 60.0, - }; - - assert_eq!(report.run_id, "run-123"); - assert_eq!(report.total_duration_secs, 60.0); - assert!(report.phases.is_empty()); - } -} diff --git a/crates/pulsing-bench/src/actors/metrics_aggregator.rs b/crates/pulsing-bench/src/actors/metrics_aggregator.rs deleted file mode 100644 index 5616531e2..000000000 --- a/crates/pulsing-bench/src/actors/metrics_aggregator.rs +++ /dev/null @@ -1,986 +0,0 @@ -//! Metrics Aggregator Actor - collects and computes statistics -//! -//! This actor is responsible for: -//! - Receiving RequestCompleted events from workers -//! - Maintaining per-phase statistics -//! - Computing metrics (percentiles, averages, throughput) -//! - Providing metrics snapshots to other actors - -use super::messages::*; -use async_trait::async_trait; -use pulsing_actor::error::{PulsingError, RuntimeError}; -use pulsing_actor::prelude::*; -use std::time::{Duration, Instant}; -use tracing::info; - -/// Phase statistics - internal data structure for metrics computation -#[derive(Debug, Clone, Default)] -pub struct PhaseStats { - pub phase_id: String, - pub phase_name: String, - pub scheduler_type: SchedulerType, - pub target_rate: Option, - pub start_time: Option, - pub end_time: Option, - pub successful_requests: u64, - pub failed_requests: u64, - pub total_prompt_tokens: u64, - pub total_generated_tokens: u64, - ttft_values: Vec, - tpot_values: Vec, - latency_values: Vec, -} - -impl PhaseStats { - pub fn new( - phase_id: String, - phase_name: String, - scheduler_type: SchedulerType, - target_rate: Option, - ) -> Self { - Self { - phase_id, - phase_name, - scheduler_type, - target_rate, - start_time: Some(Instant::now()), - ..Default::default() - } - } - - pub fn add_result(&mut self, result: &RequestCompleted) { - if result.success { - self.successful_requests += 1; - self.total_prompt_tokens += result.prompt_tokens; - self.total_generated_tokens += result.generated_tokens; - self.latency_values.push(result.latency_ms); - - if let Some(ttft) = result.ttft_ms { - self.ttft_values.push(ttft); - } - if let Some(tpot) = result.tpot_ms { - self.tpot_values.push(tpot); - } - } else { - self.failed_requests += 1; - } - } - - pub fn duration(&self) -> Duration { - match (self.start_time, self.end_time) { - (Some(start), Some(end)) => end.duration_since(start), - (Some(start), None) => start.elapsed(), - _ => Duration::ZERO, - } - } - - pub fn progress(&self, expected_duration: Duration) -> f64 { - let elapsed = self.duration().as_secs_f64(); - let expected = expected_duration.as_secs_f64(); - if expected > 0.0 { - (elapsed / expected * 100.0).min(100.0) - } else { - 0.0 - } - } - - pub fn request_rate(&self) -> f64 { - let duration = self.duration().as_secs_f64(); - if duration > 0.0 { - self.successful_requests as f64 / duration - } else { - 0.0 - } - } - - pub fn error_rate(&self) -> f64 { - let total = self.successful_requests + self.failed_requests; - if total > 0 { - self.failed_requests as f64 / total as f64 * 100.0 - } else { - 0.0 - } - } - - pub fn avg_ttft_ms(&self) -> Option { - if self.ttft_values.is_empty() { - None - } else { - Some(self.ttft_values.iter().sum::() / self.ttft_values.len() as f64) - } - } - - pub fn avg_tpot_ms(&self) -> Option { - if self.tpot_values.is_empty() { - None - } else { - Some(self.tpot_values.iter().sum::() / self.tpot_values.len() as f64) - } - } - - fn std_dev(values: &[f64]) -> Option { - if values.len() < 2 { - return None; - } - let mean = values.iter().sum::() / values.len() as f64; - let variance = - values.iter().map(|v| (v - mean).powi(2)).sum::() / (values.len() - 1) as f64; - Some(variance.sqrt()) - } - - pub fn ttft_std_ms(&self) -> Option { - Self::std_dev(&self.ttft_values) - } - - pub fn tpot_std_ms(&self) -> Option { - Self::std_dev(&self.tpot_values) - } - - fn percentile(values: &[f64], p: f64) -> Option { - if values.is_empty() { - return None; - } - let mut sorted = values.to_vec(); - sorted.sort_by(|a, b| a.partial_cmp(b).unwrap()); - let idx = ((p * (sorted.len() - 1) as f64) / 100.0).round() as usize; - Some(sorted[idx.min(sorted.len() - 1)]) - } - - pub fn avg_latency_ms(&self) -> Option { - if self.latency_values.is_empty() { - None - } else { - Some(self.latency_values.iter().sum::() / self.latency_values.len() as f64) - } - } - - pub fn p50_latency_ms(&self) -> Option { - Self::percentile(&self.latency_values, 50.0) - } - - pub fn p95_latency_ms(&self) -> Option { - Self::percentile(&self.latency_values, 95.0) - } - - pub fn p99_latency_ms(&self) -> Option { - Self::percentile(&self.latency_values, 99.0) - } - - pub fn input_throughput(&self) -> Option { - let duration = self.duration().as_secs_f64(); - if duration > 0.0 && self.total_prompt_tokens > 0 { - Some(self.total_prompt_tokens as f64 / duration) - } else { - None - } - } - - pub fn output_throughput(&self) -> Option { - let duration = self.duration().as_secs_f64(); - if duration > 0.0 && self.total_generated_tokens > 0 { - Some(self.total_generated_tokens as f64 / duration) - } else { - None - } - } - - pub fn total_throughput(&self) -> Option { - let input = self.input_throughput().unwrap_or(0.0); - let output = self.output_throughput().unwrap_or(0.0); - if input > 0.0 || output > 0.0 { - Some(input + output) - } else { - None - } - } - - /// Convert to a serializable metrics snapshot - pub fn to_metrics(&self) -> MetricsSnapshot { - MetricsSnapshot { - phase_id: self.phase_id.clone(), - phase_name: self.phase_name.clone(), - progress_pct: 100.0, - elapsed_secs: self.duration().as_secs_f64(), - successful_requests: self.successful_requests, - failed_requests: self.failed_requests, - request_rate: self.request_rate(), - avg_ttft_ms: self.avg_ttft_ms(), - avg_tpot_ms: self.avg_tpot_ms(), - ttft_std_ms: self.ttft_std_ms(), - tpot_std_ms: self.tpot_std_ms(), - avg_latency_ms: self.avg_latency_ms(), - p50_latency_ms: self.p50_latency_ms(), - p95_latency_ms: self.p95_latency_ms(), - p99_latency_ms: self.p99_latency_ms(), - input_throughput: self.input_throughput(), - output_throughput: self.output_throughput(), - total_throughput: self.total_throughput(), - } - } - - /// Create a display-friendly snapshot with progress - pub fn to_display_snapshot(&self, expected_duration: Duration) -> PhaseDisplayData { - let is_completed = self.end_time.is_some(); - // If phase is completed, progress is always 100% - let progress_pct = if is_completed { - 100.0 - } else { - self.progress(expected_duration) - }; - - PhaseDisplayData { - phase_id: self.phase_id.clone(), - phase_name: self.phase_name.clone(), - is_completed, - progress_pct, - error_rate: self.error_rate(), - request_rate: self.request_rate(), - avg_ttft_ms: self.avg_ttft_ms(), - ttft_std_ms: self.ttft_std_ms(), - avg_tpot_ms: self.avg_tpot_ms(), - tpot_std_ms: self.tpot_std_ms(), - input_throughput: self.input_throughput(), - output_throughput: self.output_throughput(), - total_throughput: self.total_throughput(), - } - } -} - -/// Data sent to console renderer for display -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PhaseDisplayData { - pub phase_id: String, - pub phase_name: String, - pub is_completed: bool, - pub progress_pct: f64, - pub error_rate: f64, - pub request_rate: f64, - pub avg_ttft_ms: Option, - pub ttft_std_ms: Option, - pub avg_tpot_ms: Option, - pub tpot_std_ms: Option, - pub input_throughput: Option, - pub output_throughput: Option, - pub total_throughput: Option, -} - -/// Display update message sent to ConsoleRenderer -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct DisplayUpdate { - pub config: Option, - pub completed_phases: Vec, - pub current_phase: Option, - pub messages: Vec, -} - -/// Log message for display -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct DisplayMessage { - pub message: String, - pub timestamp: String, - pub level: String, -} - -/// Metrics Aggregator Actor - collects and computes statistics -pub struct MetricsAggregatorActor { - /// Run ID - run_id: Option, - /// Configuration - config: Option, - /// Start time - start_time: Option, - /// Current phase statistics - current_phase: Option, - /// Completed phases - completed_phases: Vec, - /// Console renderer reference - renderer_ref: Option, - /// Display refresh interval - refresh_interval: Duration, - /// Last display update - last_display: Instant, - /// Recent log messages - messages: Vec, - /// Expected duration for current phase - expected_duration: Duration, -} - -impl MetricsAggregatorActor { - pub fn new() -> Self { - Self { - run_id: None, - config: None, - start_time: None, - current_phase: None, - completed_phases: Vec::new(), - renderer_ref: None, - refresh_interval: Duration::from_millis(500), - last_display: Instant::now(), - messages: Vec::new(), - expected_duration: Duration::from_secs(60), - } - } - - pub fn with_renderer(mut self, renderer: ActorRef) -> Self { - self.renderer_ref = Some(renderer); - self - } - - fn add_message(&mut self, message: String) { - self.messages.push(DisplayMessage { - message, - timestamp: chrono::Utc::now().format("%H:%M:%S").to_string(), - level: "INFO".to_string(), - }); - // Keep only last 50 messages - if self.messages.len() > 50 { - self.messages.remove(0); - } - } - - fn register_run(&mut self, register: RegisterRun) { - self.run_id = Some(register.run_id); - self.config = Some(register.config.clone()); - self.start_time = Some(Instant::now()); - self.completed_phases.clear(); - self.current_phase = None; - self.messages.clear(); - self.expected_duration = Duration::from_secs(register.config.duration_secs); - - // Notify renderer of config - self.send_display_update(); - } - - fn start_phase(&mut self, phase: StartPhase) { - // End current phase if any - if let Some(mut current) = self.current_phase.take() { - current.end_time = Some(Instant::now()); - self.completed_phases.push(current); - } - - let stats = PhaseStats::new( - phase.phase_id.clone(), - phase.phase_name.clone(), - phase.scheduler_type, - phase.target_rate, - ); - self.current_phase = Some(stats); - - self.add_message(format!("Starting phase: {}", phase.phase_name)); - self.send_display_update(); - } - - fn end_phase(&mut self, _end: EndPhase) { - if let Some(mut current) = self.current_phase.take() { - current.end_time = Some(Instant::now()); - - self.add_message(format!( - "Phase {} completed: {} requests at {:.2} req/s", - current.phase_name, - current.successful_requests, - current.request_rate() - )); - - self.completed_phases.push(current); - } - - self.send_display_update(); - } - - fn add_result(&mut self, result: RequestCompleted) { - let should_update = if let Some(ref mut phase) = self.current_phase { - phase.add_result(&result); - self.last_display.elapsed() >= self.refresh_interval - } else { - false - }; - - if should_update { - self.send_display_update(); - self.last_display = Instant::now(); - } - } - - fn send_display_update(&self) { - if let Some(ref renderer) = self.renderer_ref { - let update = self.build_display_update(); - // Fire and forget - don't block on display - let renderer = renderer.clone(); - tokio::spawn(async move { - let _ = renderer.tell(update).await; - }); - } - } - - fn build_display_update(&self) -> DisplayUpdate { - let completed: Vec = self - .completed_phases - .iter() - .map(|p| p.to_display_snapshot(self.expected_duration)) - .collect(); - - let current = self - .current_phase - .as_ref() - .map(|p| p.to_display_snapshot(self.expected_duration)); - - DisplayUpdate { - config: self.config.clone(), - completed_phases: completed, - current_phase: current, - messages: self.messages.clone(), - } - } - - fn get_metrics(&self) -> MetricsSnapshot { - self.current_phase - .as_ref() - .map(|p| p.to_metrics()) - .unwrap_or_else(|| { - self.completed_phases - .last() - .map(|p| p.to_metrics()) - .unwrap_or_default() - }) - } - - fn get_report(&self) -> BenchmarkReport { - let phases: Vec = self - .completed_phases - .iter() - .map(|p| PhaseReport { - phase_id: p.phase_id.clone(), - phase_name: p.phase_name.clone(), - duration_secs: p.duration().as_secs_f64(), - metrics: p.to_metrics(), - }) - .collect(); - - let total_duration = self - .start_time - .map(|t| t.elapsed().as_secs_f64()) - .unwrap_or(0.0); - - BenchmarkReport { - run_id: self.run_id.clone().unwrap_or_default(), - config: self.config.clone().unwrap_or_default(), - phases, - start_time: chrono::Utc::now().to_rfc3339(), - end_time: chrono::Utc::now().to_rfc3339(), - total_duration_secs: total_duration, - } - } - - /// Send final update to renderer - fn finalize(&self) { - if let Some(ref renderer) = self.renderer_ref { - // Send final display update - let update = self.build_display_update(); - let renderer = renderer.clone(); - - // Also send a FinalReport message - let report = self.get_report(); - tokio::spawn(async move { - let _ = renderer.tell(update).await; - let _ = renderer.tell(FinalReport { report }).await; - }); - } - } -} - -impl Default for MetricsAggregatorActor { - fn default() -> Self { - Self::new() - } -} - -/// Message to signal final report is ready -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct FinalReport { - pub report: BenchmarkReport, -} - -#[async_trait] -impl Actor for MetricsAggregatorActor { - async fn on_start(&mut self, ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - info!("MetricsAggregator started with actor_id {:?}", ctx.id()); - Ok(()) - } - - async fn on_stop(&mut self, _ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - self.finalize(); - info!("MetricsAggregator stopped"); - Ok(()) - } - - async fn receive( - &mut self, - msg: Message, - _ctx: &mut ActorContext, - ) -> pulsing_actor::error::Result { - let msg_type = msg.msg_type(); - - if msg_type.ends_with("RegisterRun") { - let register: RegisterRun = msg.unpack()?; - self.register_run(register); - return Message::pack(&AckMessage::ok()); - } - - if msg_type.ends_with("StartPhase") { - let phase: StartPhase = msg.unpack()?; - self.start_phase(phase); - return Message::pack(&AckMessage::ok()); - } - - if msg_type.ends_with("EndPhase") { - let end: EndPhase = msg.unpack()?; - self.end_phase(end); - return Message::pack(&AckMessage::ok()); - } - - if msg_type.ends_with("RequestCompleted") { - let result: RequestCompleted = msg.unpack()?; - self.add_result(result); - return Message::pack(&AckMessage::ok()); - } - - if msg_type.ends_with("GetMetrics") { - return Message::pack(&self.get_metrics()); - } - - if msg_type.ends_with("GetReport") { - return Message::pack(&self.get_report()); - } - - Err(PulsingError::from(RuntimeError::Other(format!( - "Unknown message type: {}", - msg_type - )))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_phase_stats() { - let mut stats = PhaseStats::new( - "test".to_string(), - "Test Phase".to_string(), - SchedulerType::ConstantVUs, - None, - ); - - let result = RequestCompleted { - request_id: "1".to_string(), - success: true, - error: None, - ttft_ms: Some(100.0), - latency_ms: 500.0, - generated_tokens: 50, - prompt_tokens: 10, - tpot_ms: Some(8.0), - token_times_ms: vec![], - }; - - stats.add_result(&result); - assert_eq!(stats.successful_requests, 1); - assert_eq!(stats.avg_ttft_ms(), Some(100.0)); - } - - #[test] - fn test_percentile() { - let values = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]; - // For 10 elements, 50th percentile rounds to index 5 (6.0) - assert_eq!(PhaseStats::percentile(&values, 50.0), Some(6.0)); - // For 10 elements, 90th percentile rounds to index 8 (9.0) - assert_eq!(PhaseStats::percentile(&values, 90.0), Some(9.0)); - } - - #[test] - fn test_phase_stats_default() { - let stats = PhaseStats::default(); - assert!(stats.phase_id.is_empty()); - assert_eq!(stats.successful_requests, 0); - assert_eq!(stats.failed_requests, 0); - assert!(stats.start_time.is_none()); - assert!(stats.end_time.is_none()); - } - - #[test] - fn test_phase_stats_multiple_results() { - let mut stats = PhaseStats::new( - "test".to_string(), - "Test Phase".to_string(), - SchedulerType::ConstantVUs, - None, - ); - - // Add successful results - for i in 0..5 { - let result = RequestCompleted { - request_id: format!("{}", i), - success: true, - error: None, - ttft_ms: Some(100.0 + i as f64 * 10.0), - latency_ms: 500.0 + i as f64 * 50.0, - generated_tokens: 50, - prompt_tokens: 10, - tpot_ms: Some(8.0 + i as f64), - token_times_ms: vec![], - }; - stats.add_result(&result); - } - - assert_eq!(stats.successful_requests, 5); - assert_eq!(stats.failed_requests, 0); - assert_eq!(stats.total_prompt_tokens, 50); - assert_eq!(stats.total_generated_tokens, 250); - - // Average TTFT should be (100 + 110 + 120 + 130 + 140) / 5 = 120 - assert_eq!(stats.avg_ttft_ms(), Some(120.0)); - } - - #[test] - fn test_phase_stats_failed_result() { - let mut stats = PhaseStats::new( - "test".to_string(), - "Test Phase".to_string(), - SchedulerType::ConstantVUs, - None, - ); - - let failed_result = RequestCompleted { - request_id: "1".to_string(), - success: false, - error: Some("Connection timeout".to_string()), - ttft_ms: None, - latency_ms: 5000.0, - generated_tokens: 0, - prompt_tokens: 10, - tpot_ms: None, - token_times_ms: vec![], - }; - - stats.add_result(&failed_result); - assert_eq!(stats.successful_requests, 0); - assert_eq!(stats.failed_requests, 1); - assert_eq!(stats.total_prompt_tokens, 0); - } - - #[test] - fn test_phase_stats_error_rate() { - let mut stats = PhaseStats::new( - "test".to_string(), - "Test Phase".to_string(), - SchedulerType::ConstantVUs, - None, - ); - - // Add 8 successful, 2 failed - for i in 0..10 { - let result = RequestCompleted { - request_id: format!("{}", i), - success: i < 8, - error: if i >= 8 { - Some("Error".to_string()) - } else { - None - }, - ttft_ms: Some(100.0), - latency_ms: 500.0, - generated_tokens: 50, - prompt_tokens: 10, - tpot_ms: Some(8.0), - token_times_ms: vec![], - }; - stats.add_result(&result); - } - - assert_eq!(stats.successful_requests, 8); - assert_eq!(stats.failed_requests, 2); - assert!((stats.error_rate() - 20.0).abs() < 0.001); - } - - #[test] - fn test_phase_stats_error_rate_zero() { - let stats = PhaseStats::default(); - assert_eq!(stats.error_rate(), 0.0); - } - - #[test] - fn test_std_dev() { - // Standard deviation of [1, 2, 3, 4, 5] is sqrt(2.5) ≈ 1.58 - let values = vec![1.0, 2.0, 3.0, 4.0, 5.0]; - let std = PhaseStats::std_dev(&values).unwrap(); - assert!((std - 1.5811).abs() < 0.001); - } - - #[test] - fn test_std_dev_single_value() { - let values = vec![5.0]; - assert!(PhaseStats::std_dev(&values).is_none()); - } - - #[test] - fn test_std_dev_empty() { - let values: Vec = vec![]; - assert!(PhaseStats::std_dev(&values).is_none()); - } - - #[test] - fn test_percentile_empty() { - let values: Vec = vec![]; - assert!(PhaseStats::percentile(&values, 50.0).is_none()); - } - - #[test] - fn test_percentile_single_value() { - let values = vec![42.0]; - assert_eq!(PhaseStats::percentile(&values, 50.0), Some(42.0)); - assert_eq!(PhaseStats::percentile(&values, 99.0), Some(42.0)); - } - - #[test] - fn test_phase_stats_latency_percentiles() { - let mut stats = PhaseStats::new( - "test".to_string(), - "Test Phase".to_string(), - SchedulerType::ConstantVUs, - None, - ); - - // Add results with increasing latencies - for i in 1..=100 { - let result = RequestCompleted { - request_id: format!("{}", i), - success: true, - error: None, - ttft_ms: Some(100.0), - latency_ms: i as f64, - generated_tokens: 50, - prompt_tokens: 10, - tpot_ms: Some(8.0), - token_times_ms: vec![], - }; - stats.add_result(&result); - } - - // p50 should be around 50 - let p50 = stats.p50_latency_ms().unwrap(); - assert!((p50 - 50.0).abs() < 2.0); - - // p95 should be around 95 - let p95 = stats.p95_latency_ms().unwrap(); - assert!((p95 - 95.0).abs() < 2.0); - - // p99 should be around 99 - let p99 = stats.p99_latency_ms().unwrap(); - assert!((p99 - 99.0).abs() < 2.0); - } - - #[test] - fn test_phase_stats_empty_metrics() { - let stats = PhaseStats::default(); - assert!(stats.avg_ttft_ms().is_none()); - assert!(stats.avg_tpot_ms().is_none()); - assert!(stats.avg_latency_ms().is_none()); - assert!(stats.p50_latency_ms().is_none()); - assert!(stats.p95_latency_ms().is_none()); - assert!(stats.p99_latency_ms().is_none()); - assert!(stats.ttft_std_ms().is_none()); - assert!(stats.tpot_std_ms().is_none()); - } - - #[test] - fn test_phase_stats_throughput() { - let mut stats = PhaseStats::new( - "test".to_string(), - "Test Phase".to_string(), - SchedulerType::ConstantVUs, - None, - ); - - // Add results - for _ in 0..10 { - let result = RequestCompleted { - request_id: "1".to_string(), - success: true, - error: None, - ttft_ms: Some(100.0), - latency_ms: 500.0, - generated_tokens: 100, - prompt_tokens: 50, - tpot_ms: Some(8.0), - token_times_ms: vec![], - }; - stats.add_result(&result); - } - - // Total tokens: 500 prompt + 1000 generated = 1500 - assert_eq!(stats.total_prompt_tokens, 500); - assert_eq!(stats.total_generated_tokens, 1000); - - // Throughput depends on duration, so test total_throughput - let input = stats.input_throughput(); - let output = stats.output_throughput(); - let total = stats.total_throughput(); - - // All should be Some since we have tokens - assert!(input.is_some()); - assert!(output.is_some()); - assert!(total.is_some()); - } - - #[test] - fn test_phase_stats_throughput_empty() { - let stats = PhaseStats::default(); - assert!(stats.input_throughput().is_none()); - assert!(stats.output_throughput().is_none()); - assert!(stats.total_throughput().is_none()); - } - - #[test] - fn test_phase_stats_to_metrics() { - let mut stats = PhaseStats::new( - "phase-1".to_string(), - "Test Phase".to_string(), - SchedulerType::ConstantVUs, - Some(10.0), - ); - - let result = RequestCompleted { - request_id: "1".to_string(), - success: true, - error: None, - ttft_ms: Some(100.0), - latency_ms: 500.0, - generated_tokens: 50, - prompt_tokens: 10, - tpot_ms: Some(8.0), - token_times_ms: vec![], - }; - stats.add_result(&result); - - let metrics = stats.to_metrics(); - assert_eq!(metrics.phase_id, "phase-1"); - assert_eq!(metrics.phase_name, "Test Phase"); - assert_eq!(metrics.successful_requests, 1); - assert_eq!(metrics.failed_requests, 0); - assert_eq!(metrics.avg_ttft_ms, Some(100.0)); - } - - #[test] - fn test_phase_stats_progress() { - let stats = PhaseStats::new( - "test".to_string(), - "Test Phase".to_string(), - SchedulerType::ConstantVUs, - None, - ); - - // Progress should be based on elapsed time vs expected duration - let expected_duration = Duration::from_secs(60); - let progress = stats.progress(expected_duration); - // Since we just started, progress should be small - assert!(progress >= 0.0); - assert!(progress <= 100.0); - } - - #[test] - fn test_phase_stats_progress_zero_duration() { - let stats = PhaseStats::default(); - let progress = stats.progress(Duration::ZERO); - assert_eq!(progress, 0.0); - } - - #[test] - fn test_phase_display_data() { - let stats = PhaseStats::new( - "test".to_string(), - "Test Phase".to_string(), - SchedulerType::ConstantVUs, - None, - ); - - let expected_duration = Duration::from_secs(60); - let display = stats.to_display_snapshot(expected_duration); - - assert_eq!(display.phase_id, "test"); - assert_eq!(display.phase_name, "Test Phase"); - assert!(!display.is_completed); - } - - #[test] - fn test_phase_display_data_completed() { - let now = std::time::Instant::now(); - let stats = PhaseStats { - phase_id: "test".to_string(), - phase_name: "Test Phase".to_string(), - start_time: Some(now), - end_time: Some(now), - ..Default::default() - }; - - let expected_duration = Duration::from_secs(60); - let display = stats.to_display_snapshot(expected_duration); - assert!(display.is_completed); - assert_eq!(display.progress_pct, 100.0); - } - - #[test] - fn test_metrics_aggregator_new() { - let aggregator = MetricsAggregatorActor::new(); - assert!(aggregator.run_id.is_none()); - assert!(aggregator.config.is_none()); - assert!(aggregator.current_phase.is_none()); - assert!(aggregator.completed_phases.is_empty()); - } - - #[test] - fn test_metrics_aggregator_default() { - let aggregator = MetricsAggregatorActor::default(); - assert!(aggregator.run_id.is_none()); - } - - #[test] - fn test_display_message() { - let msg = DisplayMessage { - message: "Test message".to_string(), - timestamp: "12:00:00".to_string(), - level: "INFO".to_string(), - }; - - assert_eq!(msg.message, "Test message"); - assert_eq!(msg.level, "INFO"); - } - - #[test] - fn test_display_update() { - let update = DisplayUpdate { - config: None, - completed_phases: vec![], - current_phase: None, - messages: vec![], - }; - - assert!(update.config.is_none()); - assert!(update.completed_phases.is_empty()); - } - - #[test] - fn test_final_report() { - let report = BenchmarkReport { - run_id: "test".to_string(), - config: BenchmarkConfig::default(), - phases: vec![], - start_time: "".to_string(), - end_time: "".to_string(), - total_duration_secs: 0.0, - }; - - let final_report = FinalReport { report }; - assert_eq!(final_report.report.run_id, "test"); - } -} diff --git a/crates/pulsing-bench/src/actors/mod.rs b/crates/pulsing-bench/src/actors/mod.rs deleted file mode 100644 index 675a6fa09..000000000 --- a/crates/pulsing-bench/src/actors/mod.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! Actor-based benchmark implementation -//! -//! This module provides a refactored benchmark system using the Actor model. -//! -//! ## Architecture -//! -//! ```text -//! ┌─────────────────┐ -//! │ Coordinator │ -//! │ (Orchestrator) │ -//! └────────┬────────┘ -//! │ -//! ┌─────────────────────────────┼─────────────────────────────┐ -//! │ │ │ -//! ▼ ▼ ▼ -//! ┌────────────────┐ ┌─────────────────┐ ┌────────────────┐ -//! │ Scheduler │ │ Worker(s) │ │ Metrics │ -//! │ (Rate Control) │ │ (HTTP Clients) │ │ Aggregator │ -//! └────────────────┘ └───────┬─────────┘ └────────┬───────┘ -//! │ │ -//! │ RequestCompleted │ DisplayUpdate -//! │ │ -//! ▼ ▼ -//! ┌─────────────────┐ ┌────────────────┐ -//! │ Metrics │ ───────► │ Console │ -//! │ Aggregator │ │ Renderer │ -//! └─────────────────┘ └────────────────┘ -//! ``` -//! -//! ## Actors -//! -//! - **Coordinator**: Manages lifecycle, spawns other actors, orchestrates benchmark phases -//! - **Scheduler**: Controls request timing (ConstantVUs, ConstantArrivalRate) -//! - **Worker**: Sends HTTP requests, processes streaming responses, calculates TTFT/TPOT -//! - **MetricsAggregator**: Collects results, computes statistics (percentiles, throughput) -//! - **ConsoleRenderer**: Renders benchmark progress to terminal (tables, progress bars) -//! -//! ## Benefits of Actor Model -//! -//! 1. **Separation of Concerns**: Each actor has a single responsibility -//! 2. **Testability**: Metrics logic can be tested without terminal dependencies -//! 3. **Flexibility**: Easy to replace ConsoleRenderer with JSON/Web output -//! 4. **Scalability**: Workers can be distributed across nodes -//! 5. **Fault Isolation**: Actor failures don't crash the whole system - -pub mod console_renderer; -pub mod coordinator; -pub mod messages; -pub mod metrics_aggregator; -pub mod scheduler; -pub mod worker; - -// Re-export main types -pub use console_renderer::ConsoleRendererActor; -pub use coordinator::CoordinatorActor; -pub use messages::*; -pub use metrics_aggregator::MetricsAggregatorActor; -pub use scheduler::SchedulerActor; -pub use worker::WorkerActor; diff --git a/crates/pulsing-bench/src/actors/scheduler.rs b/crates/pulsing-bench/src/actors/scheduler.rs deleted file mode 100644 index 2bf42e6ad..000000000 --- a/crates/pulsing-bench/src/actors/scheduler.rs +++ /dev/null @@ -1,711 +0,0 @@ -//! Scheduler Actor - controls request timing and rate - -use super::messages::*; -use crate::tokenizer::TokenCounter; -use async_trait::async_trait; -use pulsing_actor::error::{PulsingError, RuntimeError}; -use pulsing_actor::prelude::*; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use tokio::time::interval; -use tracing::{info, warn}; - -/// Request generator trait -pub trait RequestGenerator: Send + Sync { - fn generate(&self) -> RequestTemplate; -} - -/// Simple round-robin request generator (estimation-based) -pub struct SimpleRequestGenerator { - prompts: Vec, - index: AtomicU64, -} - -impl SimpleRequestGenerator { - pub fn new(prompts: Vec) -> Self { - Self { - prompts, - index: AtomicU64::new(0), - } - } - - pub fn default_prompts() -> Self { - Self::new(vec![ - "What is the meaning of life?".to_string(), - "Explain quantum computing in simple terms.".to_string(), - "Write a short poem about the ocean.".to_string(), - "What are the benefits of exercise?".to_string(), - "How does photosynthesis work?".to_string(), - ]) - } -} - -impl RequestGenerator for SimpleRequestGenerator { - fn generate(&self) -> RequestTemplate { - let idx = self.index.fetch_add(1, Ordering::SeqCst) as usize; - let prompt = &self.prompts[idx % self.prompts.len()]; - RequestTemplate { - id: format!("req-{}", idx), - prompt: prompt.clone(), - num_prompt_tokens: (prompt.len() / 4) as u64, // rough estimate - num_decode_tokens: Some(100), - } - } -} - -/// Tokenized request generator - uses real tokenizer for accurate token counting -pub struct TokenizedRequestGenerator { - prompts: Vec, - index: AtomicU64, - token_counter: TokenCounter, -} - -impl TokenizedRequestGenerator { - pub fn new(token_counter: TokenCounter) -> Self { - Self { - prompts: vec![ - "What is the meaning of life?".to_string(), - "Explain quantum computing in simple terms.".to_string(), - "Write a short poem about the ocean.".to_string(), - "What are the benefits of exercise?".to_string(), - "How does photosynthesis work?".to_string(), - "Describe the process of machine learning.".to_string(), - "What causes the northern lights?".to_string(), - "Explain how a computer works.".to_string(), - ], - index: AtomicU64::new(0), - token_counter, - } - } - - pub fn with_prompts(mut self, prompts: Vec) -> Self { - self.prompts = prompts; - self - } -} - -impl RequestGenerator for TokenizedRequestGenerator { - fn generate(&self) -> RequestTemplate { - let idx = self.index.fetch_add(1, Ordering::SeqCst) as usize; - let prompt = &self.prompts[idx % self.prompts.len()]; - - // Use real tokenizer for accurate token counting - let num_prompt_tokens = self.token_counter.count_tokens(prompt); - - RequestTemplate { - id: format!("req-{}", idx), - prompt: prompt.clone(), - num_prompt_tokens, - num_decode_tokens: Some(100), - } - } -} - -/// Scheduler configuration -#[derive(Debug, Clone)] -pub struct SchedulerConfig { - pub scheduler_type: SchedulerType, - pub max_vus: u64, - pub duration: Duration, - pub rate: Option, -} - -impl Default for SchedulerConfig { - fn default() -> Self { - Self { - scheduler_type: SchedulerType::ConstantVUs, - max_vus: 10, - duration: Duration::from_secs(60), - rate: None, - } - } -} - -/// Scheduler Actor - manages request scheduling -pub struct SchedulerActor { - /// Current configuration - config: SchedulerConfig, - /// Request generator - request_gen: Arc, - /// Worker actor references - workers: Vec, - /// Coordinator reference for progress updates - coordinator_ref: Option, - /// MetricsAggregator reference - metrics_ref: Option, - /// Target URL - target_url: String, - /// API key - api_key: String, - /// Model name - model_name: String, - /// Is scheduling active - is_active: Arc, - /// Current phase ID - phase_id: String, - /// Sent requests counter - sent_requests: Arc, - /// Active VUs counter - active_vus: Arc, - /// Start time - start_time: Option, -} - -impl SchedulerActor { - pub fn new() -> Self { - Self { - config: SchedulerConfig::default(), - request_gen: Arc::new(SimpleRequestGenerator::default_prompts()), - workers: Vec::new(), - coordinator_ref: None, - metrics_ref: None, - target_url: "http://localhost:8000".to_string(), - api_key: String::new(), - model_name: "gpt2".to_string(), - is_active: Arc::new(AtomicBool::new(false)), - phase_id: String::new(), - sent_requests: Arc::new(AtomicU64::new(0)), - active_vus: Arc::new(AtomicU64::new(0)), - start_time: None, - } - } - - pub fn with_config(mut self, config: SchedulerConfig) -> Self { - self.config = config; - self - } - - pub fn with_request_generator(mut self, gen: Arc) -> Self { - self.request_gen = gen; - self - } - - pub fn with_workers(mut self, workers: Vec) -> Self { - self.workers = workers; - self - } - - pub fn with_coordinator(mut self, coordinator: ActorRef) -> Self { - self.coordinator_ref = Some(coordinator); - self - } - - pub fn with_metrics(mut self, metrics: ActorRef) -> Self { - self.metrics_ref = Some(metrics); - self - } - - pub fn with_target(mut self, url: String, api_key: String, model_name: String) -> Self { - self.target_url = url; - self.api_key = api_key; - self.model_name = model_name; - self - } - - fn configure(&mut self, config: ConfigureScheduler) { - self.config = SchedulerConfig { - scheduler_type: config.scheduler_type, - max_vus: config.max_vus, - duration: Duration::from_secs(config.duration_secs), - rate: config.rate, - }; - info!("Scheduler configured: {:?}", self.config); - } - - async fn start_scheduling(&mut self, phase_id: String) -> anyhow::Result<()> { - if self.workers.is_empty() { - return Err(anyhow::anyhow!("No workers configured")); - } - - self.phase_id = phase_id.clone(); - self.is_active.store(true, Ordering::SeqCst); - self.sent_requests.store(0, Ordering::SeqCst); - self.active_vus.store(0, Ordering::SeqCst); - self.start_time = Some(Instant::now()); - - info!( - "Starting scheduling for phase {} with {:?}", - phase_id, self.config.scheduler_type - ); - - match self.config.scheduler_type { - SchedulerType::ConstantVUs => { - self.run_constant_vus().await?; - } - SchedulerType::ConstantArrivalRate => { - self.run_constant_rate().await?; - } - } - - Ok(()) - } - - /// Run constant VUs scheduling - maintain N concurrent requests - async fn run_constant_vus(&mut self) -> anyhow::Result<()> { - let max_vus = self.config.max_vus; - let duration = self.config.duration; - let is_active = self.is_active.clone(); - let sent_requests = self.sent_requests.clone(); - let active_vus = self.active_vus.clone(); - - let start = Instant::now(); - let mut handles = Vec::new(); - - // Spawn initial VUs - for i in 0..max_vus { - if !is_active.load(Ordering::SeqCst) { - break; - } - - let worker_idx = i as usize % self.workers.len(); - let worker = self.workers[worker_idx].clone(); - let template = self.request_gen.generate(); - let request_id = template.id.clone(); - - let request = SendRequest { - request_id, - template, - target_url: self.target_url.clone(), - api_key: self.api_key.clone(), - model_name: self.model_name.clone(), - }; - - sent_requests.fetch_add(1, Ordering::SeqCst); - active_vus.fetch_add(1, Ordering::SeqCst); - - let is_active_clone = is_active.clone(); - let active_vus_clone = active_vus.clone(); - let sent_requests_clone = sent_requests.clone(); - let workers = self.workers.clone(); - let request_gen = self.request_gen.clone(); - let target_url = self.target_url.clone(); - let api_key = self.api_key.clone(); - let model_name = self.model_name.clone(); - - let handle = tokio::spawn(async move { - // Send initial request - let _: RequestCompleted = worker.ask(request).await.unwrap_or_default(); - active_vus_clone.fetch_sub(1, Ordering::SeqCst); - - // Keep spawning requests while duration not reached - while is_active_clone.load(Ordering::SeqCst) && start.elapsed() < duration { - let worker_idx = - sent_requests_clone.load(Ordering::SeqCst) as usize % workers.len(); - let worker = &workers[worker_idx]; - let template = request_gen.generate(); - - let request = SendRequest { - request_id: template.id.clone(), - template, - target_url: target_url.clone(), - api_key: api_key.clone(), - model_name: model_name.clone(), - }; - - sent_requests_clone.fetch_add(1, Ordering::SeqCst); - active_vus_clone.fetch_add(1, Ordering::SeqCst); - - let _: RequestCompleted = worker.ask(request).await.unwrap_or_default(); - active_vus_clone.fetch_sub(1, Ordering::SeqCst); - } - }); - - handles.push(handle); - } - - // Wait for duration or until stopped - tokio::select! { - _ = tokio::time::sleep(duration) => { - info!("Duration reached, stopping scheduling"); - } - _ = async { - while is_active.load(Ordering::SeqCst) { - tokio::time::sleep(Duration::from_millis(100)).await; - } - } => { - info!("Scheduling stopped externally"); - } - } - - is_active.store(false, Ordering::SeqCst); - - // Wait for all VUs to complete - for handle in handles { - let _ = handle.await; - } - - info!( - "Constant VUs scheduling completed. Sent: {} requests", - sent_requests.load(Ordering::SeqCst) - ); - - Ok(()) - } - - /// Run constant arrival rate scheduling - send requests at fixed rate - async fn run_constant_rate(&mut self) -> anyhow::Result<()> { - let rate = self - .config - .rate - .ok_or_else(|| anyhow::anyhow!("Rate not configured"))?; - let max_vus = self.config.max_vus; - let duration = self.config.duration; - let is_active = self.is_active.clone(); - let sent_requests = self.sent_requests.clone(); - let active_vus = self.active_vus.clone(); - - let start = Instant::now(); - - // Calculate tick interval to achieve target rate - let tick_ms = 10u64; - let requests_per_tick = rate * (tick_ms as f64) / 1000.0; - let mut spawn_queue = 0.0; - - let mut ticker = interval(Duration::from_millis(tick_ms)); - - while start.elapsed() < duration && is_active.load(Ordering::SeqCst) { - ticker.tick().await; - - spawn_queue += requests_per_tick; - - // Spawn requests when we have accumulated enough - while spawn_queue >= 1.0 { - // Check VU limit - if active_vus.load(Ordering::SeqCst) >= max_vus { - warn!("Max VUs reached, skipping request"); - spawn_queue -= 1.0; - continue; - } - - let worker_idx = sent_requests.load(Ordering::SeqCst) as usize % self.workers.len(); - let worker = self.workers[worker_idx].clone(); - let template = self.request_gen.generate(); - - let request = SendRequest { - request_id: template.id.clone(), - template, - target_url: self.target_url.clone(), - api_key: self.api_key.clone(), - model_name: self.model_name.clone(), - }; - - sent_requests.fetch_add(1, Ordering::SeqCst); - active_vus.fetch_add(1, Ordering::SeqCst); - - let active_vus_clone = active_vus.clone(); - - // Fire and forget - don't wait for response - tokio::spawn(async move { - let _: RequestCompleted = worker.ask(request).await.unwrap_or_default(); - active_vus_clone.fetch_sub(1, Ordering::SeqCst); - }); - - spawn_queue -= 1.0; - } - } - - is_active.store(false, Ordering::SeqCst); - - // Wait for remaining requests to complete - while active_vus.load(Ordering::SeqCst) > 0 { - tokio::time::sleep(Duration::from_millis(100)).await; - } - - info!( - "Constant rate scheduling completed. Sent: {} requests at {:.2} req/s", - sent_requests.load(Ordering::SeqCst), - rate - ); - - Ok(()) - } - - fn get_progress(&self) -> SchedulerProgress { - let elapsed = self - .start_time - .map(|t| t.elapsed().as_secs_f64()) - .unwrap_or(0.0); - let progress = if self.config.duration.as_secs_f64() > 0.0 { - (elapsed / self.config.duration.as_secs_f64() * 100.0).min(100.0) - } else { - 0.0 - }; - - SchedulerProgress { - phase_id: self.phase_id.clone(), - progress_pct: progress, - sent_requests: self.sent_requests.load(Ordering::SeqCst), - active_vus: self.active_vus.load(Ordering::SeqCst), - elapsed_secs: elapsed, - } - } -} - -impl Default for SchedulerActor { - fn default() -> Self { - Self::new() - } -} - -#[async_trait] -impl Actor for SchedulerActor { - async fn on_start(&mut self, ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - info!("Scheduler started with actor_id {:?}", ctx.id()); - Ok(()) - } - - async fn on_stop(&mut self, _ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - self.is_active.store(false, Ordering::SeqCst); - info!( - "Scheduler stopped. Total sent: {}", - self.sent_requests.load(Ordering::SeqCst) - ); - Ok(()) - } - - async fn receive( - &mut self, - msg: Message, - _ctx: &mut ActorContext, - ) -> pulsing_actor::error::Result { - let msg_type = msg.msg_type(); - - if msg_type.ends_with("ConfigureScheduler") { - let config: ConfigureScheduler = msg.unpack()?; - self.configure(config); - return Message::pack(&AckMessage::ok()); - } - - if msg_type.ends_with("StartScheduling") { - let start: StartScheduling = msg.unpack()?; - match self.start_scheduling(start.phase_id).await { - Ok(()) => return Message::pack(&AckMessage::ok()), - Err(e) => return Message::pack(&AckMessage::error(e.to_string())), - } - } - - if msg_type.ends_with("PauseScheduling") { - self.is_active.store(false, Ordering::SeqCst); - return Message::pack(&AckMessage::ok()); - } - - if msg_type.ends_with("ResumeScheduling") { - // Note: Full resume would need to restart the scheduling loop - self.is_active.store(true, Ordering::SeqCst); - return Message::pack(&AckMessage::ok()); - } - - if msg_type.ends_with("SchedulerProgress") || msg_type.ends_with("GetProgress") { - return Message::pack(&self.get_progress()); - } - - Err(PulsingError::from(RuntimeError::Other(format!( - "Unknown message type: {}", - msg_type - )))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_simple_request_generator() { - let gen = SimpleRequestGenerator::default_prompts(); - let req1 = gen.generate(); - let req2 = gen.generate(); - assert_ne!(req1.id, req2.id); - } - - #[test] - fn test_scheduler_config() { - let config = SchedulerConfig { - scheduler_type: SchedulerType::ConstantArrivalRate, - max_vus: 100, - duration: Duration::from_secs(60), - rate: Some(10.0), - }; - assert_eq!(config.rate, Some(10.0)); - } - - #[test] - fn test_simple_request_generator_custom_prompts() { - let prompts = vec!["Hello".to_string(), "World".to_string()]; - let gen = SimpleRequestGenerator::new(prompts); - - let req1 = gen.generate(); - let _req2 = gen.generate(); // consume second request - let req3 = gen.generate(); - - // Third request should wrap around to first prompt - assert!(req1.prompt == "Hello" || req1.prompt == "World"); - assert!(req3.prompt == "Hello" || req3.prompt == "World"); - } - - #[test] - fn test_simple_request_generator_id_increment() { - let gen = SimpleRequestGenerator::default_prompts(); - - let req1 = gen.generate(); - let req2 = gen.generate(); - let req3 = gen.generate(); - - assert_eq!(req1.id, "req-0"); - assert_eq!(req2.id, "req-1"); - assert_eq!(req3.id, "req-2"); - } - - #[test] - fn test_simple_request_generator_token_estimate() { - let prompts = vec!["Hello world test".to_string()]; - let gen = SimpleRequestGenerator::new(prompts); - let req = gen.generate(); - - // Token estimate is len / 4 - // "Hello world test" = 16 chars / 4 = 4 tokens - assert_eq!(req.num_prompt_tokens, 4); - } - - #[test] - fn test_scheduler_config_default() { - let config = SchedulerConfig::default(); - assert_eq!(config.scheduler_type, SchedulerType::ConstantVUs); - assert_eq!(config.max_vus, 10); - assert_eq!(config.duration, Duration::from_secs(60)); - assert!(config.rate.is_none()); - } - - #[test] - fn test_scheduler_actor_new() { - let scheduler = SchedulerActor::new(); - assert!(scheduler.workers.is_empty()); - assert!(scheduler.coordinator_ref.is_none()); - assert!(scheduler.metrics_ref.is_none()); - assert_eq!(scheduler.target_url, "http://localhost:8000"); - assert!(scheduler.api_key.is_empty()); - assert_eq!(scheduler.model_name, "gpt2"); - } - - #[test] - fn test_scheduler_actor_default() { - let scheduler = SchedulerActor::default(); - assert!(scheduler.workers.is_empty()); - } - - #[test] - fn test_scheduler_actor_with_config() { - let config = SchedulerConfig { - scheduler_type: SchedulerType::ConstantArrivalRate, - max_vus: 50, - duration: Duration::from_secs(120), - rate: Some(20.0), - }; - - let scheduler = SchedulerActor::new().with_config(config.clone()); - assert_eq!( - scheduler.config.scheduler_type, - SchedulerType::ConstantArrivalRate - ); - assert_eq!(scheduler.config.max_vus, 50); - assert_eq!(scheduler.config.rate, Some(20.0)); - } - - #[test] - fn test_scheduler_actor_with_target() { - let scheduler = SchedulerActor::new().with_target( - "http://example.com".to_string(), - "api_key".to_string(), - "llama".to_string(), - ); - - assert_eq!(scheduler.target_url, "http://example.com"); - assert_eq!(scheduler.api_key, "api_key"); - assert_eq!(scheduler.model_name, "llama"); - } - - #[test] - fn test_scheduler_progress_initial() { - let scheduler = SchedulerActor::new(); - let progress = scheduler.get_progress(); - - assert!(progress.phase_id.is_empty()); - assert_eq!(progress.progress_pct, 0.0); - assert_eq!(progress.sent_requests, 0); - assert_eq!(progress.active_vus, 0); - assert_eq!(progress.elapsed_secs, 0.0); - } - - #[test] - fn test_tokenized_request_generator() { - let token_counter = TokenCounter::estimate(); - let gen = TokenizedRequestGenerator::new(token_counter); - - let req = gen.generate(); - assert!(!req.prompt.is_empty()); - assert!(req.num_prompt_tokens > 0); - assert_eq!(req.id, "req-0"); - } - - #[test] - fn test_tokenized_request_generator_with_prompts() { - let token_counter = TokenCounter::estimate(); - let prompts = vec![ - "Custom prompt one".to_string(), - "Custom prompt two".to_string(), - ]; - let gen = TokenizedRequestGenerator::new(token_counter).with_prompts(prompts); - - let req1 = gen.generate(); - let req2 = gen.generate(); - - assert!(req1.prompt == "Custom prompt one" || req1.prompt == "Custom prompt two"); - assert!(req2.prompt == "Custom prompt one" || req2.prompt == "Custom prompt two"); - } - - #[test] - fn test_tokenized_request_generator_id_increment() { - let token_counter = TokenCounter::estimate(); - let gen = TokenizedRequestGenerator::new(token_counter); - - let req1 = gen.generate(); - let req2 = gen.generate(); - let req3 = gen.generate(); - - assert_eq!(req1.id, "req-0"); - assert_eq!(req2.id, "req-1"); - assert_eq!(req3.id, "req-2"); - } - - #[test] - fn test_scheduler_configure() { - let mut scheduler = SchedulerActor::new(); - - let config_msg = ConfigureScheduler { - scheduler_type: SchedulerType::ConstantArrivalRate, - max_vus: 100, - duration_secs: 180, - rate: Some(50.0), - }; - - scheduler.configure(config_msg); - - assert_eq!( - scheduler.config.scheduler_type, - SchedulerType::ConstantArrivalRate - ); - assert_eq!(scheduler.config.max_vus, 100); - assert_eq!(scheduler.config.duration, Duration::from_secs(180)); - assert_eq!(scheduler.config.rate, Some(50.0)); - } - - #[test] - fn test_request_template_decode_tokens() { - let gen = SimpleRequestGenerator::default_prompts(); - let req = gen.generate(); - - // Default decode tokens should be 100 - assert_eq!(req.num_decode_tokens, Some(100)); - } -} diff --git a/crates/pulsing-bench/src/actors/worker.rs b/crates/pulsing-bench/src/actors/worker.rs deleted file mode 100644 index 3f30a97fc..000000000 --- a/crates/pulsing-bench/src/actors/worker.rs +++ /dev/null @@ -1,281 +0,0 @@ -//! Worker Actor - responsible for sending HTTP requests - -use super::messages::*; -use async_trait::async_trait; -use futures_util::StreamExt; -use pulsing_actor::error::{PulsingError, RuntimeError}; -use pulsing_actor::prelude::*; -use reqwest::Client; -use reqwest_eventsource::{Event as SseEvent, EventSource}; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use std::sync::Arc; -use std::time::Instant; -use tracing::{debug, info, trace}; - -/// Worker Actor - sends HTTP requests and reports results -pub struct WorkerActor { - /// Worker ID - worker_id: String, - /// HTTP client - client: Client, - /// MetricsAggregator actor reference for reporting results - metrics_ref: Option, - /// Active request count - active_requests: Arc, - /// Completed request count - completed_requests: Arc, - /// Failed request count - failed_requests: Arc, - /// Request timeout in seconds - timeout_secs: u64, -} - -impl WorkerActor { - pub fn new(worker_id: impl Into) -> Self { - Self { - worker_id: worker_id.into(), - client: Client::builder() - .pool_max_idle_per_host(100) - .build() - .expect("Failed to create HTTP client"), - metrics_ref: None, - active_requests: Arc::new(AtomicU32::new(0)), - completed_requests: Arc::new(AtomicU64::new(0)), - failed_requests: Arc::new(AtomicU64::new(0)), - timeout_secs: 300, - } - } - - pub fn with_metrics(mut self, metrics: ActorRef) -> Self { - self.metrics_ref = Some(metrics); - self - } - - pub fn with_timeout(mut self, timeout_secs: u64) -> Self { - self.timeout_secs = timeout_secs; - self - } - - /// Send a streaming request to the LLM endpoint - async fn send_request(&self, req: SendRequest) -> RequestCompleted { - let start_time = Instant::now(); - self.active_requests.fetch_add(1, Ordering::SeqCst); - - let result = self.execute_streaming_request(&req, start_time).await; - - self.active_requests.fetch_sub(1, Ordering::SeqCst); - - match result { - Ok(completed) => { - self.completed_requests.fetch_add(1, Ordering::SeqCst); - completed - } - Err(e) => { - self.failed_requests.fetch_add(1, Ordering::SeqCst); - RequestCompleted { - request_id: req.request_id, - success: false, - error: Some(e.to_string()), - ttft_ms: None, - latency_ms: start_time.elapsed().as_secs_f64() * 1000.0, - generated_tokens: 0, - prompt_tokens: req.template.num_prompt_tokens, - tpot_ms: None, - token_times_ms: vec![], - } - } - } - } - - async fn execute_streaming_request( - &self, - req: &SendRequest, - start_time: Instant, - ) -> anyhow::Result { - let url = format!("{}/v1/chat/completions", req.target_url); - - let body = serde_json::json!({ - "model": req.model_name, - "messages": [ - {"role": "user", "content": req.template.prompt} - ], - "stream": true, - "max_tokens": req.template.num_decode_tokens.unwrap_or(100), - }); - - let request = self - .client - .post(&url) - .header("Content-Type", "application/json") - .header("Accept", "text/event-stream"); - - let request = if !req.api_key.is_empty() { - request.header("Authorization", format!("Bearer {}", req.api_key)) - } else { - request - }; - - let request = request.json(&body); - - let mut es = EventSource::new(request)?; - let mut first_token_time: Option = None; - let mut token_times: Vec = Vec::new(); - let mut generated_tokens: u64 = 0; - let mut response_text = String::new(); - - while let Some(event) = es.next().await { - match event { - Ok(SseEvent::Open) => { - trace!("SSE connection opened for request {}", req.request_id); - } - Ok(SseEvent::Message(message)) => { - let data = message.data.trim(); - - if data == "[DONE]" { - break; - } - - // Parse the SSE data - if let Ok(json) = serde_json::from_str::(data) { - if let Some(choices) = json.get("choices").and_then(|c| c.as_array()) { - if let Some(choice) = choices.first() { - // Check for content delta - if let Some(delta) = choice.get("delta") { - if let Some(content) = - delta.get("content").and_then(|c| c.as_str()) - { - let now = Instant::now(); - - if first_token_time.is_none() { - first_token_time = Some(now); - } - - token_times.push( - now.duration_since(start_time).as_secs_f64() * 1000.0, - ); - generated_tokens += 1; - response_text.push_str(content); - } - } - - // Check for finish reason - if let Some(finish_reason) = - choice.get("finish_reason").and_then(|f| f.as_str()) - { - if finish_reason == "stop" || finish_reason == "length" { - break; - } - } - } - } - } - } - Err(e) => { - return Err(anyhow::anyhow!("SSE error: {}", e)); - } - } - } - - let end_time = Instant::now(); - let latency_ms = end_time.duration_since(start_time).as_secs_f64() * 1000.0; - - let ttft_ms = first_token_time.map(|t| t.duration_since(start_time).as_secs_f64() * 1000.0); - - // Calculate TPOT (time per output token) - only for tokens after the first - let tpot_ms = if token_times.len() > 1 { - let decode_time = latency_ms - ttft_ms.unwrap_or(0.0); - Some(decode_time / (generated_tokens as f64 - 1.0).max(1.0)) - } else { - None - }; - - Ok(RequestCompleted { - request_id: req.request_id.clone(), - success: true, - error: None, - ttft_ms, - latency_ms, - generated_tokens, - prompt_tokens: req.template.num_prompt_tokens, - tpot_ms, - token_times_ms: token_times, - }) - } -} - -#[async_trait] -impl Actor for WorkerActor { - async fn on_start(&mut self, ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - info!( - "Worker {} started with actor_id {:?}", - self.worker_id, - ctx.id() - ); - Ok(()) - } - - async fn on_stop(&mut self, _ctx: &mut ActorContext) -> pulsing_actor::error::Result<()> { - info!( - "Worker {} stopped. Completed: {}, Failed: {}", - self.worker_id, - self.completed_requests.load(Ordering::SeqCst), - self.failed_requests.load(Ordering::SeqCst) - ); - Ok(()) - } - - async fn receive( - &mut self, - msg: Message, - _ctx: &mut ActorContext, - ) -> pulsing_actor::error::Result { - let msg_type = msg.msg_type(); - - if msg_type.ends_with("SendRequest") { - let request: SendRequest = msg.unpack()?; - debug!( - "Worker {} received request {}", - self.worker_id, request.request_id - ); - - let result = self.send_request(request).await; - - // Report to metrics aggregator if configured - if let Some(ref metrics) = self.metrics_ref { - let _ = metrics.tell(result.clone()).await; - } - - return Message::pack(&result); - } - - if msg_type.ends_with("WorkerStatus") { - let status = WorkerStatus { - worker_id: self.worker_id.clone(), - active_requests: self.active_requests.load(Ordering::SeqCst), - completed_requests: self.completed_requests.load(Ordering::SeqCst), - failed_requests: self.failed_requests.load(Ordering::SeqCst), - }; - return Message::pack(&status); - } - - Err(PulsingError::from(RuntimeError::Other(format!( - "Unknown message type: {}", - msg_type - )))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - // Note: This test requires network/system access for HTTP client creation - // It may fail in sandboxed environments - #[test] - #[ignore] - fn test_worker_creation() { - let worker = WorkerActor::new("test-worker"); - assert_eq!(worker.worker_id, "test-worker"); - assert_eq!(worker.active_requests.load(Ordering::SeqCst), 0); - } -} diff --git a/crates/pulsing-bench/src/lib.rs b/crates/pulsing-bench/src/lib.rs deleted file mode 100644 index 2ddd5151c..000000000 --- a/crates/pulsing-bench/src/lib.rs +++ /dev/null @@ -1,355 +0,0 @@ -//! Pulsing Benchmark - Actor-based LLM Inference Benchmarking Tool -#![cfg_attr(coverage_nightly, feature(coverage_attribute))] -//! -//! This crate provides a high-performance benchmark tool for LLM inference endpoints -//! using the Actor model for better separation of concerns and real-time metrics. -//! -//! ## Architecture -//! -//! ```text -//! ┌─────────────────┐ -//! │ Coordinator │ -//! │ (Orchestrator) │ -//! └────────┬────────┘ -//! │ -//! ┌─────────────────────────────┼─────────────────────────────┐ -//! │ │ │ -//! ▼ ▼ ▼ -//! ┌────────────────┐ ┌─────────────────┐ ┌────────────────┐ -//! │ Scheduler │ │ Worker(s) │ │ Metrics │ -//! │ (Rate Control) │ │ (HTTP Clients) │ │ Aggregator │ -//! └────────────────┘ └───────┬─────────┘ └────────┬───────┘ -//! │ │ -//! │ RequestCompleted │ DisplayUpdate -//! └──────────────────────────────┤ -//! ▼ -//! ┌────────────────┐ -//! │ Console │ -//! │ Renderer │ -//! └────────────────┘ -//! ``` -//! -//! ## Example -//! -//! ```rust,ignore -//! use pulsing_bench::{run_benchmark, BenchmarkArgs}; -//! -//! #[tokio::main] -//! async fn main() { -//! let args = BenchmarkArgs { -//! url: "http://localhost:8000".to_string(), -//! model_name: "Qwen/Qwen3-0.6B".to_string(), -//! max_vus: 10, -//! duration_secs: 60, -//! ..Default::default() -//! }; -//! -//! let report = run_benchmark(args).await.unwrap(); -//! println!("Completed {} requests", report.phases.len()); -//! } -//! ``` - -use log::info; -use pulsing_actor::prelude::*; - -// Actor-based benchmark implementation -pub mod actors; - -// Tokenizer service for accurate token counting -pub mod tokenizer; - -// Re-export main types -pub use actors::{ - BenchmarkConfig, BenchmarkPhase, BenchmarkReport, CoordinatorActor, MetricsSnapshot, - PhaseReport, SchedulerType, -}; -pub use tokenizer::{TokenCounter, TokenizerService}; - -/// Benchmark arguments -#[derive(Debug, Clone)] -pub struct BenchmarkArgs { - /// Target URL for the LLM endpoint - pub url: String, - /// API key for authentication - pub api_key: String, - /// Model name to use in requests - pub model_name: String, - /// Tokenizer name (HuggingFace model name, defaults to model_name) - pub tokenizer_name: Option, - /// HuggingFace token for private models - pub hf_token: Option, - /// Maximum number of virtual users (concurrent requests) - pub max_vus: u64, - /// Duration of each benchmark phase in seconds - pub duration_secs: u64, - /// Warmup duration in seconds - pub warmup_secs: u64, - /// Benchmark kind: "throughput", "sweep", "csweep", "rate" - pub benchmark_kind: String, - /// Number of rate steps for sweep benchmarks - pub num_rates: u64, - /// Specific rates for rate benchmarks - pub rates: Option>, - /// Number of worker actors - pub num_workers: u32, -} - -impl Default for BenchmarkArgs { - fn default() -> Self { - Self { - url: "http://localhost:8000".to_string(), - api_key: String::new(), - model_name: "gpt2".to_string(), - tokenizer_name: None, - hf_token: None, - max_vus: 128, - duration_secs: 120, - warmup_secs: 30, - benchmark_kind: "throughput".to_string(), - num_rates: 10, - rates: None, - num_workers: 4, - } - } -} - -/// Parse duration string (e.g., "120s", "2m") into Duration -pub fn parse_duration(s: &str) -> anyhow::Result { - humantime::parse_duration(s).map_err(|e| anyhow::anyhow!("Invalid duration: {}", e)) -} - -/// Run benchmark with the given arguments -/// -/// This is the main entry point for running benchmarks. It creates an Actor system, -/// spawns the necessary actors, and orchestrates the benchmark phases. -/// -/// # Arguments -/// -/// * `args` - Benchmark configuration arguments -/// -/// # Returns -/// -/// * `Ok(BenchmarkReport)` - The benchmark results -/// * `Err` - If the benchmark fails -/// -/// # Example -/// -/// ```rust,ignore -/// let args = BenchmarkArgs { -/// url: "http://localhost:8000".to_string(), -/// model_name: "Qwen/Qwen3-0.6B".to_string(), -/// max_vus: 10, -/// duration_secs: 60, -/// ..Default::default() -/// }; -/// -/// let report = run_benchmark(args).await?; -/// ``` -pub async fn run_benchmark(args: BenchmarkArgs) -> anyhow::Result { - use actors::*; - - let git_sha = option_env!("VERGEN_GIT_SHA").unwrap_or("unknown"); - println!( - "Pulsing Benchmark {} ({})", - env!("CARGO_PKG_VERSION"), - git_sha - ); - - // Determine tokenizer name (use model_name if not specified) - let tokenizer_name = args - .tokenizer_name - .clone() - .unwrap_or_else(|| args.model_name.clone()); - - // Load tokenizer - println!("Loading tokenizer: {}", tokenizer_name); - let token_counter = match TokenCounter::real(&tokenizer_name, args.hf_token.clone()) { - Ok(tc) => { - println!("Tokenizer loaded successfully"); - tc - } - Err(e) => { - println!( - "Warning: Failed to load tokenizer ({}), using estimation", - e - ); - TokenCounter::estimate() - } - }; - - // Create actor system - let system = ActorSystem::new(SystemConfig::standalone()).await?; - - // Create and spawn coordinator - let coordinator = CoordinatorActor::new() - .with_system(system.clone()) - .with_num_workers(args.num_workers) - .with_token_counter(token_counter); - - let coordinator_ref = system.spawn_named("coordinator", coordinator).await?; - - // Build benchmark config - let config = BenchmarkConfig { - url: args.url, - api_key: args.api_key, - model_name: args.model_name, - tokenizer_name: Some(tokenizer_name), - max_vus: args.max_vus, - duration_secs: args.duration_secs, - rate: None, - warmup_secs: args.warmup_secs, - benchmark_kind: args.benchmark_kind, - num_rates: args.num_rates, - rates: args.rates, - }; - - let run_id = uuid::Uuid::new_v4().to_string()[..8].to_string(); - - // Start benchmark - let start_msg = StartBenchmark { - config, - run_id: run_id.clone(), - }; - - // Handle ctrl-c - let coordinator_ref_clone = coordinator_ref.clone(); - let run_id_clone = run_id.clone(); - tokio::spawn(async move { - tokio::signal::ctrl_c() - .await - .expect("Failed to listen for ctrl-c"); - info!("Received ctrl-c, stopping benchmark"); - let stop_msg = StopBenchmark { - run_id: run_id_clone, - reason: "User interrupted".to_string(), - }; - let _ = coordinator_ref_clone.tell(stop_msg).await; - }); - - // Run benchmark and wait for completion - let result: AckMessage = coordinator_ref.ask(start_msg).await?; - - if !result.success { - return Err(anyhow::anyhow!("Benchmark failed: {}", result.message)); - } - - // Get final report - let get_report = GetReport { run_id }; - let report: BenchmarkReport = coordinator_ref.ask(get_report).await?; - - // Shutdown - system.shutdown().await?; - - Ok(report) -} - -/// Run a simple throughput test -/// -/// Convenience function for running a basic throughput benchmark. -/// -/// # Arguments -/// -/// * `url` - Target URL -/// * `model_name` - Model name (also used as tokenizer name) -/// * `max_vus` - Maximum concurrent requests -/// * `duration_secs` - Test duration in seconds -pub async fn run_throughput_test( - url: &str, - model_name: &str, - max_vus: u64, - duration_secs: u64, -) -> anyhow::Result { - let args = BenchmarkArgs { - url: url.to_string(), - model_name: model_name.to_string(), - max_vus, - duration_secs, - warmup_secs: 10, - benchmark_kind: "throughput".to_string(), - ..Default::default() - }; - run_benchmark(args).await -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_benchmark_args_default() { - let args = BenchmarkArgs::default(); - assert_eq!(args.url, "http://localhost:8000"); - assert_eq!(args.model_name, "gpt2"); - assert_eq!(args.max_vus, 128); - assert_eq!(args.duration_secs, 120); - assert_eq!(args.warmup_secs, 30); - assert_eq!(args.benchmark_kind, "throughput"); - assert!(args.api_key.is_empty()); - assert!(args.tokenizer_name.is_none()); - assert!(args.hf_token.is_none()); - assert!(args.rates.is_none()); - assert_eq!(args.num_rates, 10); - assert_eq!(args.num_workers, 4); - } - - #[test] - fn test_benchmark_args_custom() { - let args = BenchmarkArgs { - url: "http://example.com:8080".to_string(), - api_key: "secret".to_string(), - model_name: "llama".to_string(), - tokenizer_name: Some("meta-llama/Llama-2".to_string()), - hf_token: Some("hf_token".to_string()), - max_vus: 64, - duration_secs: 60, - warmup_secs: 15, - benchmark_kind: "sweep".to_string(), - num_rates: 5, - rates: Some(vec![1.0, 2.0, 3.0]), - num_workers: 8, - }; - - assert_eq!(args.url, "http://example.com:8080"); - assert_eq!(args.api_key, "secret"); - assert_eq!(args.model_name, "llama"); - assert_eq!(args.tokenizer_name, Some("meta-llama/Llama-2".to_string())); - assert_eq!(args.max_vus, 64); - assert_eq!(args.rates, Some(vec![1.0, 2.0, 3.0])); - } - - #[test] - fn test_parse_duration_seconds() { - let duration = parse_duration("120s").unwrap(); - assert_eq!(duration.as_secs(), 120); - } - - #[test] - fn test_parse_duration_minutes() { - let duration = parse_duration("2m").unwrap(); - assert_eq!(duration.as_secs(), 120); - } - - #[test] - fn test_parse_duration_hours() { - let duration = parse_duration("1h").unwrap(); - assert_eq!(duration.as_secs(), 3600); - } - - #[test] - fn test_parse_duration_milliseconds() { - let duration = parse_duration("500ms").unwrap(); - assert_eq!(duration.as_millis(), 500); - } - - #[test] - fn test_parse_duration_combined() { - let duration = parse_duration("1h30m").unwrap(); - assert_eq!(duration.as_secs(), 5400); - } - - #[test] - fn test_parse_duration_invalid() { - assert!(parse_duration("invalid").is_err()); - assert!(parse_duration("abc123").is_err()); - } -} diff --git a/crates/pulsing-bench/src/tokenizer.rs b/crates/pulsing-bench/src/tokenizer.rs deleted file mode 100644 index 60d7e8c26..000000000 --- a/crates/pulsing-bench/src/tokenizer.rs +++ /dev/null @@ -1,365 +0,0 @@ -//! Tokenizer service for accurate token counting -//! -//! This module provides tokenizer functionality using HuggingFace tokenizers -//! for accurate input/output token counting. - -use std::sync::Arc; -use tokenizers::{FromPretrainedParameters, Tokenizer}; -use tracing::{info, warn}; - -/// Tokenizer service for token counting -#[derive(Clone)] -pub struct TokenizerService { - tokenizer: Arc, - model_name: String, -} - -impl TokenizerService { - /// Create a new tokenizer service from a HuggingFace model name - /// - /// # Arguments - /// * `model_name` - HuggingFace model name (e.g., "Qwen/Qwen3-0.6B") - /// * `hf_token` - Optional HuggingFace token for private models - pub fn from_pretrained(model_name: &str, hf_token: Option) -> anyhow::Result { - info!("Loading tokenizer for model: {}", model_name); - - let params = FromPretrainedParameters { - token: hf_token, - ..Default::default() - }; - - let tokenizer = Tokenizer::from_pretrained(model_name, Some(params)) - .map_err(|e| anyhow::anyhow!("Failed to load tokenizer for {}: {}", model_name, e))?; - - info!("Tokenizer loaded successfully for {}", model_name); - - Ok(Self { - tokenizer: Arc::new(tokenizer), - model_name: model_name.to_string(), - }) - } - - /// Count tokens in a text string - pub fn count_tokens(&self, text: &str) -> u64 { - match self.tokenizer.encode(text, false) { - Ok(encoding) => encoding.get_ids().len() as u64, - Err(e) => { - warn!("Failed to encode text: {}, using estimate", e); - // Fallback to rough estimate - (text.len() / 4) as u64 - } - } - } - - /// Encode text to token IDs - pub fn encode(&self, text: &str) -> anyhow::Result> { - let encoding = self - .tokenizer - .encode(text, false) - .map_err(|e| anyhow::anyhow!("Failed to encode: {}", e))?; - Ok(encoding.get_ids().to_vec()) - } - - /// Decode token IDs to text - pub fn decode(&self, ids: &[u32]) -> anyhow::Result { - self.tokenizer - .decode(ids, true) - .map_err(|e| anyhow::anyhow!("Failed to decode: {}", e)) - } - - /// Get the model name - pub fn model_name(&self) -> &str { - &self.model_name - } - - /// Get vocabulary size - pub fn vocab_size(&self) -> usize { - self.tokenizer.get_vocab_size(true) - } -} - -/// Fallback tokenizer that uses character-based estimation -/// when no real tokenizer is available -#[derive(Clone, Default)] -pub struct EstimateTokenizer; - -impl EstimateTokenizer { - /// Estimate token count based on word count - /// Assumes roughly 1.3 tokens per word (common for English text) - pub fn count_tokens(&self, text: &str) -> u64 { - let spaces = text.chars().filter(|c| c.is_whitespace()).count(); - let words = spaces + 1; - - // Rough heuristic: ~1.3 tokens per word for English - let estimate = (words as f64 * 1.3).ceil() as u64; - - // Ensure at least 1 token - estimate.max(1) - } -} - -/// Token counter enum that can be either a real tokenizer or an estimator -#[derive(Clone)] -pub enum TokenCounter { - /// Real HuggingFace tokenizer - Real(TokenizerService), - /// Estimation-based counter (fallback) - Estimate(EstimateTokenizer), -} - -impl TokenCounter { - /// Create a real tokenizer - pub fn real(model_name: &str, hf_token: Option) -> anyhow::Result { - Ok(Self::Real(TokenizerService::from_pretrained( - model_name, hf_token, - )?)) - } - - /// Create an estimate-based tokenizer - pub fn estimate() -> Self { - Self::Estimate(EstimateTokenizer) - } - - /// Count tokens in text - pub fn count_tokens(&self, text: &str) -> u64 { - match self { - Self::Real(t) => t.count_tokens(text), - Self::Estimate(e) => e.count_tokens(text), - } - } - - /// Check if this is a real tokenizer - pub fn is_real(&self) -> bool { - matches!(self, Self::Real(_)) - } -} - -impl Default for TokenCounter { - fn default() -> Self { - Self::Estimate(EstimateTokenizer) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_estimate_tokenizer() { - let estimator = EstimateTokenizer; - - // Simple English text (5 words -> ~7 tokens) - let text = "Hello, how are you today?"; - let tokens = estimator.count_tokens(text); - assert!(tokens >= 5); - - // Empty text (0 spaces -> 1 word -> ~2 tokens) - let empty = ""; - let tokens = estimator.count_tokens(empty); - assert!(tokens >= 1); - - // Long text (12 words -> ~16 tokens) - let long_text = "This is a longer piece of text that should have more tokens."; - let tokens = estimator.count_tokens(long_text); - assert!(tokens > 10); - } - - #[test] - fn test_token_counter_default() { - let counter = TokenCounter::default(); - assert!(!counter.is_real()); - - let tokens = counter.count_tokens("Hello world"); - assert!(tokens > 0); - } - - #[test] - fn test_estimate_tokenizer_default() { - let estimator = EstimateTokenizer; - let tokens = estimator.count_tokens("test"); - assert!(tokens >= 1); - } - - #[test] - fn test_estimate_tokenizer_single_word() { - let estimator = EstimateTokenizer; - // Single word with no spaces = 1 word * 1.3 = 2 tokens (ceil) - let tokens = estimator.count_tokens("Hello"); - assert_eq!(tokens, 2); - } - - #[test] - fn test_estimate_tokenizer_multiple_spaces() { - let estimator = EstimateTokenizer; - // "a b c" has 4 spaces, so 5 words * 1.3 = 6.5 -> 7 tokens - let tokens = estimator.count_tokens("a b c"); - assert!(tokens >= 5); - } - - #[test] - fn test_estimate_tokenizer_whitespace_types() { - let estimator = EstimateTokenizer; - // Text with tabs and newlines - let text = "Hello\tworld\ntest"; - let tokens = estimator.count_tokens(text); - // 2 whitespace chars = 3 words * 1.3 = 4 tokens - assert!(tokens >= 3); - } - - #[test] - fn test_estimate_tokenizer_unicode() { - let estimator = EstimateTokenizer; - // Chinese text - let tokens = estimator.count_tokens("你好 世界"); - assert!(tokens >= 2); - - // Emojis - let tokens = estimator.count_tokens("Hello 👋 World 🌍"); - // 3 spaces = 4 words * 1.3 = 6 tokens - assert!(tokens >= 4); - } - - #[test] - fn test_estimate_tokenizer_min_one() { - let estimator = EstimateTokenizer; - // Even empty string should return at least 1 token - let tokens = estimator.count_tokens(""); - assert!(tokens >= 1); - } - - #[test] - fn test_token_counter_estimate() { - let counter = TokenCounter::estimate(); - assert!(!counter.is_real()); - - let tokens = counter.count_tokens("Hello world"); - assert!(tokens > 0); - } - - #[test] - fn test_token_counter_is_real() { - let estimate_counter = TokenCounter::estimate(); - assert!(!estimate_counter.is_real()); - - let default_counter = TokenCounter::default(); - assert!(!default_counter.is_real()); - } - - #[test] - fn test_token_counter_estimate_consistency() { - let counter = TokenCounter::estimate(); - - let text = "This is a test sentence for token counting."; - let tokens1 = counter.count_tokens(text); - let tokens2 = counter.count_tokens(text); - - // Same text should always produce same count - assert_eq!(tokens1, tokens2); - } - - #[test] - fn test_token_counter_estimate_different_texts() { - let counter = TokenCounter::estimate(); - - let short = "Hello"; - let long = "Hello world this is a much longer sentence with more words"; - - let short_tokens = counter.count_tokens(short); - let long_tokens = counter.count_tokens(long); - - // Longer text should have more tokens - assert!(long_tokens > short_tokens); - } - - #[test] - fn test_token_counter_clone() { - let counter1 = TokenCounter::estimate(); - let counter2 = counter1.clone(); - - // Both should produce same results - let text = "Test text"; - assert_eq!(counter1.count_tokens(text), counter2.count_tokens(text)); - } - - #[test] - fn test_estimate_tokenizer_clone() { - let est1 = EstimateTokenizer; - let est2 = est1.clone(); - - let text = "Test"; - assert_eq!(est1.count_tokens(text), est2.count_tokens(text)); - } - - #[test] - fn test_estimate_tokenizer_very_long_text() { - let estimator = EstimateTokenizer; - - // Generate a very long text - let long_text = "word ".repeat(1000); - let tokens = estimator.count_tokens(&long_text); - - // Should be approximately 1000 * 1.3 = 1300 tokens - assert!(tokens >= 1000); - assert!(tokens <= 1500); - } - - #[test] - fn test_estimate_tokenizer_special_characters() { - let estimator = EstimateTokenizer; - - // Text with special characters but no spaces - let text = "hello@world.com"; - let tokens = estimator.count_tokens(text); - // 0 spaces = 1 word * 1.3 = 2 tokens - assert_eq!(tokens, 2); - } - - #[test] - fn test_estimate_tokenizer_only_spaces() { - let estimator = EstimateTokenizer; - - // Only spaces - let text = " "; - let tokens = estimator.count_tokens(text); - // 5 spaces = 6 words * 1.3 = 8 tokens - assert!(tokens >= 6); - } - - // Note: Real tokenizer tests require network access and are marked as ignored - // They can be run manually with: cargo test -- --ignored - - #[test] - #[ignore] - fn test_real_tokenizer_gpt2() { - // This test requires network access to download tokenizer - let result = TokenizerService::from_pretrained("gpt2", None); - if let Ok(tokenizer) = result { - assert_eq!(tokenizer.model_name(), "gpt2"); - - // Test token counting - let text = "Hello, world!"; - let tokens = tokenizer.count_tokens(text); - assert!(tokens > 0); - - // Test encode/decode - let encoded = tokenizer.encode(text).unwrap(); - assert!(!encoded.is_empty()); - - let decoded = tokenizer.decode(&encoded).unwrap(); - assert!(!decoded.is_empty()); - } - } - - #[test] - #[ignore] - fn test_token_counter_real() { - // This test requires network access - let result = TokenCounter::real("gpt2", None); - if let Ok(counter) = result { - assert!(counter.is_real()); - - let tokens = counter.count_tokens("Hello world"); - assert!(tokens > 0); - } - } -} diff --git a/crates/pulsing-cli/Cargo.toml b/crates/pulsing-cli/Cargo.toml index 8abc55079..08bc5c4a4 100644 --- a/crates/pulsing-cli/Cargo.toml +++ b/crates/pulsing-cli/Cargo.toml @@ -7,11 +7,6 @@ license.workspace = true description = "Pulsing command-line interface (RustPython embedded VM)" repository.workspace = true -# Path B: RustPython VM (no PyO3 / no libpython). Path A remains maturin + extension-module. -[features] -default = ["gui"] -gui = ["dep:pulsing-gui"] - [[bin]] name = "pulsing" path = "src/main.rs" @@ -19,8 +14,6 @@ path = "src/main.rs" [dependencies] anyhow = { workspace = true } clap = { version = "4", features = ["derive"] } -pulsing-forge = { path = "../pulsing-forge" } -pulsing-gui = { path = "../pulsing-gui", optional = true } pulsing-rpymod = { path = "../pulsing-rpymod" } pulsing-workspace = { path = "../pulsing-workspace" } serde_json = { workspace = true } diff --git a/crates/pulsing-cli/README.md b/crates/pulsing-cli/README.md index 5b631f361..f048c8908 100644 --- a/crates/pulsing-cli/README.md +++ b/crates/pulsing-cli/README.md @@ -1,63 +1,27 @@ # pulsing-cli -Single-binary CLI for Pulsing (**Path B**). - -## Layout - -All **interactive UX** lives in this crate (`src/session/`). Downstream crates stay headless: - -| Crate | Responsibility | -|-------|----------------| -| **pulsing-cli** | clap routing, immersive session, slash commands, plain render (future TUI/GUI) | -| **pulsing-forge** | agent loop, tools, LLM, sandbox | -| **pulsing-workspace** | init, journal, checkpoint, rollback | -| **pulsing-rpymod** | RustPython bindings for extension-mode workflows | - -``` -pulsing-cli/src/ - main.rs # clap only → dispatch - session/ # ★ interaction kernel - mod.rs # unified REPL loop - commands.rs # /help, /rollback, … - mode.rs # safe | workflow - input.rs # stdin (→ reedline later) - render.rs # plain text (→ ratatui / egui later) - config.rs # provider, workspace LLM config - workspace.rs # history, checkpoint, workflow list - codex.rs # thin entry → session::run_safe - workflow.rs # thin entry → session::run_workflow - embed/ # RustPython extension mode - workspace.rs # pulsing init/history/… subcommands -``` - -## Modes - -| Mode | Commands | Python | -|------|----------|--------| -| **Safe** (default) | `pulsing`, `pulsing "task"`, `pulsing agent` | None | -| **Extension** | `pulsing run`, `pulsing workflow` | RustPython + embedded sources | - -Immersive session: `/help`, `/exit`, agent tasks, workflow rerun — all via `session/`. - -## Build +RustPython-based actor CLI and workspace tools. ```bash -just build-binary release=release -# target/release/pulsing (~40MB release) +just build-binary +pulsing init --template minimal +pulsing run # execute .pulsing/workflows/example.py once +pulsing run my_workflow.py +pulsing history +pulsing checkpoint -m "working state" +pulsing rollback +pulsing actor my_app.Counter --addr 127.0.0.1:8000 +pulsing inspect actors --endpoint 127.0.0.1:8000 ``` -## Usage - -```bash -pulsing init -g "Python CLI with pytest" -pulsing # session (safe) -pulsing run # workflow → session -pulsing /help # inside session -``` +Workspace commands run in Rust. Workflow scripts and actor/inspect commands use +the embedded RustPython VM and the Python sources. Set `PULSING_REPO_ROOT` when +running outside the checkout. -## Environment +There is no default agent session, tool REPL, LLM provider configuration, or GUI. +Running without a subcommand prints help. -| Variable | Purpose | -|----------|---------| -| `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` | Live LLM providers | -| `PULSING_REPO_ROOT` | Repo root for extension-mode `sys.path` | +Build with the checked-in `Cargo.lock` (`cargo build --locked -p pulsing-cli`). +RustPython 0.5 needs the pinned libc and the shared malachite-bigint 0.9 dependency +used by its VM and pymath; unconstrained re-resolution can select incompatible +upstream versions. diff --git a/crates/pulsing-cli/src/codex.rs b/crates/pulsing-cli/src/codex.rs deleted file mode 100644 index ccb654cf5..000000000 --- a/crates/pulsing-cli/src/codex.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! Codex-style entry — delegates interactive UX to [`crate::session`]. - -use std::process::ExitCode; - -use anyhow::{Context, Result}; -use pulsing_workspace::{find_workspace_root, init_workspace, InitOptions, Template}; - -#[derive(Debug, Clone)] -pub struct CodexOptions { - pub provider: Option, - pub model: Option, - pub auto_init: bool, -} - -pub fn run_default(prompt: Option<&str>, opts: CodexOptions) -> Result { - crate::session::run_safe(opts, prompt) -} - -pub fn ensure_workspace(auto_init: bool) -> Result<()> { - if find_workspace_root(None).is_some() { - return Ok(()); - } - if !auto_init { - eprintln!("tip: `pulsing init` to bootstrap a workspace (or pass --init)"); - return Ok(()); - } - let root = std::env::current_dir().context("cwd")?; - init_workspace( - &root, - InitOptions { - template: Template::Agent, - name: None, - force: false, - guide: None, - }, - )?; - eprintln!("initialized workspace at {}", root.display()); - Ok(()) -} diff --git a/crates/pulsing-cli/src/embed/mod.rs b/crates/pulsing-cli/src/embed/mod.rs index 4f098d796..d55ecd0fa 100644 --- a/crates/pulsing-cli/src/embed/mod.rs +++ b/crates/pulsing-cli/src/embed/mod.rs @@ -3,12 +3,3 @@ mod python; pub use python::{delegate_to_python_cli, extension_mode_available, run_workflow_script}; - -#[allow(dead_code)] -pub fn warn_extension_mode() { - eprintln!("{}", crate::help::EXTENSION_MODE_HINT); -} - -pub fn warn_legacy_mode() { - eprintln!("{}", crate::help::LEGACY_HINT); -} diff --git a/crates/pulsing-cli/src/gui/mod.rs b/crates/pulsing-cli/src/gui/mod.rs deleted file mode 100644 index 5f5e20e33..000000000 --- a/crates/pulsing-cli/src/gui/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! Desktop chat GUI — `pulsing gui` (egui). - -use std::process::ExitCode; - -use anyhow::Result; - -use crate::codex::CodexOptions; - -#[cfg(feature = "gui")] -pub fn run(opts: CodexOptions) -> Result { - use crate::codex::ensure_workspace; - use crate::session::config; - - ensure_workspace(opts.auto_init)?; - let agent = config::interactive_config(&opts)?; - pulsing_gui::run(agent)?; - Ok(ExitCode::SUCCESS) -} - -#[cfg(not(feature = "gui"))] -pub fn run(_opts: CodexOptions) -> Result { - anyhow::bail!( - "desktop GUI is not available in this build; rebuild with \ - `cargo build -p pulsing-cli --features gui`" - ) -} diff --git a/crates/pulsing-cli/src/help.rs b/crates/pulsing-cli/src/help.rs index d9db87e97..351214118 100644 --- a/crates/pulsing-cli/src/help.rs +++ b/crates/pulsing-cli/src/help.rs @@ -1,55 +1,3 @@ -//! CLI help text — safe mode vs extension mode. - -pub const ABOUT: &str = "Pulsing — AI application server (single binary)"; - -pub const LONG_ABOUT: &str = "\ -Pulsing ships as one binary with two modes: - - SAFE MODE (default) - Rust agent + Forge tools + workspace journal. No user Python scripts. - pulsing interactive agent - pulsing \"fix the tests\" one-shot task - pulsing init -g \"…\" bootstrap workspace (optional LLM guide) - - EXTENSION MODE (opt-in) - Immersive workflow session — stays in the CLI after success. - pulsing run default workflow (example.py) - pulsing run my_workflow.py explicit script - On failure, returns to the shell with recovery hints. - - Workspace checkpoints (fault tolerance): - pulsing history | checkpoint | rollback - - Desktop GUI (egui): - pulsing gui Desktop chat window (egui) - -Set ANTHROPIC_API_KEY or OPENAI_API_KEY for live models; otherwise demo LLM is used."; - -pub const AFTER_HELP: &str = "\ -Examples: - pulsing init -g \"Python CLI with pytest\" - pulsing \"add error handling to src/main.rs\" - pulsing gui - pulsing run - pulsing rollback - -Workflow failed? You return to the shell — then: - pulsing rollback && pulsing \"fix .pulsing/workflows/example.py\""; - -#[allow(dead_code)] -pub const EXTENSION_MODE_HINT: &str = "\ -note: `pulsing run` opens an immersive workflow session (Codex-like). \ -Safe mode: `pulsing` or `pulsing \"task\"`."; - -pub const EXTENSION_UNAVAILABLE: &str = "\ -extension mode is not available in this build (Python sources not embedded). - -Use safe mode instead — no Python required: - pulsing # interactive agent - pulsing \"your task\" # one-shot - -Developers: set PULSING_REPO_ROOT or run from the Pulsing repository."; - -pub const LEGACY_HINT: &str = "\ -note: legacy Python CLI (actor, inspect, …) — extension mode. \ -Prefer `pulsing` for the Rust agent."; +pub const EXTENSION_UNAVAILABLE: &str = + "Python sources not found. Set PULSING_REPO_ROOT to a Pulsing checkout, \ + or use the installed Python CLI."; diff --git a/crates/pulsing-cli/src/main.rs b/crates/pulsing-cli/src/main.rs index 6bfc8d3ab..9588e5c9e 100644 --- a/crates/pulsing-cli/src/main.rs +++ b/crates/pulsing-cli/src/main.rs @@ -1,10 +1,7 @@ -//! Pulsing CLI — single binary: safe-mode agent + optional Python workflows. +//! Actor CLI and workspace workflows, without an embedded agent product. -mod codex; mod embed; -mod gui; mod help; -mod session; mod workflow; mod workspace; @@ -14,119 +11,38 @@ use std::process::ExitCode; use anyhow::Result; use clap::{Parser, Subcommand}; - -use codex::CodexOptions; use workspace::WorkspaceCommand; #[derive(Parser)] #[command( name = "pulsing", version, - about = help::ABOUT, - long_about = help::LONG_ABOUT, - after_help = help::AFTER_HELP, + about = "Distributed actor runtime and workspace tools" )] struct Cli { #[command(subcommand)] command: Option, - - /// LLM provider: demo, anthropic, openai - #[arg(long, global = true)] - provider: Option, - - /// Model id override - #[arg(long, global = true)] - model: Option, - - /// Create `.pulsing/` automatically if missing (safe mode) - #[arg(long, global = true)] - init: bool, - - /// One-shot task when no subcommand is given (safe mode) - #[arg(trailing_var_arg = true, allow_hyphen_values = true)] - prompt: Vec, } #[derive(Subcommand)] enum Command { - /// Safe mode: LLM agent with Forge tools (no user Python) - Agent(AgentArgs), - /// Bootstrap a Pulsing workspace (`.pulsing/` + journal) - Init { - #[arg(value_name = "DIR")] - dir: Option, - #[arg(long, default_value = "agent")] - template: String, - #[arg(long)] - name: Option, + #[command(flatten)] + Workspace(WorkspaceCommand), + /// Execute a Python workflow once. + #[command(visible_alias = "workflow")] + Run { + script: Option, + /// Explicit one-shot mode (all workflows now run once). #[arg(long)] - force: bool, - /// Natural-language goal — LLM customizes workspace after scaffold - #[arg(short = 'g', long = "guide")] - guide_flag: Option, + batch: bool, #[arg(trailing_var_arg = true, allow_hyphen_values = true)] - guide_words: Vec, - #[arg(long)] - provider: Option, - #[arg(long)] - model: Option, - }, - /// List workspace checkpoints - History, - /// Save a workspace checkpoint - Checkpoint { - #[arg(short, long)] - message: Option, - }, - /// Restore workspace files from a checkpoint - Rollback { revision: Option }, - /// Immersive workflow session (extension mode; stays in CLI on success) - #[command(visible_alias = "workflow")] - Run(RunArgs), - /// Desktop chat UI (egui) - Gui, - /// Low-level Forge tool REPL (safe mode) - Forge { - #[command(subcommand)] - cmd: ForgeCommand, + script_args: Vec, }, - /// Legacy Python CLI (actor, inspect, …) — extension mode + /// Python actor CLI (actor, inspect, examples). #[command(external_subcommand)] Passthrough(Vec), } -#[derive(Parser)] -struct AgentArgs { - /// Task prompt; omit for interactive session - #[arg(trailing_var_arg = true, allow_hyphen_values = true)] - prompt: Vec, -} - -#[derive(Subcommand)] -enum ForgeCommand { - /// Interactive Forge tool REPL - Repl { - #[arg(long, default_value = ".")] - cwd: PathBuf, - #[arg(long, default_value = "off")] - sandbox: String, - #[arg(long)] - dangerously_disable_sandbox: bool, - }, -} - -#[derive(Parser)] -struct RunArgs { - /// Workflow script (default: `.pulsing/workflows/example.py`) - script: Option, - /// Run script and exit (no interactive session) - #[arg(long)] - batch: bool, - /// Arguments passed to the script - #[arg(trailing_var_arg = true, allow_hyphen_values = true)] - script_args: Vec, -} - fn main() -> ExitCode { match run() { Ok(code) => code, @@ -139,106 +55,33 @@ fn main() -> ExitCode { fn run() -> Result { let cli = Cli::parse(); - let codex_opts = CodexOptions { - provider: cli.provider, - model: cli.model, - auto_init: cli.init, - }; - match cli.command { - Some(Command::Agent(args)) => { - let prompt = join_prompt(args.prompt); - codex::run_default(prompt.as_deref(), codex_opts) - } - Some(Command::Init { - dir, - template, - name, - force, - guide_flag, - guide_words, - provider, - model, - }) => { - workspace::run_or_exit(WorkspaceCommand::Init { - dir, - template, - name, - force, - guide_flag, - guide_words, - provider, - model, - }); - Ok(ExitCode::SUCCESS) - } - Some(Command::History) => { - workspace::run_or_exit(WorkspaceCommand::History); - Ok(ExitCode::SUCCESS) - } - Some(Command::Checkpoint { message }) => { - workspace::run_or_exit(WorkspaceCommand::Checkpoint { message }); - Ok(ExitCode::SUCCESS) - } - Some(Command::Rollback { revision }) => { - workspace::run_or_exit(WorkspaceCommand::Rollback { revision }); - Ok(ExitCode::SUCCESS) - } - Some(Command::Run(args)) => { - let script = workflow::resolve_script(args.script)?; - workflow::run_session(workflow::WorkflowSession { - script, - script_args: args.script_args, - codex: codex_opts, - batch: args.batch, - }) - } - Some(Command::Gui) => gui::run(codex_opts), - Some(Command::Forge { - cmd: - ForgeCommand::Repl { - cwd, - sandbox, - dangerously_disable_sandbox, - }, + Some(Command::Workspace(cmd)) => workspace::run(cmd)?, + Some(Command::Run { + script, + script_args, + batch: _, }) => { - pulsing_forge::cli::run_repl(pulsing_forge::cli::ReplCliArgs { - cwd, - sandbox, - dangerously_disable_sandbox, - approve: "auto".into(), - trace: None, - record: None, - replay_all: false, - dry_run: false, - verify: false, - })?; - Ok(ExitCode::SUCCESS) + let script = workflow::resolve_script(script)?; + embed::run_workflow_script(&script, &script_args)?; } - Some(Command::Passthrough(os_args)) => { - embed::warn_legacy_mode(); + Some(Command::Passthrough(args)) => { if !embed::extension_mode_available() { anyhow::bail!("{}", help::EXTENSION_UNAVAILABLE.trim()); } - let args: Vec = os_args + let args = args .into_iter() .map(|s| s.to_string_lossy().into_owned()) - .collect(); - embed::delegate_to_python_cli(&args) + .collect::>(); + return embed::delegate_to_python_cli(&args); } None => { - let prompt = join_prompt(cli.prompt); - codex::run_default(prompt.as_deref(), codex_opts) + use clap::CommandFactory; + Cli::command().print_help()?; + println!(); } } -} - -fn join_prompt(words: Vec) -> Option { - if words.is_empty() { - None - } else { - Some(words.join(" ")) - } + Ok(ExitCode::SUCCESS) } #[cfg(test)] @@ -246,63 +89,37 @@ mod tests { use super::*; #[test] - fn parse_oneshot_prompt() { - let cli = Cli::parse_from(["pulsing", "list", "README", "files"]); - assert!(cli.command.is_none()); - assert_eq!(cli.prompt, vec!["list", "README", "files"]); - } - - #[test] - fn parse_agent_subcommand() { - let cli = Cli::parse_from(["pulsing", "agent", "fix", "tests"]); - let Command::Agent(AgentArgs { prompt }) = cli.command.expect("agent") else { - panic!("expected Agent"); - }; - assert_eq!(prompt, vec!["fix", "tests"]); - } - - #[test] - fn parse_init_with_guide() { - let cli = Cli::parse_from(["pulsing", "init", "-g", "Python ML project"]); - let Command::Init { guide_flag, .. } = cli.command.expect("init") else { - panic!("expected Init"); - }; - assert_eq!(guide_flag.as_deref(), Some("Python ML project")); + fn parse_workspace_init() { + let cli = Cli::parse_from(["pulsing", "init", "--template", "minimal"]); + assert!(matches!( + cli.command, + Some(Command::Workspace(WorkspaceCommand::Init { .. })) + )); } #[test] fn parse_workflow_alias() { let cli = Cli::parse_from(["pulsing", "workflow", "app.py", "arg"]); - let Command::Run(RunArgs { + let Some(Command::Run { script, script_args, - batch, - }) = cli.command.expect("run") + .. + }) = cli.command else { panic!("expected Run"); }; assert_eq!(script, Some(PathBuf::from("app.py"))); assert_eq!(script_args, vec!["arg"]); - assert!(!batch); } #[test] - fn parse_run_without_script() { - let cli = Cli::parse_from(["pulsing", "run"]); - let Command::Run(RunArgs { script, .. }) = cli.command.expect("run") else { - panic!("expected Run"); - }; - assert!(script.is_none()); + fn actor_commands_pass_through() { + let cli = Cli::parse_from(["pulsing", "actor", "my_app.Counter"]); + assert!(matches!(cli.command, Some(Command::Passthrough(_)))); } #[test] - fn parse_forge_repl() { - let cli = Cli::parse_from(["pulsing", "forge", "repl"]); - let Command::Forge { - cmd: ForgeCommand::Repl { .. }, - } = cli.command.expect("forge") - else { - panic!("expected forge repl"); - }; + fn init_rejects_llm_options() { + assert!(Cli::try_parse_from(["pulsing", "init", "--provider", "demo"]).is_err()); } } diff --git a/crates/pulsing-cli/src/session/commands.rs b/crates/pulsing-cli/src/session/commands.rs deleted file mode 100644 index 3bfbe1cbb..000000000 --- a/crates/pulsing-cli/src/session/commands.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! Slash commands and legacy aliases (parsed in pulsing-cli only). - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum InputAction { - Help, - Mode, - Exit, - History, - Checkpoint { message: Option }, - Rollback { revision: Option }, - WorkflowList, - WorkflowRun { script: Option }, - RerunWorkflow, - AgentTask { prompt: String }, -} - -pub fn parse_line(line: &str) -> InputAction { - let trimmed = line.trim(); - if trimmed.is_empty() { - return InputAction::AgentTask { - prompt: String::new(), - }; - } - - if let Some(rest) = trimmed.strip_prefix('/') { - return parse_slash(rest); - } - - // Legacy aliases (discoverable via /help). - match trimmed.to_lowercase().as_str() { - "exit" | "quit" | "q" => InputAction::Exit, - "rerun" | "run" => InputAction::RerunWorkflow, - "rollback" => InputAction::Rollback { revision: None }, - _ => InputAction::AgentTask { - prompt: trimmed.to_string(), - }, - } -} - -fn parse_slash(rest: &str) -> InputAction { - let mut parts = rest.split_whitespace(); - let cmd = parts.next().unwrap_or("").to_lowercase(); - match cmd.as_str() { - "help" | "h" | "?" => InputAction::Help, - "mode" => InputAction::Mode, - "exit" | "quit" | "q" => InputAction::Exit, - "history" => InputAction::History, - "checkpoint" | "cp" => { - let msg = parts.collect::>().join(" "); - InputAction::Checkpoint { - message: if msg.is_empty() { None } else { Some(msg) }, - } - } - "rollback" | "rb" => { - let rev = parts.next().map(str::to_string); - InputAction::Rollback { revision: rev } - } - "workflow" | "wf" => { - let sub = parts.next().unwrap_or("list").to_lowercase(); - match sub.as_str() { - "list" => InputAction::WorkflowList, - "run" => { - let script = parts.next().map(str::to_string); - InputAction::WorkflowRun { script } - } - _ => InputAction::Help, - } - } - _ => InputAction::Help, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn slash_help() { - assert_eq!(parse_line("/help"), InputAction::Help); - } - - #[test] - fn slash_checkpoint_with_message() { - assert_eq!( - parse_line("/checkpoint after deploy"), - InputAction::Checkpoint { - message: Some("after deploy".into()), - } - ); - } - - #[test] - fn legacy_rerun() { - assert_eq!(parse_line("rerun"), InputAction::RerunWorkflow); - } - - #[test] - fn agent_task() { - match parse_line("fix tests") { - InputAction::AgentTask { prompt } => assert_eq!(prompt, "fix tests"), - _ => panic!("expected agent task"), - } - } -} diff --git a/crates/pulsing-cli/src/session/config.rs b/crates/pulsing-cli/src/session/config.rs deleted file mode 100644 index 7406c787a..000000000 --- a/crates/pulsing-cli/src/session/config.rs +++ /dev/null @@ -1,72 +0,0 @@ -//! Session configuration (LLM provider, workspace paths). - -use anyhow::{Context, Result}; -use pulsing_forge::InteractiveConfig; -use pulsing_workspace::find_workspace_root; - -use crate::codex::CodexOptions; - -pub fn interactive_config(opts: &CodexOptions) -> Result { - let mut cfg = workspace_interactive_config()?; - if let Some(ref p) = opts.provider { - cfg.provider = p.clone(); - cfg.model = pulsing_forge::default_model_for_provider(&cfg.provider); - } - if let Some(ref m) = opts.model { - cfg.model = m.clone(); - } - Ok(cfg) -} - -fn workspace_interactive_config() -> Result { - let cwd = std::env::current_dir().context("cwd")?; - let mut cfg = InteractiveConfig { - cwd: cwd.clone(), - ..InteractiveConfig::default() - }; - - if let Some(root) = find_workspace_root(Some(&cwd)) { - let cluster_path = root.join(".pulsing").join("cluster.json"); - if cluster_path.is_file() { - let data: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(&cluster_path)?)?; - if let Some(p) = data.get("provider").and_then(|v| v.as_str()) { - if !p.is_empty() { - cfg.provider = p.to_string(); - } - } - if let Some(m) = data.get("model").and_then(|v| v.as_str()) { - if !m.is_empty() { - cfg.model = m.to_string(); - } - } else { - cfg.model = pulsing_forge::default_model_for_provider(&cfg.provider); - } - } - } - - if !provider_has_credentials(&cfg.provider) { - cfg.provider = pulsing_forge::default_provider(); - cfg.model = pulsing_forge::default_model_for_provider(&cfg.provider); - } - Ok(cfg) -} - -fn provider_has_credentials(provider: &str) -> bool { - match provider.trim().to_lowercase().as_str() { - "demo" => true, - "openai" => std::env::var("OPENAI_API_KEY") - .map(|k| !k.is_empty()) - .unwrap_or(false), - _ => std::env::var("ANTHROPIC_API_KEY") - .map(|k| !k.is_empty()) - .unwrap_or(false), - } -} - -pub fn tokio_runtime() -> Result { - tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .context("tokio runtime") -} diff --git a/crates/pulsing-cli/src/session/input.rs b/crates/pulsing-cli/src/session/input.rs deleted file mode 100644 index a5c76a966..000000000 --- a/crates/pulsing-cli/src/session/input.rs +++ /dev/null @@ -1,28 +0,0 @@ -//! Line input (plain stdin; reedline/TUI can replace this module later). - -use std::io::{self, Write}; - -pub fn read_line(prompt: &str) -> io::Result> { - print!("{prompt}"); - let _ = io::stdout().flush(); - let mut line = String::new(); - let n = io::stdin().read_line(&mut line)?; - if n == 0 { - return Ok(None); - } - Ok(Some(line)) -} - -pub fn confirm(prompt: &str, default_no: bool) -> io::Result { - eprint!("{prompt}"); - let _ = io::stderr().flush(); - let mut line = String::new(); - if io::stdin().read_line(&mut line)? == 0 { - return Ok(false); - } - let answer = line.trim().to_lowercase(); - if answer.is_empty() { - return Ok(!default_no); - } - Ok(matches!(answer.as_str(), "y" | "yes" | "retry")) -} diff --git a/crates/pulsing-cli/src/session/mod.rs b/crates/pulsing-cli/src/session/mod.rs deleted file mode 100644 index f7e392e20..000000000 --- a/crates/pulsing-cli/src/session/mod.rs +++ /dev/null @@ -1,239 +0,0 @@ -//! Unified immersive session — all interactive UX stays in pulsing-cli. -//! -//! pulsing-forge provides agent/tools; pulsing-workspace provides journal; -//! this module owns prompts, slash commands, workflow orchestration, and rendering. - -mod commands; -pub mod config; -mod input; -mod mode; -mod render; -pub mod workspace; - -use std::path::PathBuf; -use std::process::ExitCode; - -use anyhow::{Context, Result}; -use pulsing_forge::{run_oneshot, AgentConfig, InteractiveConfig, LocalForgeClient, SessionId}; - -use commands::{parse_line, InputAction}; -use mode::SessionMode; - -use crate::codex::{ensure_workspace, CodexOptions}; -use crate::embed; - -const PROMPT: &str = "› "; - -/// Entry: `pulsing` / `pulsing agent` (safe mode). -pub fn run_safe(opts: CodexOptions, initial_prompt: Option<&str>) -> Result { - ensure_workspace(opts.auto_init)?; - - let rt = config::tokio_runtime()?; - let agent_cfg = config::interactive_config(&opts)?; - - if let Some(text) = initial_prompt.filter(|s| !s.trim().is_empty()) { - let reply = rt.block_on(run_oneshot(agent_cfg, text.trim()))?; - println!("{reply}"); - return Ok(ExitCode::SUCCESS); - } - - let mut state = SessionState { - mode: SessionMode::Safe, - agent: agent_cfg, - }; - run_loop(&mut state)?; - Ok(ExitCode::SUCCESS) -} - -/// Entry: `pulsing run` (workflow then immersive session, unless ``batch``). -pub fn run_workflow( - opts: CodexOptions, - script: PathBuf, - script_args: Vec, - batch: bool, -) -> Result { - ensure_workspace(opts.auto_init)?; - require_extension_mode()?; - - let script = script - .canonicalize() - .with_context(|| format!("workflow not found: {}", script.display()))?; - - if batch { - return match embed::run_workflow_script(&script, &script_args) { - Ok(()) => Ok(ExitCode::SUCCESS), - Err(err) => { - render::print_workflow_err(&err); - Ok(ExitCode::FAILURE) - } - }; - } - - let agent_cfg = config::interactive_config(&opts)?; - - render::print_workflow_start(&script); - match embed::run_workflow_script(&script, &script_args) { - Ok(()) => { - render::print_workflow_ok(); - let mut state = SessionState { - mode: SessionMode::WorkflowIdle { - script: script.clone(), - args: script_args.clone(), - }, - agent: agent_cfg, - }; - run_loop(&mut state)?; - Ok(ExitCode::SUCCESS) - } - Err(err) => { - render::print_workflow_err(&err); - render::print_failure_recovery(&script); - if input::confirm("› retry workflow? [y/N] ", true)? { - return run_workflow(opts, script, script_args, false); - } - Ok(ExitCode::FAILURE) - } - } -} - -struct SessionState { - mode: SessionMode, - agent: InteractiveConfig, -} - -fn run_loop(state: &mut SessionState) -> Result<()> { - let rt = config::tokio_runtime()?; - let forge = LocalForgeClient::default(); - let forge_session = rt.block_on(forge.create_session(agent_config(&state.agent)))?; - render::print_session_header(&state.mode, &state.agent); - - while let Some(line) = input::read_line(PROMPT)? { - let action = parse_line(&line); - match dispatch(&rt, &forge, &forge_session, state, action)? { - LoopControl::Continue => {} - LoopControl::Break => break, - } - } - Ok(()) -} - -enum LoopControl { - Continue, - Break, -} - -fn dispatch( - rt: &tokio::runtime::Runtime, - forge: &LocalForgeClient, - forge_session: &SessionId, - state: &mut SessionState, - action: InputAction, -) -> Result { - match action { - InputAction::AgentTask { prompt } if prompt.is_empty() => Ok(LoopControl::Continue), - InputAction::Help => { - render::print_help(&state.mode); - Ok(LoopControl::Continue) - } - InputAction::Mode => { - render::print_mode(&state.mode); - Ok(LoopControl::Continue) - } - InputAction::Exit => Ok(LoopControl::Break), - InputAction::History => { - workspace::print_history()?; - Ok(LoopControl::Continue) - } - InputAction::Checkpoint { message } => { - match workspace::save_checkpoint(message) { - Ok(msg) => eprintln!("{msg}\n"), - Err(err) => eprintln!("checkpoint failed: {err:#}\n"), - } - Ok(LoopControl::Continue) - } - InputAction::Rollback { revision } => { - match workspace::do_rollback(revision) { - Ok(msg) => eprintln!("{msg}\n"), - Err(err) => eprintln!("rollback failed: {err:#}\n"), - } - Ok(LoopControl::Continue) - } - InputAction::WorkflowList => { - match workspace::list_workflow_scripts() { - Ok(scripts) => { - if scripts.is_empty() { - eprintln!("no workflows in `.pulsing/workflows/`\n"); - } else { - for p in scripts { - eprintln!(" {}", p.display()); - } - eprintln!(); - } - } - Err(err) => eprintln!("{err:#}\n"), - } - Ok(LoopControl::Continue) - } - InputAction::WorkflowRun { script } => { - require_extension_mode()?; - let path = workspace::resolve_workflow_script(script.as_deref())?; - let args = match &state.mode { - SessionMode::WorkflowIdle { args, .. } if script.is_none() => args.clone(), - _ => Vec::new(), - }; - render::print_workflow_start(&path); - match embed::run_workflow_script(&path, &args) { - Ok(()) => { - render::print_workflow_ok(); - state.mode = SessionMode::WorkflowIdle { script: path, args }; - } - Err(err) => { - render::print_workflow_err(&err); - render::print_failure_recovery(&path); - } - } - Ok(LoopControl::Continue) - } - InputAction::RerunWorkflow => match &state.mode { - SessionMode::WorkflowIdle { script, args } => { - render::print_workflow_start(script); - match embed::run_workflow_script(script, args) { - Ok(()) => render::print_workflow_ok(), - Err(err) => { - render::print_workflow_err(&err); - render::print_failure_recovery(script); - } - } - Ok(LoopControl::Continue) - } - SessionMode::Safe => { - eprintln!("not in workflow mode — use `/workflow run`\n"); - Ok(LoopControl::Continue) - } - }, - InputAction::AgentTask { prompt } => { - match rt.block_on(forge.run_turn(forge_session.clone(), &prompt)) { - Ok(reply) => println!("\n{reply}\n"), - Err(err) => eprintln!("error: {err:#}\n"), - } - Ok(LoopControl::Continue) - } - } -} - -fn agent_config(agent: &InteractiveConfig) -> AgentConfig { - AgentConfig { - cwd: agent.cwd.clone(), - provider: agent.provider.clone(), - model: agent.model.clone(), - ..AgentConfig::default() - } -} - -fn require_extension_mode() -> Result<()> { - if embed::extension_mode_available() { - Ok(()) - } else { - anyhow::bail!("{}", crate::help::EXTENSION_UNAVAILABLE.trim()); - } -} diff --git a/crates/pulsing-cli/src/session/mode.rs b/crates/pulsing-cli/src/session/mode.rs deleted file mode 100644 index a0e27de86..000000000 --- a/crates/pulsing-cli/src/session/mode.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! Session mode — safe agent vs workflow (all UX lives in pulsing-cli). - -use std::path::PathBuf; - -#[derive(Debug, Clone)] -pub enum SessionMode { - /// Safe mode: Forge agent only (no user Python). - Safe, - /// Workflow finished; script can be re-run from the session. - WorkflowIdle { script: PathBuf, args: Vec }, -} - -impl SessionMode { - pub fn label(&self) -> &'static str { - match self { - Self::Safe => "safe", - Self::WorkflowIdle { .. } => "workflow", - } - } -} diff --git a/crates/pulsing-cli/src/session/render.rs b/crates/pulsing-cli/src/session/render.rs deleted file mode 100644 index 11568fd03..000000000 --- a/crates/pulsing-cli/src/session/render.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! Plain-text rendering (future: TUI/GUI plug in here). - -use std::path::Path; - -use pulsing_forge::InteractiveConfig; - -use super::mode::SessionMode; - -pub fn print_session_header(mode: &SessionMode, agent: &InteractiveConfig) { - let script_hint = match mode { - SessionMode::Safe => String::new(), - SessionMode::WorkflowIdle { script, .. } => { - let name = script - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or("workflow"); - format!(" · {name}") - } - }; - eprintln!( - "Pulsing session · {}/{}{script_hint}", - agent.provider, agent.model - ); - eprintln!("type /help · /exit to leave · empty line does nothing"); - if agent.provider == "demo" { - eprintln!("(demo LLM — set ANTHROPIC_API_KEY or OPENAI_API_KEY for live models)"); - } - eprintln!(); -} - -pub fn print_help(mode: &SessionMode) { - eprintln!("Commands:"); - eprintln!(" /help this message"); - eprintln!(" /mode show safe | workflow"); - eprintln!(" /exit return to shell"); - eprintln!(" /history list checkpoints"); - eprintln!(" /checkpoint [msg] save checkpoint"); - eprintln!(" /rollback [id] restore checkpoint"); - if matches!(mode, SessionMode::WorkflowIdle { .. }) { - eprintln!(" /workflow run re-run current workflow"); - eprintln!(" rerun alias for /workflow run"); - } else { - eprintln!(" /workflow list list `.pulsing/workflows/*.py`"); - eprintln!(" /workflow run [f] start workflow session"); - } - eprintln!(" safe-mode agent task"); - eprintln!(); -} - -pub fn print_mode(mode: &SessionMode) { - eprintln!("mode: {}", mode.label()); - if let SessionMode::WorkflowIdle { script, .. } = mode { - eprintln!("workflow: {}", script.display()); - } - eprintln!(); -} - -pub fn print_workflow_start(script: &Path) { - let name = script - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or("workflow"); - eprintln!("— running workflow {name} —"); -} - -pub fn print_workflow_ok() { - eprintln!("\n✓ workflow complete\n"); -} - -pub fn print_workflow_err(err: &anyhow::Error) { - eprintln!("\n✗ workflow failed: {err:#}\n"); -} - -pub fn print_failure_recovery(script: &Path) { - let name = script - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or("workflow.py"); - eprintln!("recovery: /rollback · ask agent to fix · /workflow run to retry"); - eprintln!(" pulsing \"fix {name}\""); - eprintln!(); -} diff --git a/crates/pulsing-cli/src/session/workspace.rs b/crates/pulsing-cli/src/session/workspace.rs deleted file mode 100644 index ce0e25bfe..000000000 --- a/crates/pulsing-cli/src/session/workspace.rs +++ /dev/null @@ -1,97 +0,0 @@ -//! Workspace actions invoked from the session (journal, workflow discovery). - -use std::path::PathBuf; - -use anyhow::{bail, Result}; -use pulsing_workspace::{ - checkpoint, list_revisions, require_workspace_root, rollback, CheckpointOptions, - RollbackOptions, WorkspaceLayout, -}; - -pub fn print_history() -> Result<()> { - let root = require_workspace_root(None)?; - let layout = WorkspaceLayout::new(root); - let head = pulsing_workspace::current_head(&layout)?; - let revs = list_revisions(&layout)?; - if revs.is_empty() { - eprintln!("no checkpoints yet — use /checkpoint"); - return Ok(()); - } - for r in revs { - let mark = if head.as_deref() == Some(r.id.as_str()) { - "*" - } else { - " " - }; - eprintln!( - "{mark} {} {} {} files {}", - r.id, r.created_at, r.file_count, r.message - ); - } - Ok(()) -} - -pub fn save_checkpoint(message: Option) -> Result { - let root = require_workspace_root(None)?; - let layout = WorkspaceLayout::new(root); - let manifest = checkpoint( - &layout, - CheckpointOptions { - message, - author: Some("pulsing".into()), - }, - )?; - Ok(format!( - "checkpoint {} ({} files) — {}", - manifest.id, - manifest.files.len(), - manifest.message - )) -} - -pub fn do_rollback(revision: Option) -> Result { - let root = require_workspace_root(None)?; - let layout = WorkspaceLayout::new(root); - let manifest = rollback( - &layout, - RollbackOptions { - revision_id: revision, - }, - )?; - Ok(format!( - "rolled back to {} — {}", - manifest.id, manifest.message - )) -} - -pub fn list_workflow_scripts() -> Result> { - let root = require_workspace_root(None)?; - let dir = root.join(".pulsing").join("workflows"); - if !dir.is_dir() { - bail!("no `.pulsing/workflows/` — run `pulsing init`"); - } - let mut scripts: Vec = std::fs::read_dir(&dir)? - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|ext| ext == "py")) - .collect(); - scripts.sort(); - Ok(scripts) -} - -pub fn resolve_workflow_script(explicit: Option<&str>) -> Result { - if let Some(path) = explicit { - return Ok(PathBuf::from(path)); - } - let scripts = list_workflow_scripts()?; - let example = scripts - .iter() - .find(|p| p.file_name().is_some_and(|n| n == "example.py")); - if let Some(p) = example { - return Ok(p.clone()); - } - scripts - .into_iter() - .next() - .ok_or_else(|| anyhow::anyhow!("no workflow scripts in `.pulsing/workflows/`")) -} diff --git a/crates/pulsing-cli/src/workflow.rs b/crates/pulsing-cli/src/workflow.rs index b7e9bc6e9..b53da1fa5 100644 --- a/crates/pulsing-cli/src/workflow.rs +++ b/crates/pulsing-cli/src/workflow.rs @@ -1,58 +1,18 @@ -//! Workflow script resolution — session UX lives in [`crate::session`]. +//! Workspace workflow path resolution. use std::path::PathBuf; -use std::process::ExitCode; use anyhow::Result; +use pulsing_workspace::{require_workspace_root, WorkspaceLayout}; -use crate::codex::CodexOptions; -use crate::session::workspace; - -pub struct WorkflowSession { - pub script: PathBuf, - pub script_args: Vec, - pub codex: CodexOptions, - pub batch: bool, -} - -pub fn run_session(session: WorkflowSession) -> Result { - crate::session::run_workflow( - session.codex, - session.script, - session.script_args, - session.batch, - ) -} - -/// Resolve workflow script: explicit path, or default under `.pulsing/workflows/`. pub fn resolve_script(explicit: Option) -> Result { - if let Some(path) = explicit { - return Ok(path); - } - workspace::resolve_workflow_script(None) -} - -#[cfg(test)] -mod tests { - use super::*; - use pulsing_workspace::{init_workspace, InitOptions, Template}; - use tempfile::tempdir; - - #[test] - fn resolve_default_example() { - let dir = tempdir().unwrap(); - init_workspace( - dir.path(), - InitOptions { - template: Template::Minimal, - name: None, - force: false, - guide: None, - }, - ) - .unwrap(); - std::env::set_current_dir(dir.path()).unwrap(); - let path = resolve_script(None).unwrap(); - assert!(path.ends_with("example.py")); + match explicit { + Some(path) => Ok(path), + None => { + let root = require_workspace_root(None)?; + Ok(WorkspaceLayout::new(root) + .workflows_dir() + .join("example.py")) + } } } diff --git a/crates/pulsing-cli/src/workspace.rs b/crates/pulsing-cli/src/workspace.rs index 5f527aa1a..ab56560fa 100644 --- a/crates/pulsing-cli/src/workspace.rs +++ b/crates/pulsing-cli/src/workspace.rs @@ -1,4 +1,4 @@ -//! Workspace subcommands for the pulsing binary. +//! Workspace bootstrap and journal commands. use std::path::PathBuf; @@ -11,43 +11,25 @@ use pulsing_workspace::{ #[derive(Subcommand)] pub enum WorkspaceCommand { - /// Bootstrap a Pulsing workspace (``.pulsing/`` + hooks + journal) + /// Bootstrap a workspace with hooks and journal history. Init { - /// Target directory (default: current directory) - #[arg(value_name = "DIR")] dir: Option, - /// Workspace template: minimal or agent - #[arg(long, default_value = "agent")] + #[arg(long, default_value = "minimal")] template: String, - /// Display name stored in cluster.json #[arg(long)] name: Option, - /// Re-initialize even if workspace exists #[arg(long)] force: bool, - /// Natural-language goal — LLM customizes workspace after scaffold - #[arg(short = 'g', long = "guide")] - guide_flag: Option, - #[arg(trailing_var_arg = true, allow_hyphen_values = true)] - guide_words: Vec, - #[arg(long)] - provider: Option, - #[arg(long)] - model: Option, }, - /// List workspace checkpoints + /// List workspace checkpoints. History, - /// Save a new checkpoint of tracked files + /// Save a workspace snapshot. Checkpoint { - /// Checkpoint message #[arg(short, long)] message: Option, }, - /// Restore files from a checkpoint (default: HEAD) - Rollback { - /// Revision id (e.g. 0003); default is latest checkpoint - revision: Option, - }, + /// Restore a workspace checkpoint. + Rollback { revision: Option }, } pub fn run(cmd: WorkspaceCommand) -> Result<()> { @@ -57,73 +39,48 @@ pub fn run(cmd: WorkspaceCommand) -> Result<()> { template, name, force, - guide_flag, - guide_words, - provider, - model, } => { - let root = dir.unwrap_or_else(|| std::env::current_dir().expect("cwd")); - let template = Template::parse(&template)?; - let guide = merge_guide(guide_flag, guide_words); + let root = match dir { + Some(dir) => dir, + None => std::env::current_dir()?, + }; let result = init_workspace( &root, InitOptions { - template, + template: Template::parse(&template)?, name, force, - guide: guide.clone(), + guide: None, }, )?; - if result.created { - println!( - "initialized {} (cluster_id={})", - result.root.display(), - result.cluster_id - ); - if let Some(ref text) = guide { - run_init_guide_step(&result.root, text, provider.as_deref(), model.as_deref())?; - } - println!(" pulsing # safe-mode agent (interactive)"); - println!(" pulsing \"your task\" # safe-mode one-shot"); - println!(" pulsing run # immersive workflow session"); - println!(" pulsing history # list checkpoints"); - println!(" pulsing checkpoint # save workspace snapshot"); + let status = if result.created { + "initialized" } else { - println!("already initialized: {}", result.root.display()); - if let Some(text) = guide.filter(|_| force) { - run_init_guide_step( - &result.root, - &text, - provider.as_deref(), - model.as_deref(), - )?; - } - } + "already initialized" + }; + println!( + "{status}: {} (cluster_id={})", + result.root.display(), + result.cluster_id + ); } WorkspaceCommand::History => { - let root = require_workspace_root(None)?; - let layout = WorkspaceLayout::new(root); + let layout = WorkspaceLayout::new(require_workspace_root(None)?); let head = pulsing_workspace::current_head(&layout)?; - let revs = list_revisions(&layout)?; - if revs.is_empty() { - println!("no checkpoints yet — run `pulsing checkpoint`"); - return Ok(()); - } - for r in revs { - let mark = if head.as_deref() == Some(r.id.as_str()) { + for rev in list_revisions(&layout)? { + let mark = if head.as_deref() == Some(rev.id.as_str()) { "*" } else { " " }; println!( "{mark} {} {} {} files {}", - r.id, r.created_at, r.file_count, r.message + rev.id, rev.created_at, rev.file_count, rev.message ); } } WorkspaceCommand::Checkpoint { message } => { - let root = require_workspace_root(None)?; - let layout = WorkspaceLayout::new(root); + let layout = WorkspaceLayout::new(require_workspace_root(None)?); let manifest = checkpoint( &layout, CheckpointOptions { @@ -132,15 +89,14 @@ pub fn run(cmd: WorkspaceCommand) -> Result<()> { }, )?; println!( - "checkpoint {} ({} files) — {}", + "checkpoint {} ({} files) — {}", manifest.id, manifest.files.len(), manifest.message ); } WorkspaceCommand::Rollback { revision } => { - let root = require_workspace_root(None)?; - let layout = WorkspaceLayout::new(root); + let layout = WorkspaceLayout::new(require_workspace_root(None)?); let manifest = rollback( &layout, RollbackOptions { @@ -152,49 +108,3 @@ pub fn run(cmd: WorkspaceCommand) -> Result<()> { } Ok(()) } - -fn merge_guide(flag: Option, words: Vec) -> Option { - if let Some(g) = flag.filter(|s| !s.trim().is_empty()) { - return Some(g); - } - if words.is_empty() { - None - } else { - Some(words.join(" ")) - } -} - -fn run_init_guide_step( - root: &std::path::Path, - guide: &str, - provider: Option<&str>, - model: Option<&str>, -) -> Result<()> { - eprintln!("\n# LLM-guided bootstrap…"); - let rt = tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build()?; - let summary = rt.block_on(pulsing_forge::run_init_guide( - root.to_path_buf(), - guide, - provider, - model, - ))?; - println!("\n{summary}\n"); - let layout = WorkspaceLayout::new(root); - let _ = checkpoint( - &layout, - CheckpointOptions { - message: Some("init guide".into()), - author: Some("pulsing".into()), - }, - ); - Ok(()) -} - -pub fn run_or_exit(cmd: WorkspaceCommand) { - if let Err(err) = run(cmd) { - eprintln!("error: {err:#}"); - std::process::exit(1); - } -} diff --git a/crates/pulsing-forge/Cargo.toml b/crates/pulsing-forge/Cargo.toml deleted file mode 100644 index 8135a1661..000000000 --- a/crates/pulsing-forge/Cargo.toml +++ /dev/null @@ -1,66 +0,0 @@ -[package] -name = "pulsing-forge" -version.workspace = true -edition = "2024" -authors.workspace = true -license.workspace = true -description = "Pulsing Forge — Codex-compatible agent tool runtime (sandbox + handlers)" -repository.workspace = true - -[lib] -name = "pulsing_forge" -path = "src/lib.rs" - -[[bin]] -name = "pulsing-forge-repl" -path = "src/bin/pulsing-forge-repl.rs" - -[dependencies] -anyhow = { workspace = true } -base64 = "0.22" -chrono = { workspace = true, features = ["serde"] } -clap = { version = "4", features = ["derive"] } -comfy-table = "7" -futures = { workspace = true } -futures-util = { workspace = true } -glob = "0.3" -image = { version = "0.25", default-features = false, features = ["jpeg", "png", "gif", "webp"] } -libc = "0.2" -portable-pty = "0.9" -reedline = "0.39" -regex = "1" -reqwest = { workspace = true } -reqwest-eventsource = { workspace = true } -shlex = "1" -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -sha1 = "0.10" -streaming-iterator = "0.1" -thiserror = { workspace = true } -tokio = { workspace = true, features = ["process", "io-util", "time", "rt-multi-thread", "macros", "sync"] } -tokio-util = { workspace = true } -toml = "0.8" -tracing = { workspace = true } -tree-sitter = "0.25" -tree-sitter-bash = "0.25" -url = "2" -uuid = { workspace = true, features = ["v4", "serde"] } -rmcp = { version = "1.7.0", default-features = false, features = [ - "auth", - "base64", - "client", - "macros", - "transport-child-process", - "transport-streamable-http-client-reqwest", -] } - -[dev-dependencies] -tempfile = "3" - -[lints.rust] -dead_code = "allow" - -[lints.clippy] -type_complexity = "allow" -too_many_arguments = "allow" -large_enum_variant = "allow" diff --git a/crates/pulsing-forge/NOTICE b/crates/pulsing-forge/NOTICE deleted file mode 100644 index bf26f2238..000000000 --- a/crates/pulsing-forge/NOTICE +++ /dev/null @@ -1,12 +0,0 @@ -Pulsing Forge — Third Party Notices -=================================== - -This project includes source code from OpenAI Codex (Apache License 2.0). - -Vendored reference tree: vendor/codex-rs/ -Sync script: scripts/sync-codex-forge.sh - -Adapted Rust modules in crates/pulsing-forge/src/executor.rs and error.rs -derive from codex-tools (tool_executor.rs, function_call_error.rs). - -See vendor/codex-rs/SYNC_INFO for the last synchronized commit. diff --git a/crates/pulsing-forge/src/agent/events.rs b/crates/pulsing-forge/src/agent/events.rs deleted file mode 100644 index 801af1809..000000000 --- a/crates/pulsing-forge/src/agent/events.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! Agent UI events — consumed by pulsing-cli GUI / TUI renderers. - -use std::sync::mpsc::Sender; - -#[derive(Debug, Clone)] -pub enum AgentEvent { - TextDelta(String), - ToolStart { - name: String, - }, - ToolEnd { - name: String, - ok: bool, - summary: String, - }, - ToolCancelled { - name: String, - }, - Error(String), - Cancelled, - Done { - text: String, - }, -} - -pub type AgentEventTx = Sender; - -pub(crate) fn emit(tx: &Option, event: AgentEvent) { - if let Some(tx) = tx { - let _ = tx.send(event); - } -} diff --git a/crates/pulsing-forge/src/agent/init_guide.rs b/crates/pulsing-forge/src/agent/init_guide.rs deleted file mode 100644 index 9c8e02d8b..000000000 --- a/crates/pulsing-forge/src/agent/init_guide.rs +++ /dev/null @@ -1,46 +0,0 @@ -//! LLM-guided workspace bootstrap after ``pulsing init``. - -use std::path::PathBuf; - -use super::r#loop::{AgentConfig, default_model_for_provider, default_provider, run_agent_turn}; -use super::tools::INIT_TOOL_NAMES; - -const INIT_SYSTEM: &str = "You are bootstrapping a new Pulsing AI workspace.\n\ -The `.pulsing/` scaffold (cluster.json, hooks, journal) already exists.\n\ -\n\ -Customize the project to match the user's goal:\n\ -1. Read `.pulsing/cluster.json` — adjust default_agents and puzzles if needed\n\ -2. Create or update project files (README.md, tests/, configs) with Write/Edit\n\ -3. Use Glob/Read to inspect before changing; keep changes minimal and practical\n\ -4. Do not delete `.pulsing/history/`\n\ -5. End with a short summary of what you configured\n"; - -pub async fn run_init_guide( - root: PathBuf, - guide: &str, - provider: Option<&str>, - model: Option<&str>, -) -> anyhow::Result { - let provider = provider - .map(str::to_string) - .unwrap_or_else(default_provider); - let model = model - .map(str::to_string) - .unwrap_or_else(|| default_model_for_provider(&provider)); - - let cfg = AgentConfig { - cwd: root, - provider, - model, - max_turns: 15, - system_prompt: Some(INIT_SYSTEM.to_string()), - tool_names: INIT_TOOL_NAMES.iter().map(|s| s.to_string()).collect(), - ..AgentConfig::default() - }; - - let prompt = format!( - "Workspace bootstrap goal:\n\n{guide}\n\n\ - Start by reading `.pulsing/cluster.json` and the project root, then apply changes." - ); - run_agent_turn(&cfg, &prompt).await -} diff --git a/crates/pulsing-forge/src/agent/interactive.rs b/crates/pulsing-forge/src/agent/interactive.rs deleted file mode 100644 index bb1453ed0..000000000 --- a/crates/pulsing-forge/src/agent/interactive.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! Codex-style interactive session (REPL prompt loop). - -use std::io::{self, Write}; -use std::path::PathBuf; - -use anyhow::Result; - -use super::r#loop::{AgentConfig, default_model_for_provider, default_provider}; -use crate::session::LocalForgeClient; - -#[derive(Clone, PartialEq)] -pub struct InteractiveConfig { - pub cwd: PathBuf, - pub provider: String, - pub model: String, -} - -impl Default for InteractiveConfig { - fn default() -> Self { - let provider = default_provider(); - Self { - cwd: std::env::current_dir().unwrap_or_else(|_| ".".into()), - provider: provider.clone(), - model: default_model_for_provider(&provider), - } - } -} - -pub async fn run_interactive(cfg: InteractiveConfig) -> Result<()> { - let agent_cfg = AgentConfig { - cwd: cfg.cwd, - provider: cfg.provider.clone(), - model: cfg.model, - ..AgentConfig::default() - }; - - eprintln!( - "Pulsing safe mode ({}/{}) — Forge tools, no user Python", - agent_cfg.provider, agent_cfg.model - ); - eprintln!("type a task · empty line or Ctrl-D to exit · `pulsing run` for workflows"); - if agent_cfg.provider == "demo" { - eprintln!("(demo LLM — set ANTHROPIC_API_KEY or OPENAI_API_KEY for live models)"); - } - let client = LocalForgeClient::default(); - let session_id = client.create_session(agent_cfg).await?; - - loop { - print!("› "); - let _ = io::stdout().flush(); - let mut line = String::new(); - let n = io::stdin().read_line(&mut line)?; - if n == 0 { - break; - } - let prompt = line.trim(); - if prompt.is_empty() { - break; - } - if prompt == "exit" || prompt == "quit" { - break; - } - match client.run_turn(session_id.clone(), prompt).await { - Ok(reply) => { - println!("\n{reply}\n"); - } - Err(e) => { - eprintln!("error: {e:#}"); - } - } - } - Ok(()) -} - -pub async fn run_oneshot(cfg: InteractiveConfig, prompt: &str) -> Result { - let agent_cfg = AgentConfig { - cwd: cfg.cwd, - provider: cfg.provider, - model: cfg.model, - ..AgentConfig::default() - }; - let client = LocalForgeClient::default(); - let session_id = client.create_session(agent_cfg).await?; - Ok(client.run_turn(session_id, prompt).await?) -} diff --git a/crates/pulsing-forge/src/agent/loop.rs b/crates/pulsing-forge/src/agent/loop.rs deleted file mode 100644 index bbeaf3e69..000000000 --- a/crates/pulsing-forge/src/agent/loop.rs +++ /dev/null @@ -1,407 +0,0 @@ -//! Multi-turn Forge agent loop (LLM + tools). - -use std::future::Future; -use std::path::PathBuf; -use std::pin::Pin; -use std::sync::Arc; -use std::sync::mpsc::Sender; - -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; -use thiserror::Error; -use tokio_util::sync::CancellationToken; - -use crate::agent::events::{AgentEvent, emit}; -use crate::agent::tools::DEFAULT_TOOL_NAMES; -use crate::approval::ApprovalPolicy; -use crate::context::LocalToolSession; -use crate::llm::{LlmClient, LlmMessage, LlmStream, StreamRequest}; -use crate::result::ToolResult; -use crate::runtime::ToolRuntime; -use crate::turn::TurnExecutionContext; -use crate::{SessionId, TurnId}; - -const DEFAULT_SYSTEM: &str = "You are a capable coding agent with filesystem and shell tools.\n\ -Use tools to inspect the workspace before answering.\n\ -When multi-step work is needed, call update_plan first.\n\ -Be concise in final replies."; - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct AgentConfig { - pub cwd: PathBuf, - pub provider: String, - pub model: String, - pub max_tokens: u32, - pub max_turns: usize, - pub sandbox: String, - pub approval_policy: ApprovalPolicy, - pub tool_names: Vec, - pub system_prompt: Option, -} - -#[derive(Debug, Error)] -#[error("agent turn cancelled")] -pub struct AgentCancelled; - -pub type AgentEventHandler = - Arc Pin + Send + 'static>> + Send + Sync>; - -impl Default for AgentConfig { - fn default() -> Self { - Self { - cwd: std::env::current_dir().unwrap_or_else(|_| ".".into()), - provider: default_provider(), - model: default_model_for_provider(&default_provider()), - max_tokens: 8192, - max_turns: 20, - sandbox: "off".into(), - approval_policy: ApprovalPolicy::OnRequest, - tool_names: DEFAULT_TOOL_NAMES.iter().map(|s| s.to_string()).collect(), - system_prompt: None, - } - } -} - -pub fn default_provider() -> String { - if std::env::var("ANTHROPIC_API_KEY") - .map(|k| !k.is_empty()) - .unwrap_or(false) - { - return "anthropic".into(); - } - if std::env::var("OPENAI_API_KEY") - .map(|k| !k.is_empty()) - .unwrap_or(false) - { - return "openai".into(); - } - "demo".into() -} - -pub fn default_model_for_provider(provider: &str) -> String { - match provider.trim().to_lowercase().as_str() { - "demo" => "demo".into(), - "openai" => std::env::var("OPENAI_MODEL").unwrap_or_else(|_| "gpt-4o".into()), - _ => std::env::var("ANTHROPIC_MODEL").unwrap_or_else(|_| "claude-sonnet-4-20250514".into()), - } -} - -pub async fn run_agent_turn(config: &AgentConfig, prompt: &str) -> anyhow::Result { - run_agent_turn_observed(config, prompt, None).await -} - -pub async fn run_agent_turn_observed( - config: &AgentConfig, - prompt: &str, - event_tx: Option>, -) -> anyhow::Result { - let mut agent = ForgeAgent::new(config.clone()); - agent.event_tx = event_tx; - match agent.run(prompt).await { - Ok(text) => Ok(text), - Err(err) => { - emit(&agent.event_tx, AgentEvent::Error(err.to_string())); - Err(err) - } - } -} - -pub struct ForgeAgent { - config: AgentConfig, - client: LlmClient, - runtime: ToolRuntime, - messages: Vec, - event_tx: Option>, - event_handler: Option, -} - -impl ForgeAgent { - pub fn new(config: AgentConfig) -> Self { - Self::try_new(config).expect("LLM client") - } - - pub fn try_new(config: AgentConfig) -> anyhow::Result { - let client = LlmClient::new( - &config.provider, - None, - provider_base_url_from_env(&config.provider), - )?; - let session = std::sync::Arc::new( - LocalToolSession::default().with_approval_policy(config.approval_policy), - ); - let runtime = ToolRuntime::new(crate::runtime::ToolRuntimeConfig { - cwd: config.cwd.clone(), - sandbox_policy: config.sandbox.clone(), - session, - ..Default::default() - }); - Ok(Self { - config, - client, - runtime, - messages: Vec::new(), - event_tx: None, - event_handler: None, - }) - } - - pub fn set_event_handler(&mut self, handler: Option) { - self.event_handler = handler; - } - - pub async fn run(&mut self, prompt: &str) -> anyhow::Result { - self.run_cancellable(prompt, CancellationToken::new()).await - } - - pub async fn run_cancellable( - &mut self, - prompt: &str, - cancel: CancellationToken, - ) -> anyhow::Result { - let turn = Arc::new(TurnExecutionContext::with_cancellation( - SessionId::new(), - TurnId::new(), - cancel, - )); - self.run_in_turn(prompt, turn).await - } - - pub async fn run_in_turn( - &mut self, - prompt: &str, - turn: Arc, - ) -> anyhow::Result { - let cancel = turn.cancellation(); - if cancel.is_cancelled() { - self.emit_event(AgentEvent::Cancelled).await; - return Err(AgentCancelled.into()); - } - self.messages - .push(json!({ "role": "user", "content": prompt })); - - let tools = self.runtime.tool_definitions(&self.config.tool_names)?; - - let mut final_msg: Option = None; - for _ in 0..self.config.max_turns { - let message = { - let _model_resource = turn.resources().register_passive("model_request"); - tokio::select! { - _ = cancel.cancelled() => { - self.emit_event(AgentEvent::Cancelled).await; - return Err(AgentCancelled.into()); - } - result = self.stream_one_turn(&tools) => result?, - } - }; - final_msg = Some(message); - let msg = final_msg.as_ref().expect("final message"); - self.messages - .push(json!({ "role": "assistant", "content": msg.content })); - - let tool_uses = extract_tool_uses(&msg.content); - if tool_uses.is_empty() { - let text = text_from_content(&msg.content); - self.emit_event(AgentEvent::Done { text: text.clone() }) - .await; - return Ok(text); - } - - let mut blocks = Vec::new(); - for (id, name, input) in tool_uses { - self.emit_event(AgentEvent::ToolStart { name: name.clone() }) - .await; - let result = { - let _tool_resource = turn.resources().register_passive(format!("tool:{name}")); - tokio::select! { - _ = cancel.cancelled() => { - self.emit_event(AgentEvent::ToolCancelled { name }).await; - self.emit_event(AgentEvent::Cancelled).await; - return Err(AgentCancelled.into()); - } - result = self.runtime.call_tool_in_turn(turn.clone(), &name, input) => result, - } - }; - let summary = result.content.chars().take(200).collect::(); - self.emit_event(AgentEvent::ToolEnd { - name: name.clone(), - ok: !result.is_error, - summary, - }) - .await; - blocks.push(tool_result_block(&id, &result)); - if !result.is_error { - eprintln!("# tool {name} ok"); - } else { - eprintln!("# tool {name} error: {}", result.content); - } - } - self.messages - .push(json!({ "role": "user", "content": blocks })); - } - - let text = final_msg - .map(|m| text_from_content(&m.content)) - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| "(max turns reached)".into()); - self.emit_event(AgentEvent::Done { text: text.clone() }) - .await; - Ok(text) - } - - async fn stream_one_turn(&self, tools: &[Value]) -> anyhow::Result { - let system = self - .config - .system_prompt - .clone() - .unwrap_or_else(|| DEFAULT_SYSTEM.to_string()); - let req = StreamRequest { - model: self.config.model.clone(), - max_tokens: self.config.max_tokens, - messages: self.messages.clone(), - system: Some(system), - tools: tools.to_vec(), - }; - let stream = self.client.stream_messages(req).await?; - self.emit_stream_text(&stream).await; - Ok(stream.final_message()) - } - - async fn emit_stream_text(&self, stream: &LlmStream) { - for chunk in stream.text_chunks() { - if self.event_tx.is_some() || self.event_handler.is_some() { - self.emit_event(AgentEvent::TextDelta(chunk.to_string())) - .await; - } else { - print!("{chunk}"); - let _ = std::io::Write::flush(&mut std::io::stdout()); - } - } - if self.event_tx.is_none() - && self.event_handler.is_none() - && !stream.text_chunks().is_empty() - { - println!(); - } - } - - async fn emit_event(&self, event: AgentEvent) { - emit(&self.event_tx, event.clone()); - if let Some(handler) = &self.event_handler { - handler(event).await; - } - } -} - -fn provider_base_url_from_env(provider: &str) -> Option { - let variable = match provider.trim().to_lowercase().as_str() { - "openai" => "OPENAI_BASE_URL", - "anthropic" => "ANTHROPIC_BASE_URL", - _ => return None, - }; - std::env::var(variable) - .ok() - .filter(|value| !value.is_empty()) -} - -fn text_from_content(content: &[Value]) -> String { - let mut parts = Vec::new(); - for block in content { - if block.get("type").and_then(|v| v.as_str()) == Some("text") - && let Some(t) = block.get("text").and_then(|v| v.as_str()) - { - parts.push(t); - } - } - parts.concat() -} - -fn extract_tool_uses(content: &[Value]) -> Vec<(String, String, Value)> { - let mut out = Vec::new(); - for block in content { - if block.get("type").and_then(|v| v.as_str()) != Some("tool_use") { - continue; - } - let id = block - .get("id") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - let name = block - .get("name") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - let input = block.get("input").cloned().unwrap_or_else(|| json!({})); - if !name.is_empty() { - out.push((id, name, input)); - } - } - out -} - -fn tool_result_block(id: &str, result: &ToolResult) -> Value { - json!({ - "type": "tool_result", - "tool_use_id": id, - "content": result.content, - "is_error": result.is_error, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[tokio::test] - async fn demo_agent_glob_turn() { - let cfg = AgentConfig { - provider: "demo".into(), - model: "demo".into(), - cwd: std::env::current_dir().unwrap_or_else(|_| ".".into()), - ..Default::default() - }; - let out = run_agent_turn(&cfg, "list project files with Glob") - .await - .unwrap(); - assert!(!out.is_empty()); - } - - #[tokio::test] - async fn forge_agent_preserves_messages_across_user_turns() { - let cfg = AgentConfig { - provider: "demo".into(), - model: "demo".into(), - ..Default::default() - }; - let mut agent = ForgeAgent::new(cfg); - agent.run("remember alpha").await.unwrap(); - let after_first = agent.messages.len(); - agent.run("remember beta").await.unwrap(); - assert!(agent.messages.len() > after_first); - assert_eq!( - agent - .messages - .last() - .and_then(|message| message.get("role")), - Some(&Value::String("assistant".into())) - ); - } - - #[tokio::test] - async fn pre_cancelled_turn_never_starts() { - let cfg = AgentConfig { - provider: "demo".into(), - model: "demo".into(), - ..Default::default() - }; - let mut agent = ForgeAgent::new(cfg); - let cancel = CancellationToken::new(); - cancel.cancel(); - let err = agent - .run_cancellable("must not run", cancel) - .await - .unwrap_err(); - assert!(err.downcast_ref::().is_some()); - assert!(agent.messages.is_empty()); - } -} diff --git a/crates/pulsing-forge/src/agent/mod.rs b/crates/pulsing-forge/src/agent/mod.rs deleted file mode 100644 index c7f6fe296..000000000 --- a/crates/pulsing-forge/src/agent/mod.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! Forge coding agent — Codex-style LLM + tool loop (pure Rust). - -mod events; -mod init_guide; -mod interactive; -mod r#loop; -mod tools; - -pub use events::{AgentEvent, AgentEventTx}; -pub use init_guide::run_init_guide; -pub use interactive::{InteractiveConfig, run_interactive, run_oneshot}; -pub use r#loop::{ - AgentCancelled, AgentConfig, AgentEventHandler, ForgeAgent, default_model_for_provider, - default_provider, run_agent_turn, run_agent_turn_observed, -}; -pub use tools::{DEFAULT_TOOL_NAMES, INIT_TOOL_NAMES}; diff --git a/crates/pulsing-forge/src/agent/tools.rs b/crates/pulsing-forge/src/agent/tools.rs deleted file mode 100644 index da302c68a..000000000 --- a/crates/pulsing-forge/src/agent/tools.rs +++ /dev/null @@ -1,17 +0,0 @@ -//! Default tool selections for Forge agent profiles. -//! -//! Schemas intentionally do not live here. The canonical definitions are -//! derived from the executable [`crate::registry::ToolRegistry`]. - -pub const DEFAULT_TOOL_NAMES: &[&str] = &["update_plan", "Glob", "Read", "Grep", "shell_command"]; - -/// Tools for LLM-guided ``pulsing init`` (includes write/edit). -pub const INIT_TOOL_NAMES: &[&str] = &[ - "update_plan", - "Glob", - "Read", - "Grep", - "Write", - "Edit", - "shell_command", -]; diff --git a/crates/pulsing-forge/src/approval/gate.rs b/crates/pulsing-forge/src/approval/gate.rs deleted file mode 100644 index 097303b4d..000000000 --- a/crates/pulsing-forge/src/approval/gate.rs +++ /dev/null @@ -1,307 +0,0 @@ -//! Gate shell / unified-exec behind execpolicy + host approval. - -use serde_json::Value; - -use crate::approval::{ApprovalPolicy, ExecApprovalRequest, ReviewDecision}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::execpolicy::{Decision, ExecPolicy}; -use crate::sandbox::SandboxPolicy; -use std::sync::{Arc, Mutex}; - -pub fn tokenize_shell_command(command: &str) -> Vec { - shlex::split(command) - .unwrap_or_else(|| command.split_whitespace().map(str::to_string).collect()) -} - -/// Returns effective sandbox policy after policy + approval checks. -pub fn ensure_shell_allowed( - ctx: &ToolCallContext, - args: &Value, - command: &str, -) -> Result { - let tokens = tokenize_shell_command(command); - if tokens.is_empty() { - return Err(ToolError::respond("empty command")); - } - - let cache = &ctx.approval_cache; - if cache.is_prefix_allowed(&tokens) { - return Ok(effective_sandbox_policy(ctx, args)); - } - - let policy_match = ctx.exec_policy.lock().unwrap().evaluate(&tokens); - - if policy_match.decision == Decision::Forbidden { - let msg = policy_match - .justification - .unwrap_or_else(|| "command forbidden by execpolicy".into()); - return Err(ToolError::respond(format!("execpolicy forbidden: {msg}"))); - } - - let sandbox_perm = args - .get("sandbox_permissions") - .and_then(|v| v.as_str()) - .map(str::to_string); - let needs_escalation = sandbox_perm.as_deref() == Some("require_escalated"); - let needs_prompt = policy_match.decision == Decision::Prompt - || needs_escalation - || cache.strict_auto_review() - || args.get("justification").and_then(|v| v.as_str()).is_some(); - - if !needs_prompt { - return Ok(effective_sandbox_policy(ctx, args)); - } - - let approval_policy = ctx.session.approval_policy(); - match approval_policy { - ApprovalPolicy::Always => return Ok(effective_sandbox_policy(ctx, args)), - ApprovalPolicy::Never => { - return Err(ToolError::respond( - "command requires approval but approval_policy=never", - )); - } - ApprovalPolicy::OnRequest => {} - } - - let reason = args - .get("justification") - .or_else(|| args.get("reason")) - .and_then(|v| v.as_str()) - .map(str::to_string) - .or(policy_match.justification.clone()) - .or_else(|| { - if needs_escalation { - Some("sandbox_permissions=require_escalated".into()) - } else { - None - } - }); - - let req = ExecApprovalRequest { - command: tokens.clone(), - cwd: ctx.cwd.clone(), - reason, - sandbox_permissions: sandbox_perm, - policy_decision: policy_match.decision, - justification: policy_match.justification.clone(), - proposed_execpolicy_amendment: Some(tokens.clone()), - }; - - let decision = ctx.session.request_exec_approval(req)?; - apply_review_decision(ctx, &decision, &tokens)?; - - if decision.is_approved() { - // A plain `Approved` decision covers this single execution only — it - // is intentionally not cached, so an identical command still goes - // through the same policy/approval checks next time (Codex parity; - // use `ApprovedForSession` or an execpolicy amendment to persist). - Ok(effective_sandbox_policy(ctx, args)) - } else { - Err(ToolError::respond(format!( - "exec approval denied: {:?}", - decision - ))) - } -} - -fn apply_review_decision( - ctx: &ToolCallContext, - decision: &ReviewDecision, - tokens: &[String], -) -> Result<(), ToolError> { - match decision { - ReviewDecision::Approved => Ok(()), - ReviewDecision::ApprovedForSession => { - ctx.approval_cache.allow_prefix_for_session(tokens.to_vec()); - Ok(()) - } - ReviewDecision::ApprovedExecpolicyAmendment { - proposed_execpolicy_amendment, - } => { - ctx.exec_policy - .lock() - .unwrap() - .add_allow_prefix(proposed_execpolicy_amendment.clone()); - Ok(()) - } - ReviewDecision::Denied | ReviewDecision::Abort => Ok(()), - } -} - -pub fn args_dangerously_disable_sandbox(ctx: &ToolCallContext, args: &Value) -> bool { - args.get("dangerously_disable_sandbox") - .and_then(|v| v.as_bool()) - .unwrap_or(ctx.dangerously_disable_sandbox) -} - -pub fn effective_sandbox_policy(ctx: &ToolCallContext, args: &Value) -> SandboxPolicy { - if args_dangerously_disable_sandbox(ctx, args) { - return SandboxPolicy::Off; - } - match args.get("sandbox_permissions").and_then(|v| v.as_str()) { - Some("require_escalated") => SandboxPolicy::Off, - Some("with_additional_permissions") => { - if ctx.approval_cache.effective_grants().is_effectively_empty() { - ctx.sandbox_policy - } else { - SandboxPolicy::Restricted - } - } - _ => ctx.sandbox_policy, - } -} - -pub fn new_exec_policy() -> Arc> { - Arc::new(Mutex::new(ExecPolicy::default_codex_like())) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::approval::ApprovalCache; - use crate::context::{LocalToolSession, ToolCallContext}; - use crate::discovery::new_tool_catalog; - use crate::unified_exec::UnifiedExecManager; - use std::sync::atomic::{AtomicUsize, Ordering}; - - fn strict_ctx( - exec_approval_calls: Arc, - decision: ReviewDecision, - ) -> ToolCallContext { - let session = Arc::new(LocalToolSession::default().with_exec_approval(move |_req| { - exec_approval_calls.fetch_add(1, Ordering::SeqCst); - Ok(decision.clone()) - })); - let ctx = ToolCallContext::new( - ".", - "off", - session, - Arc::new(UnifiedExecManager::new()), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - new_tool_catalog(), - ); - // Force `needs_prompt` regardless of execpolicy defaults so every - // call below exercises the approval path under review. - ctx.approval_cache.set_strict_auto_review(true); - ctx - } - - /// Regression test: a plain `Approved` decision must not be cached, or - /// `strict_auto_review`'s "review every subsequent command" guarantee - /// would be silently defeated after the first approval. - #[test] - fn approved_decision_is_not_cached_across_calls() { - let calls = Arc::new(AtomicUsize::new(0)); - let ctx = strict_ctx(calls.clone(), ReviewDecision::Approved); - - let args = serde_json::json!({}); - ensure_shell_allowed(&ctx, &args, "echo hi").expect("first call approved"); - assert_eq!(calls.load(Ordering::SeqCst), 1); - - ensure_shell_allowed(&ctx, &args, "echo hi").expect("second call approved"); - assert_eq!( - calls.load(Ordering::SeqCst), - 2, - "identical command must be re-reviewed, not auto-approved from a stale cache" - ); - } - - /// `ApprovedForSession` is the documented persistent-approval path and - /// must keep working: it should still skip re-prompting for the - /// remainder of the session (unlike the one-time `Approved` case above). - #[test] - fn approved_for_session_still_skips_future_prompts() { - let calls = Arc::new(AtomicUsize::new(0)); - let ctx = strict_ctx(calls.clone(), ReviewDecision::ApprovedForSession); - - let args = serde_json::json!({}); - ensure_shell_allowed(&ctx, &args, "echo hi").expect("first call approved"); - assert_eq!(calls.load(Ordering::SeqCst), 1); - - ensure_shell_allowed(&ctx, &args, "echo hi").expect("second call approved"); - assert_eq!( - calls.load(Ordering::SeqCst), - 1, - "ApprovedForSession must not re-prompt for the same command" - ); - } - - #[test] - fn effective_policy_maps_sandbox_permissions() { - let cache = Arc::new(ApprovalCache::default()); - let ctx = ToolCallContext::new( - ".", - "restricted", - Arc::new(LocalToolSession::default()), - Arc::new(UnifiedExecManager::new()), - new_exec_policy(), - cache.clone(), - new_tool_catalog(), - ); - let base = serde_json::json!({}); - assert_eq!( - effective_sandbox_policy(&ctx, &base), - SandboxPolicy::Restricted - ); - assert_eq!( - effective_sandbox_policy( - &ctx, - &serde_json::json!({"sandbox_permissions": "require_escalated"}), - ), - SandboxPolicy::Off - ); - assert_eq!( - effective_sandbox_policy( - &ctx, - &serde_json::json!({"sandbox_permissions": "with_additional_permissions"}), - ), - SandboxPolicy::Restricted, - "without grants, with_additional_permissions falls back to base policy" - ); - cache.record_permission_grant( - crate::approval::RequestPermissionProfile { - network: Some(serde_json::json!({"enabled": true})), - file_system: None, - }, - "turn", - ); - let ctx_off = ToolCallContext::new( - ".", - "off", - Arc::new(LocalToolSession::default()), - Arc::new(UnifiedExecManager::new()), - new_exec_policy(), - cache, - new_tool_catalog(), - ); - assert_eq!( - effective_sandbox_policy( - &ctx_off, - &serde_json::json!({"sandbox_permissions": "with_additional_permissions"}), - ), - SandboxPolicy::Restricted, - "granted permissions enable restricted overlay on off base policy" - ); - assert_eq!( - effective_sandbox_policy( - &ctx, - &serde_json::json!({"dangerously_disable_sandbox": true}), - ), - SandboxPolicy::Off - ); - } - - /// Denied decisions must never be cached as approved. - #[test] - fn denied_decision_keeps_failing_and_reprompts() { - let calls = Arc::new(AtomicUsize::new(0)); - let ctx = strict_ctx(calls.clone(), ReviewDecision::Denied); - - let args = serde_json::json!({}); - assert!(ensure_shell_allowed(&ctx, &args, "echo hi").is_err()); - assert!(ensure_shell_allowed(&ctx, &args, "echo hi").is_err()); - assert_eq!(calls.load(Ordering::SeqCst), 2); - } -} diff --git a/crates/pulsing-forge/src/approval/mod.rs b/crates/pulsing-forge/src/approval/mod.rs deleted file mode 100644 index 20b6b4206..000000000 --- a/crates/pulsing-forge/src/approval/mod.rs +++ /dev/null @@ -1,149 +0,0 @@ -//! Exec approval types and shell gate (Codex-aligned). - -mod gate; -mod types; - -pub use gate::{ - args_dangerously_disable_sandbox, effective_sandbox_policy, ensure_shell_allowed, - new_exec_policy, tokenize_shell_command, -}; -pub use types::{ - ApprovalPolicy, ExecApprovalRequest, RequestPermissionProfile, RequestPermissionsArgs, - RequestPermissionsResponse, ReviewDecision, -}; - -use std::sync::Mutex; - -/// Session-scoped approval cache (prefix allow-list + strict review flag). -/// -/// Only `ApprovedForSession` (`session_prefixes`) and execpolicy amendments -/// persist beyond a single exec call — a plain `Approved` decision is a -/// one-time grant for that command execution only (Codex `ReviewDecision` -/// semantics) and must never be cached here, or every subsequent identical -/// command would silently skip approval for the lifetime of this cache. -#[derive(Default)] -pub struct ApprovalCache { - session_prefixes: Mutex>>, - strict_auto_review: Mutex, - turn_grants: Mutex>, - session_grants: Mutex>, -} - -impl ApprovalCache { - pub fn is_prefix_allowed(&self, cmd: &[String]) -> bool { - let prefixes = self.session_prefixes.lock().unwrap(); - prefixes.iter().any(|p| cmd.starts_with(p.as_slice())) - } - - pub fn allow_prefix_for_session(&self, prefix: Vec) { - if prefix.is_empty() { - return; - } - let mut prefixes = self.session_prefixes.lock().unwrap(); - if !prefixes.iter().any(|p| p == &prefix) { - prefixes.push(prefix); - } - } - - pub fn set_strict_auto_review(&self, on: bool) { - *self.strict_auto_review.lock().unwrap() = on; - } - - pub fn strict_auto_review(&self) -> bool { - *self.strict_auto_review.lock().unwrap() - } - - /// Record an approved `request_permissions` grant (turn vs session scope). - pub fn record_permission_grant(&self, profile: RequestPermissionProfile, scope: &str) { - let slot = if scope == "session" { - &self.session_grants - } else { - &self.turn_grants - }; - *slot.lock().unwrap() = Some(profile); - } - - /// Merged session + turn grants (turn overlays session). - pub fn effective_grants(&self) -> RequestPermissionProfile { - let session = self.session_grants.lock().unwrap().clone(); - let turn = self.turn_grants.lock().unwrap().clone(); - match (session, turn) { - (None, None) => RequestPermissionProfile::default(), - (Some(s), None) => s, - (None, Some(t)) => t, - (Some(mut s), Some(t)) => { - if t.network.is_some() { - s.network = t.network; - } - if let Some(t_fs) = t.file_system { - s.file_system = Some(merge_file_system_json(s.file_system.take(), t_fs)); - } - s - } - } - } - - pub fn network_granted(&self) -> bool { - self.effective_grants().network_enabled() - } - - /// Clears turn-scoped state. Session prefix allow-list is preserved. - pub fn clear_turn_state(&self) { - self.set_strict_auto_review(false); - *self.turn_grants.lock().unwrap() = None; - } -} - -fn merge_file_system_json( - base: Option, - overlay: serde_json::Value, -) -> serde_json::Value { - let Some(mut base_obj) = base.and_then(|v| v.as_object().cloned()) else { - return overlay; - }; - let Some(overlay_obj) = overlay.as_object() else { - return overlay; - }; - for key in ["read", "write", "entries"] { - if let Some(overlay_arr) = overlay_obj.get(key).and_then(|v| v.as_array()) { - let entry = base_obj - .entry(key.to_string()) - .or_insert(serde_json::json!([])); - if let Some(base_arr) = entry.as_array_mut() { - for item in overlay_arr { - if !base_arr.contains(item) { - base_arr.push(item.clone()); - } - } - } - } - } - serde_json::Value::Object(base_obj) -} - -#[cfg(test)] -mod cache_tests { - use super::*; - - #[test] - fn session_grant_survives_turn_clear() { - let cache = ApprovalCache::default(); - cache.record_permission_grant( - RequestPermissionProfile { - network: Some(serde_json::json!({"enabled": true})), - file_system: None, - }, - "session", - ); - cache.record_permission_grant( - RequestPermissionProfile { - network: Some(serde_json::json!({"enabled": false})), - file_system: None, - }, - "turn", - ); - cache.clear_turn_state(); - assert!(!cache.strict_auto_review()); - assert!(cache.network_granted()); - } -} diff --git a/crates/pulsing-forge/src/approval/types.rs b/crates/pulsing-forge/src/approval/types.rs deleted file mode 100644 index 4e398e674..000000000 --- a/crates/pulsing-forge/src/approval/types.rs +++ /dev/null @@ -1,283 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::path::{Component, Path, PathBuf}; - -use crate::execpolicy::Decision; - -#[derive(Clone, Copy, Debug, Eq, PartialEq, Default, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ApprovalPolicy { - /// Prompt on execpolicy Prompt / sandbox escalation (default). - #[default] - OnRequest, - /// Auto-approve all prompts (tests / trusted hosts). - Always, - /// Deny all prompts. - Never, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct ExecApprovalRequest { - pub command: Vec, - pub cwd: PathBuf, - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub sandbox_permissions: Option, - pub policy_decision: Decision, - #[serde(skip_serializing_if = "Option::is_none")] - pub justification: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub proposed_execpolicy_amendment: Option>, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ReviewDecision { - Approved, - ApprovedExecpolicyAmendment { - proposed_execpolicy_amendment: Vec, - }, - ApprovedForSession, - Denied, - Abort, -} - -impl ReviewDecision { - pub fn is_approved(&self) -> bool { - matches!( - self, - Self::Approved | Self::ApprovedExecpolicyAmendment { .. } | Self::ApprovedForSession - ) - } -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RequestPermissionProfile { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub network: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub file_system: Option, -} - -impl RequestPermissionProfile { - pub fn is_empty(&self) -> bool { - self.network.is_none() && self.file_system.is_none() - } - - /// True when every present section is null/{} or has no effective grant - /// (Codex `NetworkPermissions::is_empty` / `FileSystemPermissions::is_empty`). - pub fn is_effectively_empty(&self) -> bool { - let net_empty = self - .network - .as_ref() - .map(is_permission_section_empty) - .unwrap_or(true); - let fs_empty = self - .file_system - .as_ref() - .map(is_permission_section_empty) - .unwrap_or(true); - net_empty && fs_empty - } - - pub fn has_actionable_request(&self) -> bool { - !self.is_empty() && !self.is_effectively_empty() - } - - /// Reject file_system paths that resolve outside `cwd` (P0 sandbox safety). - pub fn validate_paths(&self, cwd: &Path) -> Result<(), String> { - if let Some(fs) = &self.file_system { - validate_file_system_paths(cwd, fs)?; - } - Ok(()) - } - - pub fn network_enabled(&self) -> bool { - self.network - .as_ref() - .and_then(|v| v.get("enabled")) - .and_then(|v| v.as_bool()) - .unwrap_or(false) - } -} - -fn validate_file_system_paths(cwd: &Path, fs: &serde_json::Value) -> Result<(), String> { - let root = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf()); - for raw in collect_file_system_path_strings(fs) { - let resolved = resolve_permission_path(&root, &raw)?; - if resolved != root && !resolved.starts_with(&root) { - return Err(format!( - "file_system permission path outside working directory: {raw}" - )); - } - } - Ok(()) -} - -fn collect_file_system_path_strings(fs: &serde_json::Value) -> Vec { - let mut out = Vec::new(); - let Some(obj) = fs.as_object() else { - return out; - }; - for key in ["read", "write"] { - if let Some(arr) = obj.get(key).and_then(|v| v.as_array()) { - for item in arr { - if let Some(s) = item.as_str() { - out.push(s.to_string()); - } - } - } - } - if let Some(entries) = obj.get("entries").and_then(|v| v.as_array()) { - for entry in entries { - let Some(entry_obj) = entry.as_object() else { - continue; - }; - let Some(path_val) = entry_obj.get("path") else { - continue; - }; - if let Some(s) = path_val.as_str() { - out.push(s.to_string()); - continue; - } - let Some(path_obj) = path_val.as_object() else { - continue; - }; - if path_obj.get("type").and_then(|v| v.as_str()) == Some("path") - && let Some(s) = path_obj.get("path").and_then(|v| v.as_str()) - { - out.push(s.to_string()); - } - } - } - out -} - -fn resolve_permission_path(cwd: &Path, raw: &str) -> Result { - let path = Path::new(raw); - if path.is_absolute() { - return path - .canonicalize() - .or_else(|_| Ok::<_, std::io::Error>(path.to_path_buf())) - .map_err(|e| format!("invalid file_system path {raw:?}: {e}")); - } - for component in path.components() { - if matches!(component, Component::ParentDir) { - return Err(format!( - "file_system permission path must not contain '..': {raw}" - )); - } - } - Ok(cwd.join(path)) -} - -fn is_permission_section_empty(value: &serde_json::Value) -> bool { - match value { - serde_json::Value::Null => true, - serde_json::Value::Object(map) => { - if map.is_empty() { - return true; - } - if map.len() == 1 && map.get("enabled").is_some_and(|enabled| enabled.is_null()) { - return true; - } - if let Some(entries) = map.get("entries").and_then(|v| v.as_array()) { - return entries.is_empty(); - } - let read_empty = map - .get("read") - .map(|v| v.as_array().is_none_or(|a| a.is_empty())) - .unwrap_or(true); - let write_empty = map - .get("write") - .map(|v| v.as_array().is_none_or(|a| a.is_empty())) - .unwrap_or(true); - if map.contains_key("read") || map.contains_key("write") { - return read_empty && write_empty; - } - false - } - _ => false, - } -} - -#[cfg(test)] -mod profile_tests { - use super::*; - - #[test] - fn rejects_unknown_fields_on_args() { - let err = serde_json::from_value::(serde_json::json!({ - "permissions": {"network": {"enabled": true}}, - "extra": true, - })) - .unwrap_err(); - assert!(err.to_string().contains("unknown field")); - } - - #[test] - fn rejects_file_system_path_outside_cwd() { - let profile = RequestPermissionProfile { - network: None, - file_system: Some(serde_json::json!({ - "write": ["/etc/passwd"] - })), - }; - let err = profile - .validate_paths(Path::new("/tmp/workspace")) - .unwrap_err(); - assert!(err.contains("outside working directory")); - } - - #[test] - fn rejects_parent_dir_in_relative_path() { - let profile = RequestPermissionProfile { - network: None, - file_system: Some(serde_json::json!({ - "read": ["../secret"] - })), - }; - let err = profile - .validate_paths(Path::new("/tmp/workspace")) - .unwrap_err(); - assert!(err.contains("..")); - } - - #[test] - fn allows_in_cwd_relative_path() { - let profile = RequestPermissionProfile { - network: None, - file_system: Some(serde_json::json!({ - "write": ["subdir/file.txt"] - })), - }; - profile - .validate_paths(Path::new("/tmp")) - .expect("in-cwd path"); - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RequestPermissionsArgs { - #[serde( - default, - rename = "environment_id", - alias = "environmentId", - skip_serializing_if = "Option::is_none" - )] - pub environment_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reason: Option, - pub permissions: RequestPermissionProfile, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct RequestPermissionsResponse { - pub permissions: RequestPermissionProfile, - #[serde(default)] - pub scope: String, - #[serde(default)] - pub strict_auto_review: bool, -} diff --git a/crates/pulsing-forge/src/bin/pulsing-forge-repl.rs b/crates/pulsing-forge/src/bin/pulsing-forge-repl.rs deleted file mode 100644 index 133ee0bf5..000000000 --- a/crates/pulsing-forge/src/bin/pulsing-forge-repl.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! ``pulsing-forge-repl`` — Rust Forge session REPL binary for ``pulsing forge repl``. - -fn main() -> anyhow::Result<()> { - pulsing_forge::cli::run_repl_from_iter(std::env::args()) -} diff --git a/crates/pulsing-forge/src/cli/commands.rs b/crates/pulsing-forge/src/cli/commands.rs deleted file mode 100644 index 04300c7c9..000000000 --- a/crates/pulsing-forge/src/cli/commands.rs +++ /dev/null @@ -1,352 +0,0 @@ -//! Slash + meta commands — Codex-compatible names with Forge REPL semantics. - -/// What a slash command does in this REPL. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum SlashAction { - Meta(&'static str), - Clear, - Diff, - Ps, - Stop, - Fork, - Compact, - Mcp, - Plugins, - Mention, - Review, - Rollout, - Copy, -} - -pub struct SlashDef { - pub name: &'static str, - pub aliases: &'static [&'static str], - pub description: &'static str, - pub action: SlashAction, -} - -/// Presentation order: frequent first (Codex convention — do not alpha-sort). -pub const SLASH_DEFS: &[SlashDef] = &[ - SlashDef { - name: "help", - aliases: &[], - description: "show commands and examples", - action: SlashAction::Meta("help"), - }, - SlashDef { - name: "tools", - aliases: &[], - description: "list registered Forge tools", - action: SlashAction::Meta("tools"), - }, - SlashDef { - name: "session", - aliases: &["status"], - description: "cwd, approval, replay progress (Codex /status)", - action: SlashAction::Meta("session"), - }, - SlashDef { - name: "plan", - aliases: &[], - description: "show collaborative task plan", - action: SlashAction::Meta("plan"), - }, - SlashDef { - name: "permissions", - aliases: &["approve"], - description: "approval mode: auto | ask (Codex /permissions)", - action: SlashAction::Meta("approve"), - }, - SlashDef { - name: "replay", - aliases: &[], - description: "replay trace step or /replay all [dry] [verify]", - action: SlashAction::Meta("replay"), - }, - SlashDef { - name: "trace", - aliases: &[], - description: "trace save PATH | trace show", - action: SlashAction::Meta("trace"), - }, - SlashDef { - name: "fork", - aliases: &[], - description: "fork trace at step N then continue interactively", - action: SlashAction::Fork, - }, - SlashDef { - name: "ps", - aliases: &[], - description: "list background unified-exec sessions (Codex /ps)", - action: SlashAction::Ps, - }, - SlashDef { - name: "stop", - aliases: &["clean"], - description: "stop all background exec sessions (Codex /clean)", - action: SlashAction::Stop, - }, - SlashDef { - name: "diff", - aliases: &[], - description: "git diff including untracked files (Codex /diff)", - action: SlashAction::Diff, - }, - SlashDef { - name: "review", - aliases: &[], - description: "show workspace diff for manual review", - action: SlashAction::Review, - }, - SlashDef { - name: "compact", - aliases: &[], - description: "request new context (maps to new_context tool)", - action: SlashAction::Compact, - }, - SlashDef { - name: "mcp", - aliases: &[], - description: "list MCP-related tools", - action: SlashAction::Mcp, - }, - SlashDef { - name: "plugins", - aliases: &[], - description: "list installable plugins", - action: SlashAction::Plugins, - }, - SlashDef { - name: "mention", - aliases: &[], - description: "read file preview: /mention path/to/file", - action: SlashAction::Mention, - }, - SlashDef { - name: "rollout", - aliases: &[], - description: "show active trace/record file paths", - action: SlashAction::Rollout, - }, - SlashDef { - name: "copy", - aliases: &[], - description: "print last tool result (markdown-friendly)", - action: SlashAction::Copy, - }, - SlashDef { - name: "clear", - aliases: &[], - description: "clear terminal screen", - action: SlashAction::Clear, - }, - SlashDef { - name: "events", - aliases: &[], - description: "recent exec deltas / forge events", - action: SlashAction::Meta("events"), - }, - SlashDef { - name: "call", - aliases: &[], - description: "call TOOL {json}", - action: SlashAction::Meta("call"), - }, - SlashDef { - name: "quit", - aliases: &["exit"], - description: "exit REPL", - action: SlashAction::Meta("quit"), - }, -]; - -pub const META_COMMANDS: &[(&str, &str)] = &[ - ("help", "show commands"), - ("tools", "list tools"), - ("session", "session snapshot"), - ("plan", "task plan"), - ("events", "exec deltas"), - ("approve", "auto | ask"), - ("replay", "step | all [dry] [verify]"), - ("trace", "save PATH | show"), - ("fork", "N — fork trace at step"), - ("call", "TOOL {json}"), - ("quit", "exit"), -]; - -pub const APPROVE_MODES: &[&str] = &["auto", "ask"]; -pub const REPLAY_FLAGS: &[&str] = &["all", "dry", "verify"]; -pub const TRACE_SUBCMDS: &[&str] = &["save", "show"]; - -pub const TOOL_FLAGS: &[(&str, &[&str])] = &[ - ("Read", &["--file_path", "--offset", "--limit"]), - ("Glob", &["--pattern", "--path"]), - ("Grep", &["--pattern", "--path", "--glob"]), - ("Edit", &["--file_path", "--old_string", "--new_string"]), - ("Write", &["--file_path", "--content"]), - ("Bash", &["--command"]), - ( - "shell_command", - &[ - "--command", - "--workdir", - "--timeout_ms", - "--login", - "--sandbox_permissions", - ], - ), - ( - "exec_command", - &[ - "--cmd", - "--workdir", - "--tty", - "--yield_time_ms", - "--max_output_tokens", - ], - ), - ( - "write_stdin", - &["--session_id", "--chars", "--yield_time_ms"], - ), - ("apply_patch", &["--patch"]), - ("view_image", &["--path", "--detail"]), - ("tool_search", &["--query", "--limit"]), - ( - "request_plugin_install", - &[ - "--tool_type", - "--action_type", - "--tool_id", - "--suggest_reason", - ], - ), - ("request_permissions", &["--reason"]), - ("list_mcp_resources", &["--server"]), - ("list_mcp_resource_templates", &["--server", "--cursor"]), - ("read_mcp_resource", &["--server", "--uri"]), -]; - -pub const HELP: &str = r#"Forge session REPL — Codex-aligned slash commands + ToolRuntime - -Tools (Nushell-style): - Read --file_path README.md - @README.md mention → Read preview - -Slash (Tab after /): - /help /tools /session /plan /permissions auto - /replay all verify /fork 3 /ps /stop /diff /compact - /mcp /plugins /mention src/main.rs /rollout /copy /clear - -Meta: tools | session | approve ask | replay | trace show | quit -Tips: Tab · gray hints · A=auto K=ask · :cmd = bare meta alias -"#; - -/// Parsed user input before dispatch. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ParsedInput { - Empty, - SlashMenu, - Slash { action: SlashAction, args: String }, - Mention(String), - Meta(String), - Bare(String), -} - -pub fn parse_line(line: &str) -> ParsedInput { - let line = line.trim(); - if line.is_empty() { - return ParsedInput::Empty; - } - if let Some(path) = line.strip_prefix('@') { - let path = path.trim(); - if path.is_empty() { - return ParsedInput::SlashMenu; - } - return ParsedInput::Mention(path.to_string()); - } - if let Some(rest) = line.strip_prefix('/') { - let rest = rest.trim(); - if rest.is_empty() { - return ParsedInput::SlashMenu; - } - let mut parts = rest.split_whitespace(); - let head = parts.next().unwrap_or(""); - let args = parts.collect::>().join(" "); - let def = match resolve_slash(head) { - Some(d) => d, - None => return ParsedInput::Bare(line.to_string()), - }; - return ParsedInput::Slash { - action: def.action.clone(), - args, - }; - } - if let Some(meta) = line.strip_prefix(':') { - return ParsedInput::Meta(meta.trim().to_string()); - } - ParsedInput::Bare(line.to_string()) -} - -pub fn resolve_slash(head: &str) -> Option<&'static SlashDef> { - SLASH_DEFS - .iter() - .find(|d| d.name == head || d.aliases.contains(&head)) -} - -/// Flat list for tab completion: name + aliases. -pub fn slash_completion_names() -> Vec<(&'static str, &'static str)> { - let mut out = Vec::new(); - for d in SLASH_DEFS { - out.push((d.name, d.description)); - for a in d.aliases { - out.push((a, d.description)); - } - } - out -} - -pub fn print_slash_menu() { - println!("Slash commands (Tab to complete):"); - for d in SLASH_DEFS { - let aliases = if d.aliases.is_empty() { - String::new() - } else { - format!(" (alias: {})", d.aliases.join(", ")) - }; - println!(" /{:<14} {}{}", d.name, d.description, aliases); - } - println!(" @file mention → Read preview"); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn clean_alias_resolves_to_stop() { - let p = parse_line("/clean"); - assert_eq!( - p, - ParsedInput::Slash { - action: SlashAction::Stop, - args: String::new() - } - ); - } - - #[test] - fn status_alias_resolves_to_session() { - let def = resolve_slash("status").unwrap(); - assert_eq!(def.action, SlashAction::Meta("session")); - } - - #[test] - fn mention_parses_at_path() { - assert_eq!( - parse_line("@src/main.rs"), - ParsedInput::Mention("src/main.rs".into()) - ); - } -} diff --git a/crates/pulsing-forge/src/cli/completer.rs b/crates/pulsing-forge/src/cli/completer.rs deleted file mode 100644 index eef09e4b2..000000000 --- a/crates/pulsing-forge/src/cli/completer.rs +++ /dev/null @@ -1,307 +0,0 @@ -//! Tab completion + inline hints. - -use std::path::{Path, PathBuf}; - -use reedline::{Completer, Hinter, History, Span, Suggestion}; - -use super::commands::{ - APPROVE_MODES, META_COMMANDS, REPLAY_FLAGS, TOOL_FLAGS, TRACE_SUBCMDS, slash_completion_names, -}; - -pub struct ForgeCompleter { - tool_names: Vec, - cwd: PathBuf, -} - -impl ForgeCompleter { - pub fn new(tool_names: Vec, cwd: PathBuf) -> Self { - Self { tool_names, cwd } - } - - fn word_bounds(line: &str, pos: usize) -> (usize, usize) { - let before = &line[..pos.min(line.len())]; - let start = before - .rfind(|c: char| c.is_whitespace()) - .map(|i| i + 1) - .unwrap_or(0); - (start, pos) - } - - fn flag_suggestions(tool: &str, prefix: &str, span: Span) -> Vec { - TOOL_FLAGS - .iter() - .find(|(name, _)| *name == tool) - .map(|(_, flags)| *flags) - .unwrap_or(&[]) - .iter() - .filter(|f| f.starts_with(prefix) || prefix.is_empty()) - .map(|f| Suggestion { - value: format!("{f} "), - description: Some("tool argument".into()), - span, - append_whitespace: false, - ..Default::default() - }) - .collect() - } - - fn path_suggestions(prefix: &str, span: Span, cwd: &Path) -> Vec { - let clean = prefix.trim_start_matches("./"); - let (dir, file_prefix) = match clean.rfind('/') { - Some(i) => (cwd.join(&clean[..i]), &clean[i + 1..]), - None => (cwd.to_path_buf(), clean), - }; - let read_dir = match std::fs::read_dir(dir) { - Ok(d) => d, - Err(_) => return Vec::new(), - }; - let mut out = Vec::new(); - for entry in read_dir.flatten() { - let name = entry.file_name().to_string_lossy().into_owned(); - if file_prefix.is_empty() || name.starts_with(file_prefix) { - let suffix = if entry.path().is_dir() { "/" } else { " " }; - out.push(Suggestion { - value: format!("{name}{suffix}"), - description: Some("path".into()), - span, - append_whitespace: false, - ..Default::default() - }); - } - } - out.sort_by(|a, b| a.value.cmp(&b.value)); - out.truncate(32); - out - } -} - -impl Completer for ForgeCompleter { - fn complete(&mut self, line: &str, pos: usize) -> Vec { - let (start, end) = Self::word_bounds(line, pos); - let span = Span::new(start, end); - let word = &line[start..end]; - - if let Some(needle) = line.strip_prefix('@') { - let needle = needle.trim_start(); - return Self::path_suggestions(needle, Span::new(1, pos), &self.cwd) - .into_iter() - .map(|mut s| { - s.value = format!("@{}", s.value); - s.span = Span::new(0, pos); - s - }) - .collect(); - } - - if let Some(needle) = line.strip_prefix('/') { - let needle = needle.trim_start(); - return slash_completion_names() - .iter() - .filter(|(name, _)| name.starts_with(needle) || needle.is_empty()) - .map(|(name, desc)| Suggestion { - value: format!("/{name}"), - description: Some((*desc).into()), - span: Span::new(0, pos), - append_whitespace: true, - ..Default::default() - }) - .collect(); - } - - let tokens: Vec<&str> = line[..pos].split_whitespace().collect(); - if tokens.is_empty() { - let mut out: Vec = META_COMMANDS - .iter() - .map(|(name, desc)| Suggestion { - value: (*name).into(), - description: Some((*desc).into()), - span, - append_whitespace: true, - ..Default::default() - }) - .collect(); - for name in &self.tool_names { - out.push(Suggestion { - value: name.clone(), - description: Some("tool".into()), - span, - append_whitespace: true, - ..Default::default() - }); - } - return out; - } - - let head = tokens[0]; - if tokens.len() == 1 { - let mut out: Vec = META_COMMANDS - .iter() - .filter(|(n, _)| n.starts_with(head)) - .map(|(name, desc)| Suggestion { - value: (*name).into(), - description: Some((*desc).into()), - span, - append_whitespace: true, - ..Default::default() - }) - .collect(); - for name in &self.tool_names { - if name.starts_with(head) { - out.push(Suggestion { - value: name.clone(), - description: Some("tool".into()), - span, - append_whitespace: true, - ..Default::default() - }); - } - } - if !out.is_empty() { - return out; - } - } - - if head == "approve" || head == "permissions" { - return APPROVE_MODES - .iter() - .filter(|m| m.starts_with(word)) - .map(|m| Suggestion { - value: (*m).into(), - description: Some("approval mode".into()), - span, - append_whitespace: true, - ..Default::default() - }) - .collect(); - } - - if head == "replay" { - return REPLAY_FLAGS - .iter() - .filter(|f| f.starts_with(word)) - .map(|f| Suggestion { - value: (*f).into(), - description: Some("replay modifier".into()), - span, - append_whitespace: true, - ..Default::default() - }) - .collect(); - } - - if head == "trace" && tokens.len() >= 2 { - return TRACE_SUBCMDS - .iter() - .filter(|s| s.starts_with(word)) - .map(|s| Suggestion { - value: (*s).into(), - description: Some("trace subcommand".into()), - span, - append_whitespace: true, - ..Default::default() - }) - .collect(); - } - - if word.starts_with("--") { - return Self::flag_suggestions(tokens[0], word, span); - } - - if self.tool_names.iter().any(|t| t == head) && tokens.len() >= 2 { - let last_flag = tokens - .iter() - .rev() - .find(|t| t.starts_with("--")) - .copied() - .unwrap_or(""); - if matches!(last_flag, "--file_path" | "--path" | "--pattern") { - return Self::path_suggestions(word, span, &self.cwd); - } - if word.is_empty() || word.starts_with("--") { - return Self::flag_suggestions( - head, - if word.starts_with("--") { word } else { "" }, - span, - ); - } - } - - Vec::new() - } -} - -pub struct ForgeHinter { - completer: ForgeCompleter, - last_hint: String, -} - -impl ForgeHinter { - pub fn new(tool_names: Vec, cwd: PathBuf) -> Self { - Self { - completer: ForgeCompleter::new(tool_names, cwd), - last_hint: String::new(), - } - } -} - -impl Hinter for ForgeHinter { - fn handle( - &mut self, - line: &str, - pos: usize, - _history: &dyn History, - use_ansi_coloring: bool, - _cwd: &str, - ) -> String { - let hint = self - .completer - .complete(line, pos) - .first() - .map(|s| suffix_after(line, &s.value)) - .unwrap_or_default(); - self.last_hint = hint.clone(); - if hint.is_empty() { - return String::new(); - } - if use_ansi_coloring { - format!("\x1b[2m{hint}\x1b[0m") - } else { - hint - } - } - - fn complete_hint(&self) -> String { - self.last_hint.clone() - } - - fn next_hint_token(&self) -> String { - self.last_hint - .split_whitespace() - .next() - .unwrap_or("") - .to_string() - } -} - -fn suffix_after(line: &str, completion: &str) -> String { - completion.strip_prefix(line).unwrap_or("").to_string() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn completes_slash_and_aliases() { - let mut c = ForgeCompleter::new(vec![], PathBuf::from(".")); - assert!(c.complete("/hel", 4).iter().any(|s| s.value == "/help")); - assert!(c.complete("/clean", 6).iter().any(|s| s.value == "/clean")); - } - - #[test] - fn completes_tool_flags() { - let mut c = ForgeCompleter::new(vec!["Read".into()], PathBuf::from(".")); - let hits = c.complete("Read --file", 11); - assert!(hits.iter().any(|s| s.value.contains("file_path"))); - } -} diff --git a/crates/pulsing-forge/src/cli/mod.rs b/crates/pulsing-forge/src/cli/mod.rs deleted file mode 100644 index b95645c28..000000000 --- a/crates/pulsing-forge/src/cli/mod.rs +++ /dev/null @@ -1,80 +0,0 @@ -//! Forge session REPL (Rust-native). Invoked via ``pulsing forge repl``. - -pub mod commands; -pub mod completer; -pub mod parse; -pub mod repl; -pub mod session; -pub mod trace; - -use std::path::PathBuf; - -use anyhow::Result; -use clap::Parser; - -pub use repl::{ForgeRepl, ReplConfig}; - -#[derive(Parser, Debug)] -#[command( - name = "pulsing forge repl", - about = "Forge session REPL (Rust-native shell)" -)] -pub struct ReplCliArgs { - #[arg(long, default_value = ".")] - pub cwd: PathBuf, - #[arg(long, default_value = "off")] - pub sandbox: String, - #[arg(long)] - pub dangerously_disable_sandbox: bool, - #[arg(long, default_value = "auto")] - pub approve: String, - #[arg(long)] - pub trace: Option, - #[arg(long)] - pub record: Option, - #[arg(long)] - pub replay_all: bool, - #[arg(long)] - pub dry_run: bool, - #[arg(long)] - pub verify: bool, -} - -pub fn run_repl(args: ReplCliArgs) -> Result<()> { - let approve_auto = !args.approve.eq_ignore_ascii_case("ask"); - let cfg = ReplConfig { - cwd: args.cwd.canonicalize().unwrap_or(args.cwd), - sandbox: args.sandbox, - dangerously_disable_sandbox: args.dangerously_disable_sandbox, - approve_auto, - trace_path: args.trace.clone(), - record_path: args.record, - }; - - let rt = tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build()?; - - rt.block_on(async { - let mut repl = ForgeRepl::new(cfg)?; - if args.replay_all { - if args.trace.is_none() { - anyhow::bail!("--replay-all requires --trace"); - } - for line in repl.replay_all(args.dry_run, args.verify).await? { - println!("{line}"); - } - Ok(()) - } else { - repl.run_interactive() - } - }) -} - -pub fn run_repl_from_iter(iter: I) -> Result<()> -where - I: IntoIterator, - T: Into + Clone, -{ - run_repl(ReplCliArgs::parse_from(iter)) -} diff --git a/crates/pulsing-forge/src/cli/parse.rs b/crates/pulsing-forge/src/cli/parse.rs deleted file mode 100644 index f521c60c2..000000000 --- a/crates/pulsing-forge/src/cli/parse.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! Line parsing — tool args (Nushell-style flags + JSON). - -use anyhow::Result; -use serde_json::{Map, Value, json}; - -pub fn parse_tool_args(text: &str) -> Result { - let text = text.trim(); - if text.is_empty() { - return Ok(json!({})); - } - if text.starts_with('{') { - return Ok(serde_json::from_str(text)?); - } - let mut out = Map::new(); - let mut parts = text.split_whitespace().peekable(); - while parts.peek().is_some() { - let tok = parts.next().unwrap(); - if !tok.starts_with("--") { - continue; - } - let key = tok.trim_start_matches("--"); - if let Some((k, v)) = key.split_once('=') { - out.insert(k.to_string(), Value::String(v.to_string())); - continue; - } - if let Some(v) = parts.next() { - if !v.starts_with("--") { - out.insert(key.to_string(), Value::String(v.to_string())); - } - } else { - out.insert(key.to_string(), Value::Bool(true)); - } - } - Ok(Value::Object(out)) -} - -pub fn parse_tool_invocation(rest: &str) -> Result<(String, Value)> { - let (tool, args_text) = rest - .split_once(|c: char| c.is_whitespace()) - .map(|(a, b)| (a.to_string(), b.trim())) - .unwrap_or((rest.to_string(), "")); - Ok((tool, parse_tool_args(args_text)?)) -} diff --git a/crates/pulsing-forge/src/cli/repl.rs b/crates/pulsing-forge/src/cli/repl.rs deleted file mode 100644 index cc425b661..000000000 --- a/crates/pulsing-forge/src/cli/repl.rs +++ /dev/null @@ -1,646 +0,0 @@ -//! Forge session REPL. - -use std::future::Future; -use std::path::PathBuf; -use std::sync::Arc; - -use crate::context::{StepStatus, ToolSession}; -use crate::result::ToolResult; -use crate::runtime::{ToolRuntime, ToolRuntimeConfig}; -use crate::unified_exec::UnifiedExecManager; -use anyhow::{Result, anyhow}; -use comfy_table::{Table, presets::UTF8_FULL}; -use reedline::{ - ColumnarMenu, DefaultPrompt, DefaultPromptSegment, EditCommand, Emacs, FileBackedHistory, - KeyCode, KeyModifiers, MenuBuilder, Reedline, ReedlineEvent, ReedlineMenu, Signal, - default_emacs_keybindings, -}; -use serde_json::{Value, json}; - -use super::commands::{HELP, ParsedInput, SlashAction, parse_line, print_slash_menu}; -use super::completer::{ForgeCompleter, ForgeHinter}; -use super::parse::{parse_tool_args, parse_tool_invocation}; -use super::session::ReplToolSession; -use super::trace::{self, TraceRecord}; - -pub struct ReplConfig { - pub cwd: PathBuf, - pub sandbox: String, - pub dangerously_disable_sandbox: bool, - pub approve_auto: bool, - pub trace_path: Option, - pub record_path: Option, -} - -pub struct ForgeRepl { - session: Arc, - runtime: ToolRuntime, - exec: Arc, - trace: Vec, - trace_path: Option, - replay_index: usize, - record: Vec, - record_path: Option, - next_seq: u64, - cwd: PathBuf, - last_result: Option, -} - -impl ForgeRepl { - pub fn new(cfg: ReplConfig) -> Result { - let session = ReplToolSession::new(cfg.approve_auto); - let cwd = cfg.cwd.clone(); - let exec = Arc::new(UnifiedExecManager::new()); - let runtime = ToolRuntime::new(ToolRuntimeConfig { - cwd: cfg.cwd, - sandbox_policy: cfg.sandbox, - dangerously_disable_sandbox: cfg.dangerously_disable_sandbox, - session: session.clone(), - exec: exec.clone(), - ..Default::default() - }); - let trace = cfg - .trace_path - .as_ref() - .map(|p| trace::load_trace(p)) - .transpose()? - .unwrap_or_default(); - Ok(Self { - session, - runtime, - exec, - trace, - trace_path: cfg.trace_path, - replay_index: 0, - record: Vec::new(), - record_path: cfg.record_path, - next_seq: 1, - cwd, - last_result: None, - }) - } - - fn prompt(&self) -> DefaultPrompt { - let cwd = self.cwd.file_name().and_then(|s| s.to_str()).unwrap_or("."); - let mode = if self.session.approve_auto() { - "A" - } else { - "K" - }; - let replay = if trace::tool_calls(&self.trace).is_empty() { - String::new() - } else { - format!( - " {}/{}", - self.replay_index, - trace::tool_calls(&self.trace).len() - ) - }; - DefaultPrompt { - left_prompt: DefaultPromptSegment::Basic(format!("forge ⟨{cwd}⟩ {mode}{replay}⟩ ")), - ..Default::default() - } - } - - fn build_line_editor(&self) -> Result { - let tool_names = self.runtime.tool_names(); - let completer = Box::new(ForgeCompleter::new(tool_names.clone(), self.cwd.clone())); - let hinter = Box::new(ForgeHinter::new(tool_names, self.cwd.clone())); - let completion_menu = Box::new( - ColumnarMenu::default() - .with_name("completion_menu") - .with_columns(3), - ); - let mut keybindings = default_emacs_keybindings(); - keybindings.add_binding( - KeyModifiers::NONE, - KeyCode::Tab, - ReedlineEvent::UntilFound(vec![ - ReedlineEvent::Menu("completion_menu".to_string()), - ReedlineEvent::MenuNext, - ]), - ); - keybindings.add_binding( - KeyModifiers::ALT, - KeyCode::Enter, - ReedlineEvent::Edit(vec![EditCommand::InsertNewline]), - ); - let history = Box::new( - FileBackedHistory::with_file(1000, ".pforge_history".into()) - .map_err(|e| anyhow!("history: {e}"))?, - ); - Ok(Reedline::create() - .with_history(history) - .with_completer(completer) - .with_hinter(hinter) - .with_menu(ReedlineMenu::EngineCompleter(completion_menu)) - .with_edit_mode(Box::new(Emacs::new(keybindings)))) - } - - pub fn run_interactive(&mut self) -> Result<()> { - let mut line_editor = self.build_line_editor()?; - println!("{HELP}"); - if !self.trace.is_empty() { - println!( - "loaded trace: {} tool calls (/replay or replay all)", - trace::tool_calls(&self.trace).len() - ); - } - loop { - match line_editor.read_line(&self.prompt()) { - Ok(Signal::Success(line)) => match self.dispatch(&line) { - Ok(true) => {} - Ok(false) => break, - Err(e) => eprintln!("error: {e:#}"), - }, - Ok(Signal::CtrlC) | Ok(Signal::CtrlD) => { - println!(); - break; - } - Err(e) => return Err(anyhow!("readline: {e}")), - } - } - Ok(()) - } - - pub async fn replay_all(&mut self, dry_run: bool, verify: bool) -> Result> { - let mut lines = Vec::new(); - loop { - let msg = self.replay_step(dry_run, verify).await?; - let done = msg.contains("complete") || msg.starts_with("no trace"); - lines.push(msg); - if done { - break; - } - } - Ok(lines) - } - - fn dispatch(&mut self, line: &str) -> Result { - match parse_line(line) { - ParsedInput::Empty => Ok(true), - ParsedInput::SlashMenu => { - print_slash_menu(); - Ok(true) - } - ParsedInput::Slash { action, args } => self.dispatch_slash(action, &args), - ParsedInput::Mention(path) => { - self.exec_call("Read", json!({ "file_path": path }))?; - Ok(true) - } - ParsedInput::Meta(cmd) => self.dispatch_meta(&cmd), - ParsedInput::Bare(line) => self.dispatch_bare(&line), - } - } - - fn dispatch_slash(&mut self, action: SlashAction, args: &str) -> Result { - match action { - SlashAction::Meta(cmd) => self.dispatch_meta(format!("{cmd} {args}").trim()), - SlashAction::Clear => { - print!("\x1b[2J\x1b[H"); - Ok(true) - } - SlashAction::Diff | SlashAction::Review => { - self.exec_call( - "shell_command", - json!({ "command": "git diff && git diff --cached && git status -sb" }), - )?; - Ok(true) - } - SlashAction::Ps => { - let sessions = run_async(self.exec.list_sessions())?; - if sessions.is_empty() { - println!("(no background exec sessions)"); - } else { - let mut table = Table::new(); - table.load_preset(UTF8_FULL); - table.set_header(["id", "elapsed_s", "tty"]); - for s in sessions { - table.add_row([ - s.id.to_string(), - format!("{:.1}", s.elapsed_secs), - s.tty.to_string(), - ]); - } - println!("{table}"); - } - Ok(true) - } - SlashAction::Stop => { - let n = run_async(self.exec.stop_all())?; - println!("stopped {n} exec session(s)"); - Ok(true) - } - SlashAction::Fork => { - let step: usize = args.trim().parse().map_err(|_| anyhow!("usage: /fork N"))?; - self.fork_trace(step)?; - println!( - "forked trace at step {step}; replay_index={}", - self.replay_index - ); - Ok(true) - } - SlashAction::Compact => { - self.exec_call("new_context", json!({}))?; - Ok(true) - } - SlashAction::Mcp => { - let mcp: Vec<_> = self - .runtime - .tool_names() - .into_iter() - .filter(|n| n.contains("mcp")) - .collect(); - if mcp.is_empty() { - println!("(no MCP tools registered)"); - } else { - for n in mcp { - println!(" {n}"); - } - } - Ok(true) - } - SlashAction::Plugins => { - self.exec_call("list_available_plugins_to_install", json!({}))?; - Ok(true) - } - SlashAction::Mention => { - let path = args.trim(); - if path.is_empty() { - return Err(anyhow!("usage: /mention PATH")); - } - self.exec_call("Read", json!({ "file_path": path }))?; - Ok(true) - } - SlashAction::Rollout => { - if let Some(p) = &self.trace_path { - println!("trace: {}", p.display()); - } - if let Some(p) = &self.record_path { - println!("record: {} ({} lines)", p.display(), self.record.len()); - } - if self.trace_path.is_none() && self.record_path.is_none() { - println!("(no --trace or --record path)"); - } - Ok(true) - } - SlashAction::Copy => { - match &self.last_result { - Some(r) => println!("{}", r.content), - None => println!("(no tool result yet)"), - } - Ok(true) - } - } - } - - fn dispatch_meta(&mut self, line: &str) -> Result { - let mut parts = line.split_whitespace(); - let cmd = parts.next().unwrap_or("help"); - match cmd { - "help" | "?" => println!("{HELP}"), - "quit" | "exit" => return Ok(false), - "tools" => println!("{}", self.format_tools_table()), - "session" | "status" => println!("{}", self.format_session_table()), - "plan" => println!("{}", self.format_plan_table()), - "events" => println!("{}", self.format_events_table()), - "approve" | "permissions" => self.set_approval(parts.next()), - "replay" => self.run_replay(&parts.collect::>())?, - "trace" => self.run_trace(&mut parts)?, - "fork" => { - let step: usize = parts - .next() - .ok_or_else(|| anyhow!("usage: fork N"))? - .parse() - .map_err(|_| anyhow!("fork step must be integer"))?; - self.fork_trace(step)?; - println!("forked at step {step}"); - } - "call" => { - let tool = parts - .next() - .ok_or_else(|| anyhow!("usage: call TOOL {{json}}"))?; - let args = parse_tool_args(parts.collect::>().join(" ").trim())?; - self.exec_call(tool, args)?; - } - other => return Err(anyhow!("unknown command: {other} (try /help)")), - } - Ok(true) - } - - fn dispatch_bare(&mut self, line: &str) -> Result { - let lower = line.to_lowercase(); - if matches!(lower.as_str(), "help" | "?") { - println!("{HELP}"); - return Ok(true); - } - if matches!(lower.as_str(), "quit" | "exit") { - return Ok(false); - } - for prefix in [ - "tools", - "session", - "plan", - "events", - "replay", - "approve", - "permissions", - "trace", - "fork", - ] { - if lower == prefix || lower.starts_with(&format!("{prefix} ")) { - return self.dispatch_meta(line); - } - } - if let Some(rest) = line.strip_prefix("call ") { - let (tool, args) = parse_tool_invocation(rest.trim())?; - self.exec_call(&tool, args)?; - return Ok(true); - } - if let Some((tool, rest)) = line.split_once(' ') - && self.runtime.tool_names().iter().any(|n| n == tool) - { - self.exec_call(tool, parse_tool_args(rest)?)?; - return Ok(true); - } - if self.runtime.tool_names().iter().any(|n| n == line) { - self.exec_call(line, json!({}))?; - return Ok(true); - } - Err(anyhow!("unknown: {line:?} (try /help)")) - } - - fn set_approval(&self, mode: Option<&str>) { - match mode { - Some(m) => { - let auto = m.eq_ignore_ascii_case("auto"); - self.session.set_approve_auto(auto); - println!("approval → {}", if auto { "auto" } else { "ask" }); - } - None => println!( - "approval: {}", - if self.session.approve_auto() { - "auto" - } else { - "ask" - } - ), - } - } - - fn run_replay(&mut self, rest: &[&str]) -> Result<()> { - let dry = rest.contains(&"dry"); - let verify = rest.contains(&"verify"); - if rest.contains(&"all") { - for msg in run_async(self.replay_all(dry, verify))?? { - println!("{msg}"); - } - } else { - println!("{}", run_async(self.replay_step(dry, verify))??); - } - Ok(()) - } - - fn run_trace(&mut self, parts: &mut std::str::SplitWhitespace<'_>) -> Result<()> { - match parts.next() { - Some("show") => { - if let Some(path) = &self.record_path { - println!( - "recording → {} ({} lines)", - path.display(), - self.record.len() - ); - } else { - println!("(not recording; use --record or trace save PATH)"); - } - } - Some("save") => { - let path = PathBuf::from( - parts - .next() - .ok_or_else(|| anyhow!("usage: trace save PATH"))?, - ); - trace::save_trace(&path, &self.record)?; - self.record_path = Some(path.clone()); - println!("saved {} records → {}", self.record.len(), path.display()); - } - _ => println!("usage: trace save PATH | trace show"), - } - Ok(()) - } - - fn fork_trace(&mut self, step: usize) -> Result<()> { - if self.trace.is_empty() { - return Err(anyhow!("no trace loaded")); - } - self.replay_index = 0; - let records: Vec<_> = self.trace.clone(); - for rec in &records { - if rec.seq > step as u64 { - break; - } - if rec.kind == "session" { - if let Some(snap) = &rec.session { - self.apply_session(snap); - } - } else if rec.kind == "tool_call" && rec.seq <= step as u64 { - if let Some(tool) = &rec.tool - && self.runtime.tool_names().iter().any(|n| n == tool) - { - self.exec_call(tool, rec.arguments.clone().unwrap_or(json!({})))?; - } - self.replay_index += 1; - } - } - Ok(()) - } - - fn apply_session(&self, snap: &Value) { - use crate::context::{PlanItem, UpdatePlanArgs}; - if let Some(plan_raw) = snap.get("plan").and_then(|v| v.as_array()) { - let items: Vec = plan_raw - .iter() - .filter_map(|p| { - Some(PlanItem { - step: p.get("step")?.as_str()?.to_string(), - status: match p.get("status")?.as_str()? { - "in_progress" => StepStatus::InProgress, - "completed" => StepStatus::Completed, - _ => StepStatus::Pending, - }, - }) - }) - .collect(); - if !items.is_empty() { - let _ = self.session.update_plan(UpdatePlanArgs { - explanation: None, - plan: items, - }); - } - } - } - - fn exec_call(&mut self, tool: &str, args: Value) -> Result<()> { - let out = run_async(self.runtime.call_tool(tool, args.clone()))?; - self.last_result = Some(out.clone()); - if let Some(path) = &self.record_path { - self.record.push(TraceRecord { - seq: self.next_seq, - kind: "tool_call".into(), - tool: Some(tool.into()), - arguments: Some(args), - result: Some(json!({ - "content": out.content, - "is_error": out.is_error, - "structured": out.structured, - })), - event: None, - session: None, - }); - self.next_seq += 1; - trace::save_trace(path, &self.record)?; - } - let payload = json!({ - "tool": tool, - "is_error": out.is_error, - "content": out.content.chars().take(2000).collect::(), - "structured": out.structured, - }); - println!("{}", serde_json::to_string_pretty(&payload)?); - Ok(()) - } - - async fn replay_step(&mut self, dry_run: bool, verify: bool) -> Result { - let calls = trace::tool_calls(&self.trace); - if calls.is_empty() { - return Ok("no trace loaded".into()); - } - if self.replay_index >= calls.len() { - return Ok("replay complete".into()); - } - let rec = calls[self.replay_index]; - self.replay_index += 1; - let tool = rec.tool.as_deref().unwrap_or("?"); - let args = rec.arguments.clone().unwrap_or(json!({})); - if dry_run { - return Ok(format!( - "dry-run #{} call {} {}", - rec.seq, - tool, - serde_json::to_string(&args)? - )); - } - let out = self.runtime.call_tool(tool, args).await; - self.last_result = Some(out.clone()); - if verify && let Some(exp) = &rec.result { - let exp_err = exp - .get("is_error") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - if out.is_error != exp_err { - return Ok(format!( - "verify FAIL #{} {tool}: is_error expected {exp_err} got {}", - rec.seq, out.is_error - )); - } - } - let flag = if out.is_error { "ERR" } else { "ok" }; - let preview: String = out.content.chars().take(400).collect(); - Ok(format!("replay #{} {tool} [{flag}] {preview}", rec.seq)) - } - - fn format_tools_table(&self) -> String { - let mut table = Table::new(); - table.load_preset(UTF8_FULL); - table.set_header(["tool"]); - for name in self.runtime.tool_names() { - table.add_row([name]); - } - table.to_string() - } - - fn format_plan_table(&self) -> String { - let plan = self.session.plan_snapshot(); - if plan.is_empty() { - return "(empty plan)".into(); - } - let mut table = Table::new(); - table.load_preset(UTF8_FULL); - table.set_header(["step", "status"]); - for item in plan { - let status = match item.status { - StepStatus::Pending => "pending", - StepStatus::InProgress => "in_progress", - StepStatus::Completed => "completed", - }; - table.add_row([item.step, status.to_string()]); - } - table.to_string() - } - - fn format_events_table(&self) -> String { - let deltas = self.session.exec_deltas(); - if deltas.is_empty() { - return "(no exec output deltas yet)".into(); - } - let mut table = Table::new(); - table.load_preset(UTF8_FULL); - table.set_header(["kind", "preview"]); - for d in deltas.iter().rev().take(12).rev() { - let preview: String = format!("{d:?}").chars().take(80).collect(); - table.add_row(["exec_delta".to_string(), preview]); - } - table.to_string() - } - - fn format_session_table(&self) -> String { - let mut table = Table::new(); - table.load_preset(UTF8_FULL); - table.set_header(["field", "value"]); - table.add_row(["cwd".to_string(), self.cwd.display().to_string()]); - table.add_row([ - "approval".to_string(), - if self.session.approve_auto() { - "auto".to_string() - } else { - "ask".to_string() - }, - ]); - table.add_row([ - "plan".to_string(), - self.session.plan_snapshot().len().to_string(), - ]); - table.add_row([ - "new_context".to_string(), - self.session.new_context_requested().to_string(), - ]); - if let Some(tokens) = self.session.tokens_remaining() { - table.add_row(["tokens_remaining".to_string(), tokens.to_string()]); - } - table.add_row([ - "replay".to_string(), - format!( - "{}/{}", - self.replay_index, - trace::tool_calls(&self.trace).len() - ), - ]); - table.to_string() - } -} - -fn run_async(fut: F) -> Result -where - F: Future, -{ - match tokio::runtime::Handle::try_current() { - Ok(handle) => Ok(tokio::task::block_in_place(|| handle.block_on(fut))), - Err(_) => { - let rt = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|e| anyhow!("runtime: {e}"))?; - Ok(rt.block_on(fut)) - } - } -} diff --git a/crates/pulsing-forge/src/cli/session.rs b/crates/pulsing-forge/src/cli/session.rs deleted file mode 100644 index b50888130..000000000 --- a/crates/pulsing-forge/src/cli/session.rs +++ /dev/null @@ -1,237 +0,0 @@ -//! REPL ToolSession — wires exec/permissions approval to stdin (Codex-style). - -use std::io::{self, Write}; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; - -use crate::approval::{ - ApprovalPolicy, ExecApprovalRequest, RequestPermissionsArgs, RequestPermissionsResponse, - ReviewDecision, -}; -use crate::context::{LocalToolSession, PlanItem, ToolSession, UpdatePlanArgs}; -use crate::error::ToolError; -use crate::exec_output::ExecOutputDelta; -use serde_json::{Value, json}; - -pub struct ReplToolSession { - inner: LocalToolSession, - approve_auto: Arc, -} - -impl ReplToolSession { - pub fn new(approve_auto: bool) -> Arc { - let flag = Arc::new(AtomicBool::new(approve_auto)); - let flag_exec = flag.clone(); - let flag_perm = flag.clone(); - let flag_input = flag.clone(); - let flag_plugin = flag.clone(); - - let inner = LocalToolSession::default() - .with_exec_approval(move |req| prompt_exec(&flag_exec, req)) - .with_request_permissions(move |args| prompt_permissions(&flag_perm, args)) - .with_user_input(move |args| prompt_user_input(&flag_input, args)) - .with_plugin_install(move |tool_id, tool_name, suggest_reason| { - prompt_plugin(&flag_plugin, &tool_id, &tool_name, &suggest_reason) - }); - - Arc::new(Self { - inner, - approve_auto: flag, - }) - } - - pub fn set_approve_auto(&self, auto: bool) { - self.approve_auto.store(auto, Ordering::Relaxed); - } - - pub fn approve_auto(&self) -> bool { - self.approve_auto.load(Ordering::Relaxed) - } - - pub fn plan_snapshot(&self) -> Vec { - self.inner.plan_snapshot() - } - - pub fn new_context_requested(&self) -> bool { - self.inner.new_context_requested() - } - - pub fn exec_deltas(&self) -> Vec { - self.inner.exec_deltas() - } - - pub fn tokens_remaining(&self) -> Option { - self.inner.tokens_remaining() - } -} - -impl ToolSession for ReplToolSession { - fn update_plan(&self, args: UpdatePlanArgs) -> Result<(), ToolError> { - self.inner.update_plan(args) - } - - fn request_new_context(&self) -> Result<(), ToolError> { - self.inner.request_new_context() - } - - fn tokens_remaining(&self) -> Option { - self.inner.tokens_remaining() - } - - fn request_user_input(&self, arguments: Value) -> Result { - self.inner.request_user_input(arguments) - } - - fn on_exec_output_delta(&self, delta: ExecOutputDelta) -> Result<(), ToolError> { - self.inner.on_exec_output_delta(delta) - } - - fn approval_policy(&self) -> ApprovalPolicy { - if self.approve_auto.load(Ordering::Relaxed) { - ApprovalPolicy::Always - } else { - ApprovalPolicy::OnRequest - } - } - - fn request_exec_approval( - &self, - request: ExecApprovalRequest, - ) -> Result { - self.inner.request_exec_approval(request) - } - - fn request_permissions( - &self, - args: RequestPermissionsArgs, - ) -> Result { - self.inner.request_permissions(args) - } - - fn request_plugin_install( - &self, - tool_id: String, - tool_name: String, - suggest_reason: String, - ) -> Result { - self.inner - .request_plugin_install(tool_id, tool_name, suggest_reason) - } -} - -fn prompt_exec( - approve_auto: &AtomicBool, - req: ExecApprovalRequest, -) -> Result { - if approve_auto.load(Ordering::Relaxed) { - return Ok(ReviewDecision::Approved); - } - let cmd = req.command.join(" "); - eprintln!("\n── exec approval ──"); - eprintln!("command: {cmd}"); - if let Some(reason) = &req.reason { - eprintln!("reason: {reason}"); - } - eprint!(" [y] once [a] session [n] deny > "); - let _ = io::stderr().flush(); - let choice = read_stdin_line()?; - match choice.trim().to_ascii_lowercase().as_str() { - "y" | "yes" => Ok(ReviewDecision::Approved), - "a" | "allow" | "session" => Ok(ReviewDecision::ApprovedForSession), - _ => Ok(ReviewDecision::Denied), - } -} - -fn prompt_permissions( - approve_auto: &AtomicBool, - args: RequestPermissionsArgs, -) -> Result { - if approve_auto.load(Ordering::Relaxed) { - return Ok(RequestPermissionsResponse { - permissions: args.permissions, - scope: "session".into(), - strict_auto_review: false, - }); - } - eprintln!("\n── permissions request ──"); - if let Some(reason) = &args.reason { - eprintln!("reason: {reason}"); - } - eprint!("grant permissions? [y/N/a=session] > "); - let _ = io::stderr().flush(); - let choice = read_stdin_line()?; - match choice.trim().to_ascii_lowercase().as_str() { - "y" | "yes" | "a" | "allow" => Ok(RequestPermissionsResponse { - permissions: args.permissions, - scope: if choice.starts_with('a') { - "session".into() - } else { - "once".into() - }, - strict_auto_review: false, - }), - _ => Err(ToolError::respond("permissions denied by user")), - } -} - -fn prompt_user_input(approve_auto: &AtomicBool, args: Value) -> Result { - if approve_auto.load(Ordering::Relaxed) { - if let Some(questions) = args.get("questions").and_then(|q| q.as_array()) - && let Some(q0) = questions.first() - { - let id = q0.get("id").and_then(|v| v.as_str()).unwrap_or("q0"); - if let Some(opts) = q0.get("options").and_then(|o| o.as_array()) - && let Some(opt) = opts.first() - { - let label = opt.get("label").and_then(|v| v.as_str()).unwrap_or("yes"); - return Ok(json!({ "answers": { id: label } })); - } - } - return Ok(json!({ "answers": {} })); - } - eprintln!("\n── user input request ──"); - eprintln!( - "{}", - serde_json::to_string_pretty(&args).unwrap_or_default() - ); - eprint!("accept first option? [Y/n/custom JSON] > "); - let _ = io::stderr().flush(); - let line = read_stdin_line()?; - let trimmed = line.trim(); - if trimmed.is_empty() - || trimmed.eq_ignore_ascii_case("y") - || trimmed.eq_ignore_ascii_case("yes") - { - return prompt_user_input(&AtomicBool::new(true), args); - } - if trimmed.eq_ignore_ascii_case("n") || trimmed.eq_ignore_ascii_case("no") { - return Ok(json!({ "answers": {} })); - } - serde_json::from_str(trimmed).map_err(|e| ToolError::respond(format!("invalid JSON: {e}"))) -} - -fn prompt_plugin( - approve_auto: &AtomicBool, - tool_id: &str, - tool_name: &str, - suggest_reason: &str, -) -> Result { - if approve_auto.load(Ordering::Relaxed) { - return Ok(true); - } - eprint!("\ninstall plugin {tool_name} ({tool_id})? reason: {suggest_reason} [y/N] > "); - let _ = io::stderr().flush(); - let line = read_stdin_line()?; - Ok(matches!( - line.trim().to_ascii_lowercase().as_str(), - "y" | "yes" | "allow" - )) -} - -fn read_stdin_line() -> Result { - let mut buf = String::new(); - io::stdin() - .read_line(&mut buf) - .map_err(|e| ToolError::respond(format!("stdin: {e}")))?; - Ok(buf) -} diff --git a/crates/pulsing-forge/src/cli/trace.rs b/crates/pulsing-forge/src/cli/trace.rs deleted file mode 100644 index 2494d5350..000000000 --- a/crates/pulsing-forge/src/cli/trace.rs +++ /dev/null @@ -1,56 +0,0 @@ -//! JSONL trace — same format as ``python/pulsing/forge/repl/trace.py``. - -use std::fs::File; -use std::io::{BufRead, BufReader, Write}; -use std::path::Path; - -use anyhow::{Context, Result}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct TraceRecord { - pub seq: u64, - pub kind: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub tool: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub arguments: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub event: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub session: Option, -} - -pub fn load_trace(path: &Path) -> Result> { - let file = File::open(path).with_context(|| format!("open trace {}", path.display()))?; - let mut out = Vec::new(); - for line in BufReader::new(file).lines() { - let line = line?; - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - out.push(serde_json::from_str(line)?); - } - Ok(out) -} - -pub fn save_trace(path: &Path, records: &[TraceRecord]) -> Result<()> { - if let Some(parent) = path.parent() - && !parent.as_os_str().is_empty() - { - std::fs::create_dir_all(parent)?; - } - let mut file = File::create(path)?; - for rec in records { - writeln!(file, "{}", serde_json::to_string(rec)?)?; - } - Ok(()) -} - -pub fn tool_calls(records: &[TraceRecord]) -> Vec<&TraceRecord> { - records.iter().filter(|r| r.kind == "tool_call").collect() -} diff --git a/crates/pulsing-forge/src/context.rs b/crates/pulsing-forge/src/context.rs deleted file mode 100644 index d187b2bac..000000000 --- a/crates/pulsing-forge/src/context.rs +++ /dev/null @@ -1,359 +0,0 @@ -//! Host-facing abstractions for session/plan tools (framework-agnostic). - -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; - -use serde::{Deserialize, Serialize}; - -use crate::approval::{ - ApprovalCache, ApprovalPolicy, ExecApprovalRequest, RequestPermissionsArgs, - RequestPermissionsResponse, ReviewDecision, -}; -use crate::discovery::ToolCatalog; -use crate::execpolicy::ExecPolicy; - -use crate::error::ToolError; -use crate::exec_output::ExecOutputDelta; -use crate::sandbox::{SandboxPolicy, normalize_policy}; -use crate::unified_exec::UnifiedExecManager; - -/// Plan step status for collaborative plan tools. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum StepStatus { - Pending, - InProgress, - Completed, -} - -/// Single plan item for `update_plan`. -/// Mirrors Codex's `PlanItemArg` (vendor/codex-rs/protocol/src/plan_tool.rs). -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct PlanItem { - pub step: String, - pub status: StepStatus, -} - -/// Arguments for the `update_plan` tool. -/// Mirrors Codex's `UpdatePlanArgs` (vendor/codex-rs/protocol/src/plan_tool.rs). -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct UpdatePlanArgs { - #[serde(default)] - pub explanation: Option, - pub plan: Vec, -} - -/// Callback host for plan/session tools. Implementations live in Craft, CLI, tests, etc. -pub trait ToolSession: Send + Sync { - fn update_plan(&self, args: UpdatePlanArgs) -> Result<(), ToolError>; - - fn request_new_context(&self) -> Result<(), ToolError>; - - fn tokens_remaining(&self) -> Option; - - /// Host shows UI and returns structured answers JSON. - fn request_user_input( - &self, - arguments: serde_json::Value, - ) -> Result; - - /// Streaming unified-exec output (Codex `ExecCommandOutputDelta` equivalent). - fn on_exec_output_delta(&self, _delta: ExecOutputDelta) -> Result<(), ToolError> { - Ok(()) - } - - /// Host approval policy for shell / exec (Codex `AskForApproval` subset). - fn approval_policy(&self) -> ApprovalPolicy { - ApprovalPolicy::OnRequest - } - - /// Prompt user before running a shell command (Codex ExecApprovalRequest). - fn request_exec_approval( - &self, - _request: ExecApprovalRequest, - ) -> Result { - Err(ToolError::respond( - "exec approval is not configured on this ToolSession", - )) - } - - /// Resolve `request_permissions` tool (Codex permission escalation). - fn request_permissions( - &self, - _args: RequestPermissionsArgs, - ) -> Result { - Err(ToolError::respond( - "request_permissions is not configured on this ToolSession", - )) - } - - /// Prompt before installing a Codex-compatible plugin. - fn request_plugin_install( - &self, - _tool_id: String, - _tool_name: String, - _suggest_reason: String, - ) -> Result { - Err(ToolError::respond( - "request_plugin_install is not configured on this ToolSession", - )) - } -} - -/// Per-invocation context passed to every handler. -#[derive(Clone)] -pub struct ToolCallContext { - pub cwd: PathBuf, - pub sandbox_policy: SandboxPolicy, - pub dangerously_disable_sandbox: bool, - pub session: Arc, - pub exec: Arc, - pub exec_policy: Arc>, - pub approval_cache: Arc, - pub tool_catalog: Arc>, - pub mcp_runtime: Option, - pub turn: Option>, -} - -impl ToolCallContext { - pub fn new( - cwd: impl AsRef, - sandbox_policy: &str, - session: Arc, - exec: Arc, - exec_policy: Arc>, - approval_cache: Arc, - tool_catalog: Arc>, - ) -> Self { - Self { - cwd: cwd.as_ref().to_path_buf(), - sandbox_policy: normalize_policy(sandbox_policy), - dangerously_disable_sandbox: false, - session, - exec, - exec_policy, - approval_cache, - tool_catalog, - mcp_runtime: None, - turn: None, - } - } - - pub fn with_mcp_runtime(mut self, mcp: crate::mcp::SharedMcpRuntime) -> Self { - self.mcp_runtime = Some(mcp); - self - } - - pub fn with_dangerous_sandbox(mut self, disable: bool) -> Self { - self.dangerously_disable_sandbox = disable; - self - } - - pub fn with_turn(mut self, turn: Arc) -> Self { - self.turn = Some(turn); - self - } -} - -/// In-memory session for local runs and tests. -pub struct LocalToolSession { - plan: std::sync::Mutex>, - new_context_requested: std::sync::Mutex, - tokens_remaining: Option, - user_input: Option< - Arc Result + Send + Sync>, - >, - exec_deltas: std::sync::Mutex>, - exec_approval: - Option Result + Send + Sync>>, - permissions: Option< - Arc< - dyn Fn(RequestPermissionsArgs) -> Result - + Send - + Sync, - >, - >, - plugin_install: - Option Result + Send + Sync>>, - approval_policy: ApprovalPolicy, -} - -impl Default for LocalToolSession { - fn default() -> Self { - Self { - plan: std::sync::Mutex::new(Vec::new()), - new_context_requested: std::sync::Mutex::new(false), - tokens_remaining: None, - user_input: None, - exec_deltas: std::sync::Mutex::new(Vec::new()), - exec_approval: None, - permissions: None, - plugin_install: None, - approval_policy: ApprovalPolicy::OnRequest, - } - } -} - -impl LocalToolSession { - pub fn new(tokens_remaining: Option) -> Self { - Self { - tokens_remaining, - ..Default::default() - } - } - - pub fn with_user_input(mut self, f: F) -> Self - where - F: Fn(serde_json::Value) -> Result + Send + Sync + 'static, - { - self.user_input = Some(Arc::new(f)); - self - } - - pub fn with_exec_approval(mut self, f: F) -> Self - where - F: Fn(ExecApprovalRequest) -> Result + Send + Sync + 'static, - { - self.exec_approval = Some(Arc::new(f)); - self - } - - pub fn with_request_permissions(mut self, f: F) -> Self - where - F: Fn(RequestPermissionsArgs) -> Result - + Send - + Sync - + 'static, - { - self.permissions = Some(Arc::new(f)); - self - } - - pub fn with_plugin_install(mut self, f: F) -> Self - where - F: Fn(String, String, String) -> Result + Send + Sync + 'static, - { - self.plugin_install = Some(Arc::new(f)); - self - } - - pub fn with_approval_policy(mut self, policy: ApprovalPolicy) -> Self { - self.approval_policy = policy; - self - } - - pub fn plan_snapshot(&self) -> Vec { - self.plan.lock().unwrap().clone() - } - - pub fn new_context_requested(&self) -> bool { - *self.new_context_requested.lock().unwrap() - } - - pub fn exec_deltas(&self) -> Vec { - self.exec_deltas.lock().unwrap().clone() - } -} - -impl ToolSession for LocalToolSession { - fn update_plan(&self, args: UpdatePlanArgs) -> Result<(), ToolError> { - *self.plan.lock().unwrap() = args.plan; - Ok(()) - } - - fn request_new_context(&self) -> Result<(), ToolError> { - *self.new_context_requested.lock().unwrap() = true; - Ok(()) - } - - fn tokens_remaining(&self) -> Option { - self.tokens_remaining - } - - fn request_user_input( - &self, - arguments: serde_json::Value, - ) -> Result { - match &self.user_input { - Some(f) => f(arguments), - None => Err(ToolError::respond( - "request_user_input is not configured on this ToolSession", - )), - } - } - - fn on_exec_output_delta(&self, delta: ExecOutputDelta) -> Result<(), ToolError> { - self.exec_deltas.lock().unwrap().push(delta); - Ok(()) - } - - fn approval_policy(&self) -> ApprovalPolicy { - self.approval_policy - } - - fn request_exec_approval( - &self, - request: ExecApprovalRequest, - ) -> Result { - match &self.exec_approval { - Some(f) => f(request), - None => Err(ToolError::respond( - "exec approval is not configured on this ToolSession", - )), - } - } - - fn request_permissions( - &self, - args: RequestPermissionsArgs, - ) -> Result { - match &self.permissions { - Some(f) => f(args), - None => Err(ToolError::respond( - "request_permissions is not configured on this ToolSession", - )), - } - } - - fn request_plugin_install( - &self, - tool_id: String, - tool_name: String, - suggest_reason: String, - ) -> Result { - match &self.plugin_install { - Some(f) => f(tool_id, tool_name, suggest_reason), - None => Err(ToolError::respond( - "request_plugin_install is not configured on this ToolSession", - )), - } - } -} - -/// No-op session when host does not care about plan/session side effects. -pub struct NullToolSession; - -impl ToolSession for NullToolSession { - fn update_plan(&self, _args: UpdatePlanArgs) -> Result<(), ToolError> { - Ok(()) - } - - fn request_new_context(&self) -> Result<(), ToolError> { - Ok(()) - } - - fn tokens_remaining(&self) -> Option { - None - } - - fn request_user_input( - &self, - _arguments: serde_json::Value, - ) -> Result { - Err(ToolError::respond( - "request_user_input is not available in this runtime", - )) - } -} diff --git a/crates/pulsing-forge/src/discovery/bm25.rs b/crates/pulsing-forge/src/discovery/bm25.rs deleted file mode 100644 index eb82f42a9..000000000 --- a/crates/pulsing-forge/src/discovery/bm25.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! BM25-lite scoring for tool_search. - -pub fn tokenize(text: &str) -> Vec { - text.to_lowercase() - .split(|c: char| !c.is_alphanumeric() && c != '_') - .filter(|t| !t.is_empty()) - .map(str::to_string) - .collect() -} - -pub fn bm25_scores(query: &str, documents: &[String]) -> Vec { - let q_terms = tokenize(query); - if q_terms.is_empty() || documents.is_empty() { - return vec![0.0; documents.len()]; - } - - let doc_terms: Vec> = documents.iter().map(|d| tokenize(d)).collect(); - let n = documents.len() as f64; - let avgdl = doc_terms.iter().map(|t| t.len() as f64).sum::() / n.max(1.0); - - let mut df = std::collections::HashMap::new(); - for terms in &doc_terms { - let mut seen = std::collections::HashSet::new(); - for t in terms { - if seen.insert(t.clone()) { - *df.entry(t.clone()).or_insert(0usize) += 1; - } - } - } - - let k1 = 1.5; - let b = 0.75; - - doc_terms - .iter() - .map(|terms| { - let dl = terms.len() as f64; - let mut score = 0.0; - for qt in &q_terms { - let tf = terms.iter().filter(|t| *t == qt).count() as f64; - if tf == 0.0 { - continue; - } - let df_q = *df.get(qt).unwrap_or(&0) as f64; - let idf = ((n - df_q + 0.5) / (df_q + 0.5) + 1.0).ln(); - score += idf * (tf * (k1 + 1.0)) / (tf + k1 * (1.0 - b + b * dl / avgdl.max(1.0))); - } - score - }) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ranks_github_higher() { - let docs = vec![ - "filesystem read write grep".into(), - "github pull request mcp server".into(), - ]; - let scores = bm25_scores("github mcp", &docs); - assert!(scores[1] > scores[0]); - } - - #[test] - fn empty_query_scores_everything_zero() { - let docs = vec!["github mcp server".into(), "filesystem tools".into()]; - assert_eq!(bm25_scores("", &docs), vec![0.0, 0.0]); - assert_eq!(bm25_scores(" ", &docs), vec![0.0, 0.0]); - } - - #[test] - fn punctuation_only_query_has_no_terms() { - // Tokenize drops non-alphanumeric characters, so a query made only of - // punctuation/symbols reduces to zero terms — matches the empty-query case. - let docs = vec!["github mcp server".into()]; - assert_eq!(bm25_scores("!!! ??? ---", &docs), vec![0.0]); - } - - #[test] - fn no_documents_returns_empty_scores() { - assert_eq!(bm25_scores("github", &[]), Vec::::new()); - } -} diff --git a/crates/pulsing-forge/src/discovery/catalog.rs b/crates/pulsing-forge/src/discovery/catalog.rs deleted file mode 100644 index 79a1b12f4..000000000 --- a/crates/pulsing-forge/src/discovery/catalog.rs +++ /dev/null @@ -1,390 +0,0 @@ -//! In-memory deferred tool catalog. - -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -use super::bm25; - -pub const TOOL_SEARCH_DEFAULT_LIMIT: usize = 8; -/// Upper bound on `tool_search` `limit`; guards against unbounded results for a -/// pathological/huge value from the model. Non-positive or unparsable values fall -/// back to [`TOOL_SEARCH_DEFAULT_LIMIT`] instead. -pub const TOOL_SEARCH_MAX_LIMIT: usize = 100; - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct DeferredToolEntry { - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub namespace: Option, - pub description: String, - pub parameters: Value, - pub search_text: String, - #[serde(default)] - pub defer_loading: bool, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub plugin_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub source: Option, -} - -impl DeferredToolEntry { - pub fn from_function(name: &str, description: &str, parameters: Value) -> Self { - let search_text = format!("{name} {} {}", name.replace('_', " "), description); - Self { - name: name.to_string(), - namespace: None, - description: description.to_string(), - parameters, - search_text, - defer_loading: true, - plugin_id: None, - source: None, - } - } -} - -use super::codex_manifest::load_codex_manifest; -use super::codex_paths::{ - TOOL_SUGGEST_PLUGIN_ALLOWLIST, discover_all_plugins_enabled, forge_plugin_state_path, - plugins_cache_root, -}; -use super::marketplace::{InstallPolicy, list_marketplaces}; -use super::plugins::{ - DiscoverablePlugin, PluginManifest, load_plugin_manifests, scan_codex_plugin_dirs, -}; -use std::path::{Path, PathBuf}; - -#[derive(Clone, Debug, Default)] -pub struct ToolCatalog { - deferred: Vec, - discoverable: Vec, - installed_plugin_ids: std::collections::HashSet, -} - -#[derive(Clone, Debug, Serialize)] -pub struct ToolCatalogSnapshot { - pub tools: Vec, -} - -impl ToolCatalog { - pub fn register_deferred(&mut self, entry: DeferredToolEntry) { - if self.deferred.iter().any(|e| e.name == entry.name) { - self.deferred.retain(|e| e.name != entry.name); - } - self.deferred.push(entry); - } - - pub fn mark_plugin_installed(&mut self, plugin_id: &str) { - self.installed_plugin_ids.insert(plugin_id.to_string()); - } - - pub fn is_plugin_installed(&self, plugin_id: &str) -> bool { - self.installed_plugin_ids.contains(plugin_id) - } - - pub fn search(&self, query: &str, limit: usize) -> Vec { - let docs: Vec = self - .deferred - .iter() - .map(|e| e.search_text.clone()) - .collect(); - let scores = bm25::bm25_scores(query, &docs); - let mut ranked: Vec<(usize, f64)> = scores.into_iter().enumerate().collect(); - ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); - ranked - .into_iter() - .filter(|(_, s)| *s > 0.0) - .take(limit) - .map(|(i, _)| self.deferred[i].clone()) - .collect() - } - - pub fn snapshot(&self) -> ToolCatalogSnapshot { - ToolCatalogSnapshot { - tools: self.deferred.clone(), - } - } - - pub fn load_codex_plugins(&mut self, extra_dirs: &[PathBuf]) { - let _ = self.refresh_from_codex(extra_dirs); - } - - /// Rescan marketplaces + installed-plugin cache (Python `ToolCatalog.refresh_from_codex`). - pub fn refresh_from_codex(&mut self, extra_dirs: &[PathBuf]) -> Result<(), String> { - let configured = load_configured_plugin_ids(); - let installed_ids = list_installed_plugin_ids() - .map_err(|e| format!("failed to refresh plugin catalog: {e}"))?; - - self.installed_plugin_ids = installed_ids.iter().cloned().collect(); - self.discoverable = collect_discoverable_plugins(&installed_ids, &configured, extra_dirs); - - let mut seen = std::collections::HashSet::new(); - self.deferred.clear(); - for plugin_id in installed_ids { - match deferred_tools_for_installed_plugin(&plugin_id) { - Ok(entries) => { - for entry in entries { - if seen.insert(entry.name.clone()) { - self.register_deferred(entry); - } - } - } - Err(_) => continue, - } - } - Ok(()) - } - - pub fn list_installable(&self) -> Vec { - self.discoverable - .iter() - .filter(|p| !p.installed) - .cloned() - .collect() - } - - pub fn find_plugin(&self, plugin_id: &str) -> Option { - self.discoverable - .iter() - .find(|p| p.id == plugin_id) - .cloned() - } - - pub fn list_installable_entries(&self) -> Vec { - self.list_installable() - } - - pub fn install_plugin(&mut self, plugin_id: &str) -> Result, String> { - let manifest_path = self - .discoverable - .iter() - .find(|p| p.id == plugin_id) - .map(|p| p.manifest_path.clone()) - .ok_or_else(|| format!("unknown plugin {plugin_id}"))?; - let raw = std::fs::read_to_string(&manifest_path).map_err(|e| e.to_string())?; - let manifest: PluginManifest = - serde_json::from_str(&raw).map_err(|e| format!("{manifest_path:?}: {e}"))?; - self.installed_plugin_ids.insert(plugin_id.to_string()); - for plugin in &mut self.discoverable { - if plugin.id == plugin_id { - plugin.installed = true; - } - } - let entries = manifest.deferred_tools(); - for entry in &entries { - self.register_deferred(entry.clone()); - } - Ok(entries) - } -} - -fn load_configured_plugin_ids() -> std::collections::HashSet { - let path = forge_plugin_state_path(); - let Ok(text) = std::fs::read_to_string(&path) else { - return std::collections::HashSet::new(); - }; - let Ok(raw) = serde_json::from_str::(&text) else { - return std::collections::HashSet::new(); - }; - raw.get("enabled_plugins") - .and_then(|v| v.as_array()) - .map(|items| { - items - .iter() - .filter_map(|v| v.as_str().map(str::to_string)) - .collect() - }) - .unwrap_or_default() -} - -fn list_installed_plugin_ids() -> Result, std::io::Error> { - let cache = plugins_cache_root(); - let mut out = Vec::new(); - if !cache.is_dir() { - return Ok(out); - } - for marketplace_dir in std::fs::read_dir(&cache)? { - let marketplace_dir = marketplace_dir?; - if !marketplace_dir.file_type()?.is_dir() { - continue; - } - let marketplace_name = marketplace_dir.file_name().to_string_lossy().to_string(); - for plugin_dir in std::fs::read_dir(marketplace_dir.path())? { - let plugin_dir = plugin_dir?; - if !plugin_dir.file_type()?.is_dir() { - continue; - } - let plugin_name = plugin_dir.file_name().to_string_lossy().to_string(); - let plugin_id = format!("{plugin_name}@{marketplace_name}"); - if is_plugin_installed(&plugin_id) { - out.push(plugin_id); - } - } - } - Ok(out) -} - -fn is_plugin_installed(plugin_id: &str) -> bool { - let Some((plugin_name, marketplace_name)) = plugin_id.rsplit_once('@') else { - return false; - }; - let base = plugins_cache_root() - .join(marketplace_name) - .join(plugin_name); - if !base.is_dir() { - return false; - } - let Ok(entries) = std::fs::read_dir(&base) else { - return false; - }; - for entry in entries.flatten() { - if !entry.path().is_dir() { - continue; - } - if super::codex_paths::find_plugin_manifest_path(&entry.path()).is_some() { - return true; - } - } - false -} - -fn collect_discoverable_plugins( - installed_ids: &[String], - configured: &std::collections::HashSet, - extra_dirs: &[PathBuf], -) -> Vec { - let discover_all = discover_all_plugins_enabled(); - let installed: std::collections::HashSet<&str> = - installed_ids.iter().map(String::as_str).collect(); - let mut out = Vec::new(); - - for marketplace in list_marketplaces(extra_dirs) { - for entry in &marketplace.plugins { - let plugin_id = entry.plugin_id(); - if installed.contains(plugin_id.as_str()) { - continue; - } - if entry.installation == InstallPolicy::NotAvailable { - continue; - } - let in_allowlist = TOOL_SUGGEST_PLUGIN_ALLOWLIST.contains(&plugin_id.as_str()); - let is_configured = configured.contains(&plugin_id); - if !discover_all && !in_allowlist && !is_configured { - continue; - } - let manifest = entry - .source - .local_path - .as_ref() - .filter(|p| p.is_dir()) - .and_then(|p| load_codex_manifest(p).ok()); - let name = manifest - .as_ref() - .and_then(|m| m.display_name.clone()) - .or_else(|| manifest.as_ref().map(|m| m.name.clone())) - .unwrap_or_else(|| entry.name.clone()); - let description = manifest.as_ref().and_then(|m| m.description.clone()); - let manifest_path = manifest - .as_ref() - .map(|m| m.manifest_path.clone()) - .unwrap_or_else(|| entry.marketplace_root.clone()); - out.push(DiscoverablePlugin { - id: plugin_id, - name, - description, - remote_plugin_id: remote_plugin_id(&entry.marketplace_name, &entry.name), - has_skills: manifest.as_ref().is_some_and(|m| m.has_skills), - mcp_server_names: manifest - .as_ref() - .map(|m| m.mcp_server_names.clone()) - .unwrap_or_default(), - app_connector_ids: manifest - .as_ref() - .map(|m| m.app_connector_ids.clone()) - .unwrap_or_default(), - manifest_path, - installed: false, - }); - } - } - - // Legacy flat plugin dirs (tests + FORGE_PLUGIN_DIRS). - let dirs = scan_codex_plugin_dirs(extra_dirs); - for (manifest, path) in load_plugin_manifests(&dirs) { - if installed.contains(manifest.id.as_str()) { - continue; - } - out.retain(|p| p.id != manifest.id); - out.push(manifest.to_discoverable(&path, false)); - } - out -} - -fn remote_plugin_id(marketplace_name: &str, plugin_name: &str) -> Option { - if marketplace_name.ends_with("-remote") { - Some(format!("plugins~Plugin_{plugin_name}")) - } else { - None - } -} - -fn deferred_tools_for_installed_plugin(plugin_id: &str) -> Result, String> { - let Some((plugin_name, marketplace_name)) = plugin_id.rsplit_once('@') else { - return Ok(Vec::new()); - }; - let base = plugins_cache_root() - .join(marketplace_name) - .join(plugin_name); - let root = - active_plugin_root(&base).ok_or_else(|| format!("plugin not installed: {plugin_id}"))?; - let manifest = load_codex_manifest(&root)?; - Ok(manifest - .mcp_server_names - .iter() - .map(|server| { - let ns = format!("mcp__{server}"); - let mut entry = DeferredToolEntry::from_function( - &ns, - &format!( - "MCP server {server} from plugin {}", - manifest.display_name.as_deref().unwrap_or(&manifest.name) - ), - serde_json::json!({"type": "object", "properties": {}}), - ); - entry.defer_loading = true; - entry.namespace = Some(ns.clone()); - entry.plugin_id = Some(plugin_id.to_string()); - entry.source = Some("codex_mcp_server".into()); - entry - }) - .collect()) -} - -fn active_plugin_root(base: &Path) -> Option { - if !base.is_dir() { - return None; - } - let Ok(entries) = std::fs::read_dir(base) else { - return None; - }; - let mut versions: Vec = entries - .flatten() - .filter(|e| e.path().is_dir()) - .map(|e| e.path()) - .collect(); - if versions.is_empty() { - return None; - } - if let Some(local) = versions - .iter() - .find(|p| p.file_name().and_then(|s| s.to_str()) == Some("local")) - { - return Some(local.clone()); - } - versions.sort_by(|a, b| { - let av = a.file_name().and_then(|s| s.to_str()).unwrap_or(""); - let bv = b.file_name().and_then(|s| s.to_str()).unwrap_or(""); - av.cmp(bv) - }); - versions.last().cloned() -} diff --git a/crates/pulsing-forge/src/discovery/codex_manifest.rs b/crates/pulsing-forge/src/discovery/codex_manifest.rs deleted file mode 100644 index 69e89d46c..000000000 --- a/crates/pulsing-forge/src/discovery/codex_manifest.rs +++ /dev/null @@ -1,149 +0,0 @@ -//! Parse Codex `.codex-plugin/plugin.json` manifests. - -use std::path::{Path, PathBuf}; - -use serde_json::Value; - -use super::codex_paths::find_plugin_manifest_path; - -#[derive(Clone, Debug)] -pub struct CodexPluginManifest { - pub name: String, - pub version: Option, - pub description: Option, - pub display_name: Option, - pub has_skills: bool, - pub mcp_server_names: Vec, - pub app_connector_ids: Vec, - pub manifest_path: PathBuf, -} - -pub fn load_codex_manifest(plugin_root: &Path) -> Result { - let manifest_path = find_plugin_manifest_path(plugin_root) - .ok_or_else(|| format!("missing plugin manifest under {}", plugin_root.display()))?; - let raw = std::fs::read_to_string(&manifest_path).map_err(|e| e.to_string())?; - let value: Value = - serde_json::from_str(&raw).map_err(|e| format!("{}: {e}", manifest_path.display()))?; - let obj = value.as_object().ok_or_else(|| { - format!( - "{}: manifest must be a JSON object", - manifest_path.display() - ) - })?; - parse_codex_manifest(obj, plugin_root, manifest_path) -} - -fn parse_codex_manifest( - raw: &serde_json::Map, - plugin_root: &Path, - manifest_path: PathBuf, -) -> Result { - let interface = raw - .get("interface") - .and_then(|v| v.as_object()) - .cloned() - .unwrap_or_default(); - let display = interface - .get("displayName") - .or_else(|| interface.get("display_name")) - .and_then(|v| v.as_str()) - .map(str::to_string); - let desc = raw - .get("description") - .or_else(|| interface.get("shortDescription")) - .or_else(|| interface.get("short_description")) - .and_then(|v| v.as_str()) - .map(str::to_string); - let mcp_ref = raw - .get("mcpServers") - .or_else(|| raw.get("mcp_servers")) - .and_then(|v| v.as_str()) - .map(str::to_string); - let apps_ref = raw.get("apps").and_then(|v| v.as_str()).map(str::to_string); - let skills = raw.get("skills").and_then(|v| v.as_str()).is_some(); - let name = raw.get("name").and_then(|v| v.as_str()).unwrap_or_else(|| { - plugin_root - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or("plugin") - }); - let version = raw - .get("version") - .and_then(|v| v.as_str()) - .map(str::to_string); - Ok(CodexPluginManifest { - name: name.to_string(), - version, - description: desc, - display_name: display, - has_skills: skills, - mcp_server_names: extract_mcp_server_names(plugin_root, mcp_ref.as_deref()), - app_connector_ids: extract_app_connector_ids(plugin_root, apps_ref.as_deref()), - manifest_path, - }) -} - -fn resolve_relative(plugin_root: &Path, reference: Option<&str>) -> Option { - let reference = reference?; - let path = plugin_root.join(reference); - if path.exists() { Some(path) } else { None } -} - -fn extract_mcp_server_names(plugin_root: &Path, mcp_ref: Option<&str>) -> Vec { - let Some(path) = resolve_relative(plugin_root, mcp_ref) else { - return Vec::new(); - }; - let Ok(text) = std::fs::read_to_string(&path) else { - return Vec::new(); - }; - let Ok(raw) = serde_json::from_str::(&text) else { - return Vec::new(); - }; - let servers = raw.get("mcpServers").or(Some(&raw)); - if let Some(obj) = servers.and_then(|v| v.as_object()) { - let mut names: Vec = obj - .keys() - .filter(|k| !k.trim().is_empty()) - .cloned() - .collect(); - names.sort(); - return names; - } - Vec::new() -} - -fn extract_app_connector_ids(plugin_root: &Path, apps_ref: Option<&str>) -> Vec { - let Some(path) = resolve_relative(plugin_root, apps_ref) else { - return Vec::new(); - }; - let Ok(text) = std::fs::read_to_string(&path) else { - return Vec::new(); - }; - let Ok(raw) = serde_json::from_str::(&text) else { - return Vec::new(); - }; - let Some(obj) = raw.as_object() else { - return Vec::new(); - }; - let connectors = obj - .get("connectors") - .or_else(|| obj.get("apps")) - .unwrap_or(&raw); - if let Some(list) = connectors.as_array() { - return list - .iter() - .filter_map(|c| { - c.as_object() - .and_then(|o| o.get("id")) - .and_then(|v| v.as_str()) - .map(str::to_string) - }) - .collect(); - } - if let Some(map) = connectors.as_object() { - let mut ids: Vec = map.keys().cloned().collect(); - ids.sort(); - return ids; - } - Vec::new() -} diff --git a/crates/pulsing-forge/src/discovery/codex_paths.rs b/crates/pulsing-forge/src/discovery/codex_paths.rs deleted file mode 100644 index e4fa1d010..000000000 --- a/crates/pulsing-forge/src/discovery/codex_paths.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Codex home + marketplace roots (aligned with python/pulsing/forge/discovery/codex_paths.py). - -use std::path::{Path, PathBuf}; - -pub const PLUGINS_CACHE_DIR: &str = "plugins/cache"; - -pub const MARKETPLACE_MANIFEST_RELATIVE_PATHS: &[&str] = &[ - ".agents/plugins/marketplace.json", - ".claude-plugin/marketplace.json", -]; - -pub const PLUGIN_MANIFEST_RELATIVE_PATHS: &[&str] = - &[".codex-plugin/plugin.json", ".claude-plugin/plugin.json"]; - -/// Codex tool_suggest fallback allowlist (core-plugins/src/discoverable.rs). -pub const TOOL_SUGGEST_PLUGIN_ALLOWLIST: &[&str] = &[ - "github@openai-curated", - "notion@openai-curated", - "slack@openai-curated", - "gmail@openai-curated", - "google-calendar@openai-curated", - "google-drive@openai-curated", - "openai-developers@openai-curated", - "canva@openai-curated", - "teams@openai-curated", - "sharepoint@openai-curated", - "outlook-email@openai-curated", - "outlook-calendar@openai-curated", - "linear@openai-curated", - "figma@openai-curated", - "github@openai-curated-remote", - "notion@openai-curated-remote", - "slack@openai-curated-remote", - "gmail@openai-curated-remote", - "google-calendar@openai-curated-remote", - "google-drive@openai-curated-remote", - "openai-developers@openai-curated-remote", - "canva@openai-curated-remote", - "teams@openai-curated-remote", - "sharepoint@openai-curated-remote", - "outlook-email@openai-curated-remote", - "outlook-calendar@openai-curated-remote", - "linear@openai-curated-remote", - "figma@openai-curated-remote", - "chrome@openai-bundled", - "computer-use@openai-bundled", -]; - -pub fn codex_home() -> PathBuf { - if let Ok(raw) = std::env::var("CODEX_HOME") { - let trimmed = raw.trim(); - if !trimmed.is_empty() { - return PathBuf::from(trimmed); - } - } - dirs_home().join(".codex") -} - -pub fn plugins_cache_root() -> PathBuf { - codex_home().join(PLUGINS_CACHE_DIR) -} - -pub fn forge_plugin_state_path() -> PathBuf { - codex_home().join("forge").join("plugin_state.json") -} - -fn dirs_home() -> PathBuf { - std::env::var("HOME") - .map(PathBuf::from) - .unwrap_or_else(|_| PathBuf::from(".")) -} - -pub fn discover_marketplace_roots(extra_roots: &[PathBuf]) -> Vec { - let mut roots = Vec::new(); - for base in [dirs_home(), codex_home()] { - let agents = base.join(".agents").join("plugins"); - if agents.is_dir() { - roots.push(agents); - } - for rel in MARKETPLACE_MANIFEST_RELATIVE_PATHS { - let candidate = base.join(rel); - if candidate.is_file() { - roots.push(candidate.parent().unwrap_or(&base).to_path_buf()); - } - } - } - if let Ok(cwd) = std::env::current_dir() { - for rel in MARKETPLACE_MANIFEST_RELATIVE_PATHS { - let candidate = cwd.join(rel); - if candidate.is_file() { - roots.push(candidate.parent().unwrap_or(&cwd).to_path_buf()); - } - } - } - if let Ok(env) = std::env::var("FORGE_PLUGIN_DIRS") { - for part in env.split(':').filter(|s| !s.is_empty()) { - roots.push(PathBuf::from(part)); - } - } - roots.extend(extra_roots.iter().cloned()); - - let mut seen = std::collections::HashSet::new(); - let mut out = Vec::new(); - for root in roots { - let resolved = root.canonicalize().unwrap_or(root); - if seen.insert(resolved.clone()) { - out.push(resolved); - } - } - out -} - -pub fn find_marketplace_manifest(root: &Path) -> Option { - for rel in MARKETPLACE_MANIFEST_RELATIVE_PATHS { - let candidate = root.join(rel); - if candidate.is_file() { - return Some(candidate); - } - } - let direct = root.join("marketplace.json"); - if direct.is_file() { - return Some(direct); - } - None -} - -pub fn find_plugin_manifest_path(plugin_root: &Path) -> Option { - for rel in PLUGIN_MANIFEST_RELATIVE_PATHS { - let candidate = plugin_root.join(rel); - if candidate.is_file() { - return Some(candidate); - } - } - None -} - -pub fn discover_all_plugins_enabled() -> bool { - matches!( - std::env::var("FORGE_PLUGIN_DISCOVER_ALL") - .unwrap_or_default() - .to_ascii_lowercase() - .as_str(), - "1" | "true" | "yes" - ) -} diff --git a/crates/pulsing-forge/src/discovery/marketplace.rs b/crates/pulsing-forge/src/discovery/marketplace.rs deleted file mode 100644 index 1db2167a7..000000000 --- a/crates/pulsing-forge/src/discovery/marketplace.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! Codex marketplace.json discovery (aligned with python/pulsing/forge/discovery/marketplace.py). - -use std::path::{Path, PathBuf}; - -use serde_json::Value; - -use super::codex_paths::{discover_marketplace_roots, find_marketplace_manifest}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum InstallPolicy { - NotAvailable, - Available, - InstalledByDefault, -} - -#[derive(Clone, Debug)] -pub struct MarketplacePluginSource { - pub kind: String, - pub local_path: Option, -} - -#[derive(Clone, Debug)] -pub struct MarketplacePluginEntry { - pub name: String, - pub source: MarketplacePluginSource, - pub installation: InstallPolicy, - pub marketplace_name: String, - pub marketplace_root: PathBuf, -} - -impl MarketplacePluginEntry { - pub fn plugin_id(&self) -> String { - format!("{}@{}", self.name, self.marketplace_name) - } -} - -#[derive(Clone, Debug)] -pub struct Marketplace { - pub name: String, - pub root: PathBuf, - pub manifest_path: PathBuf, - pub plugins: Vec, -} - -pub fn list_marketplaces(extra_roots: &[PathBuf]) -> Vec { - let mut out = Vec::new(); - for root in discover_marketplace_roots(extra_roots) { - let Some(manifest_path) = find_marketplace_manifest(&root) else { - continue; - }; - if let Ok(marketplace) = load_marketplace(&manifest_path) { - out.push(marketplace); - } - } - out -} - -pub fn load_marketplace(manifest_path: &Path) -> Result { - let raw = std::fs::read_to_string(manifest_path).map_err(|e| e.to_string())?; - let value: Value = serde_json::from_str(&raw).map_err(|e| e.to_string())?; - let obj = value.as_object().ok_or_else(|| { - format!( - "{}: marketplace must be a JSON object", - manifest_path.display() - ) - })?; - let name = obj.get("name").and_then(|v| v.as_str()).unwrap_or_else(|| { - manifest_path - .parent() - .and_then(|p| p.file_name()) - .and_then(|s| s.to_str()) - .unwrap_or("marketplace") - }); - let marketplace_root = - if manifest_path.file_name().and_then(|s| s.to_str()) == Some("marketplace.json") { - manifest_path - .parent() - .unwrap_or(manifest_path) - .to_path_buf() - } else { - marketplace_root_from_manifest(manifest_path) - }; - let mut plugins = Vec::new(); - if let Some(items) = obj.get("plugins").and_then(|v| v.as_array()) { - for item in items { - let Some(entry_obj) = item.as_object() else { - continue; - }; - let plugin_name = entry_obj - .get("name") - .and_then(|v| v.as_str()) - .unwrap_or("") - .trim() - .to_string(); - if plugin_name.is_empty() { - continue; - } - let policy_raw = entry_obj - .get("policy") - .and_then(|v| v.as_object()) - .and_then(|p| p.get("installation")) - .and_then(|v| v.as_str()) - .unwrap_or("AVAILABLE"); - let installation = match policy_raw { - "NOT_AVAILABLE" => InstallPolicy::NotAvailable, - "INSTALLED_BY_DEFAULT" => InstallPolicy::InstalledByDefault, - _ => InstallPolicy::Available, - }; - let source = parse_source( - entry_obj.get("source").and_then(|v| v.as_object()), - &marketplace_root, - ); - plugins.push(MarketplacePluginEntry { - name: plugin_name, - source, - installation, - marketplace_name: name.to_string(), - marketplace_root: marketplace_root.clone(), - }); - } - } - Ok(Marketplace { - name: name.to_string(), - root: marketplace_root.clone(), - manifest_path: manifest_path.to_path_buf(), - plugins, - }) -} - -fn marketplace_root_from_manifest(manifest_path: &Path) -> PathBuf { - for rel in super::codex_paths::MARKETPLACE_MANIFEST_RELATIVE_PATHS { - let parts: Vec<_> = Path::new(rel).components().collect(); - let mut current = manifest_path.to_path_buf(); - let mut matched = true; - for part in parts.iter().rev() { - if current.file_name() != part.as_os_str().into() { - matched = false; - break; - } - current = current.parent().unwrap_or(¤t).to_path_buf(); - } - if matched { - return current; - } - } - manifest_path - .parent() - .unwrap_or(manifest_path) - .to_path_buf() -} - -fn parse_source( - raw: Option<&serde_json::Map>, - marketplace_root: &Path, -) -> MarketplacePluginSource { - let Some(raw) = raw else { - return MarketplacePluginSource { - kind: "local".into(), - local_path: Some(marketplace_root.to_path_buf()), - }; - }; - let kind = raw - .get("source") - .and_then(|v| v.as_str()) - .unwrap_or("local") - .to_ascii_lowercase(); - if kind == "git" { - return MarketplacePluginSource { - kind: "git".into(), - local_path: None, - }; - } - let rel = raw.get("path").and_then(|v| v.as_str()).unwrap_or("."); - let local = marketplace_root.join(rel); - MarketplacePluginSource { - kind: "local".into(), - local_path: Some(local), - } -} diff --git a/crates/pulsing-forge/src/discovery/mod.rs b/crates/pulsing-forge/src/discovery/mod.rs deleted file mode 100644 index 7a08556d6..000000000 --- a/crates/pulsing-forge/src/discovery/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! Deferred tool catalog + BM25 search (Codex `tool_search` compatible). - -mod bm25; -mod catalog; -mod codex_manifest; -mod codex_paths; -mod marketplace; -mod plugins; - -pub use catalog::{ - DeferredToolEntry, TOOL_SEARCH_DEFAULT_LIMIT, TOOL_SEARCH_MAX_LIMIT, ToolCatalog, - ToolCatalogSnapshot, -}; -pub use plugins::{ - DiscoverablePlugin, PluginManifest, load_plugin_manifests, scan_codex_plugin_dirs, -}; - -use std::sync::{Arc, Mutex}; - -pub fn new_tool_catalog() -> Arc> { - Arc::new(Mutex::new(ToolCatalog::default())) -} diff --git a/crates/pulsing-forge/src/discovery/plugins.rs b/crates/pulsing-forge/src/discovery/plugins.rs deleted file mode 100644 index 98a4da650..000000000 --- a/crates/pulsing-forge/src/discovery/plugins.rs +++ /dev/null @@ -1,154 +0,0 @@ -//! Codex-compatible plugin manifest loading. - -use std::path::{Path, PathBuf}; - -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -use super::catalog::DeferredToolEntry; - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct PluginToolDef { - #[serde(default)] - pub r#type: String, - pub name: String, - #[serde(default)] - pub description: String, - #[serde(default)] - pub parameters: Value, - #[serde(default)] - pub defer_loading: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct PluginManifest { - pub id: String, - pub name: String, - #[serde(default)] - pub description: Option, - #[serde(default)] - pub remote_plugin_id: Option, - #[serde(default)] - pub has_skills: bool, - #[serde(default)] - pub mcp_server_names: Vec, - #[serde(default)] - pub app_connector_ids: Vec, - #[serde(default)] - pub tools: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct DiscoverablePlugin { - pub id: String, - pub name: String, - pub description: Option, - pub remote_plugin_id: Option, - pub has_skills: bool, - pub mcp_server_names: Vec, - pub app_connector_ids: Vec, - pub manifest_path: PathBuf, - pub installed: bool, -} - -pub fn scan_codex_plugin_dirs(extra_dirs: &[PathBuf]) -> Vec { - let mut out = Vec::new(); - if let Some(home) = dirs_home() { - out.push(home.join(".codex").join("plugins")); - } - for d in extra_dirs { - out.push(d.clone()); - } - if let Ok(env) = std::env::var("FORGE_PLUGIN_DIRS") { - for part in env.split(':').filter(|s| !s.is_empty()) { - out.push(PathBuf::from(part)); - } - } - out -} - -fn dirs_home() -> Option { - std::env::var("HOME").ok().map(PathBuf::from) -} - -pub fn load_plugin_manifests(dirs: &[PathBuf]) -> Vec<(PluginManifest, PathBuf)> { - let mut out = Vec::new(); - for root in dirs { - if !root.is_dir() { - continue; - } - let Ok(entries) = std::fs::read_dir(root) else { - continue; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - for name in ["plugin.json", "manifest.json", "codex-plugin.json"] { - let mf = path.join(name); - if mf.is_file() - && let Ok(m) = read_manifest(&mf) - { - out.push((m, mf)); - } - } - } else if path.extension().is_some_and(|e| e == "json") - && let Ok(m) = read_manifest(&path) - { - out.push((m, path)); - } - } - } - out -} - -fn read_manifest(path: &Path) -> Result { - let raw = std::fs::read_to_string(path).map_err(|e| e.to_string())?; - serde_json::from_str(&raw).map_err(|e| format!("{}: {e}", path.display())) -} - -impl PluginManifest { - pub fn to_discoverable(&self, manifest_path: &Path, installed: bool) -> DiscoverablePlugin { - DiscoverablePlugin { - id: self.id.clone(), - name: self.name.clone(), - description: self.description.clone(), - remote_plugin_id: self.remote_plugin_id.clone(), - has_skills: self.has_skills, - mcp_server_names: self.mcp_server_names.clone(), - app_connector_ids: self.app_connector_ids.clone(), - manifest_path: manifest_path.to_path_buf(), - installed, - } - } - - pub fn deferred_tools(&self) -> Vec { - self.tools - .iter() - .map(|t| { - let mut entry = - DeferredToolEntry::from_function(&t.name, &t.description, t.parameters.clone()); - entry.defer_loading = t.defer_loading; - entry.plugin_id = Some(self.id.clone()); - entry.source = Some("codex_plugin".into()); - entry - }) - .collect() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_minimal_manifest() { - let raw = r#"{ - "id": "demo", - "name": "Demo Plugin", - "tools": [{"name": "demo_tool", "description": "hello", "parameters": {"type":"object"}}] - }"#; - let m: PluginManifest = serde_json::from_str(raw).unwrap(); - assert_eq!(m.tools.len(), 1); - assert_eq!(m.deferred_tools()[0].name, "demo_tool"); - } -} diff --git a/crates/pulsing-forge/src/error.rs b/crates/pulsing-forge/src/error.rs deleted file mode 100644 index da81c5057..000000000 --- a/crates/pulsing-forge/src/error.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! Error returned while executing a model-visible tool invocation. -//! -//! Adapted from `codex-tools` `FunctionCallError` (Apache-2.0). - -use thiserror::Error; - -#[derive(Debug, Error, PartialEq, Eq, Clone)] -pub enum ToolError { - #[error("{0}")] - RespondToModel(String), - #[error("Fatal error: {0}")] - Fatal(String), -} - -impl ToolError { - pub fn respond(msg: impl Into) -> Self { - Self::RespondToModel(msg.into()) - } -} diff --git a/crates/pulsing-forge/src/exec_output.rs b/crates/pulsing-forge/src/exec_output.rs deleted file mode 100644 index 4cbacff82..000000000 --- a/crates/pulsing-forge/src/exec_output.rs +++ /dev/null @@ -1,239 +0,0 @@ -//! Codex-compatible exec output shapes and output buffering. - -use serde::{Deserialize, Serialize}; -use uuid::Uuid; - -pub const DEFAULT_SHELL_TIMEOUT_MS: u64 = 10_000; -pub const DEFAULT_YIELD_TIME_MS: u64 = 250; -pub const MIN_YIELD_TIME_MS: u64 = 250; -pub const MAX_YIELD_TIME_MS: u64 = 30_000; -pub const DEFAULT_MAX_OUTPUT_TOKENS: usize = 10_000; -pub const SHELL_MAX_BYTES: usize = 256 * 1024; -/// Max bytes accepted per `write_stdin` call — guards against unbounded input growth. -pub const MAX_STDIN_BYTES: usize = 1024 * 1024; -/// Atomic sentinel while PTY / pipe session is still running. -pub const RUNNING_EXIT_SENTINEL: i32 = i32::MIN; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ExecStream { - Stdout, - Stderr, - Pty, -} - -/// Streaming chunk emitted while a unified exec session is running. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ExecOutputDelta { - pub session_id: i32, - pub stream: ExecStream, - pub chunk: String, -} - -/// Structured payload returned by `exec_command` / `write_stdin`. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ExecCommandOutput { - pub chunk_id: String, - pub wall_time_seconds: f64, - #[serde(skip_serializing_if = "Option::is_none")] - pub exit_code: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub session_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub original_token_count: Option, - pub output: String, -} - -impl ExecCommandOutput { - pub fn new( - output: String, - wall_time_seconds: f64, - exit_code: Option, - session_id: Option, - ) -> Self { - let original_token_count = estimate_tokens(&output); - Self { - chunk_id: Uuid::new_v4().to_string(), - wall_time_seconds, - exit_code, - session_id, - original_token_count: Some(original_token_count), - output, - } - } -} - -/// Rolling buffer for unified exec sessions (head+tail truncation). -#[derive(Clone, Debug, Default)] -pub struct OutputBuffer { - max_bytes: usize, - data: String, -} - -impl OutputBuffer { - pub fn new(max_bytes: usize) -> Self { - Self { - max_bytes, - data: String::new(), - } - } - - pub fn push(&mut self, chunk: &str) { - if chunk.is_empty() { - return; - } - self.data.push_str(chunk); - if self.data.len() > self.max_bytes { - let keep = self.max_bytes / 2; - let tail = tail_at(&self.data, keep); - self.data = format!("...[output truncated]...\n{tail}"); - } - } - - pub fn snapshot(&self) -> String { - self.data.clone() - } - - pub fn truncate_to_tokens(&mut self, max_tokens: usize) { - let est = estimate_tokens(&self.data); - if est <= max_tokens { - return; - } - let ratio = max_tokens as f64 / est as f64; - let keep = ((self.data.len() as f64) * ratio) as usize; - let tail = tail_at(&self.data, keep); - self.data = format!("...[token limit]...\n{tail}"); - } -} - -/// Returns the trailing slice of `s` that keeps at least `keep` bytes, -/// snapped outward to the nearest UTF-8 char boundary. Naive byte-offset -/// slicing (`s[len - keep..]`) panics whenever the cut point lands inside a -/// multi-byte character (e.g. CJK output), so callers must go through this. -fn tail_at(s: &str, keep: usize) -> &str { - let mut start = s.len().saturating_sub(keep); - while start > 0 && !s.is_char_boundary(start) { - start -= 1; - } - &s[start..] -} - -/// Incrementally decodes a raw byte stream (PTY/pipe reads) into UTF-8, -/// holding back a possibly-incomplete trailing multi-byte sequence instead of -/// rendering it as `U+FFFD` when a codepoint is split across two reads. -#[derive(Debug, Default)] -pub struct Utf8ChunkDecoder { - pending: Vec, -} - -impl Utf8ChunkDecoder { - /// Decodes `bytes` combined with any carry-over from the previous call. - pub fn decode(&mut self, bytes: &[u8]) -> String { - if !bytes.is_empty() { - self.pending.extend_from_slice(bytes); - } - match std::str::from_utf8(&self.pending) { - Ok(s) => { - let out = s.to_string(); - self.pending.clear(); - out - } - Err(e) => { - let valid_len = e.valid_up_to(); - let out = String::from_utf8_lossy(&self.pending[..valid_len]).into_owned(); - let leftover = self.pending.len() - valid_len; - // A genuine UTF-8 codepoint is at most 4 bytes; a longer - // leftover means the bytes are simply invalid rather than a - // split codepoint, so flush them lossily instead of - // buffering forever. - if leftover > 4 { - let rest = String::from_utf8_lossy(&self.pending[valid_len..]).into_owned(); - self.pending.clear(); - return out + &rest; - } - self.pending.drain(..valid_len); - out - } - } - } - - /// Flushes any buffered bytes at end-of-stream (best-effort lossy decode). - pub fn finish(&mut self) -> String { - if self.pending.is_empty() { - return String::new(); - } - let out = String::from_utf8_lossy(&self.pending).into_owned(); - self.pending.clear(); - out - } -} - -pub fn estimate_tokens(text: &str) -> usize { - // Cheap proxy: ~4 chars per token for mixed shell output. - (text.len() / 4).max(1) -} - -pub fn clamp_yield_ms(raw: Option) -> u64 { - raw.unwrap_or(DEFAULT_YIELD_TIME_MS) - .clamp(MIN_YIELD_TIME_MS, MAX_YIELD_TIME_MS) -} - -pub fn shell_timeout_ms(args: &serde_json::Value) -> u64 { - if let Some(ms) = args.get("timeout_ms").and_then(|v| v.as_u64()) { - return ms.max(1); - } - if let Some(sec) = args.get("timeout_sec").and_then(|v| v.as_u64()) { - return (sec * 1000).max(1); - } - DEFAULT_SHELL_TIMEOUT_MS -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn push_truncation_does_not_split_multibyte_chars() { - // Regression test: naive `s[len - keep..]` byte slicing panics (or - // corrupts output) when the cut point lands mid-codepoint. Every "中" - // is 3 bytes, so a `max_bytes` that isn't a multiple of 3 forces the - // cut through the middle of a character. - let mut buf = OutputBuffer::new(10); - buf.push(&"中".repeat(20)); - let snapshot = buf.snapshot(); - assert!(snapshot.contains("...[output truncated]...")); - // If this didn't panic, the buffer is guaranteed valid UTF-8 already - // (Rust `String` invariant) — assert content is sane too. - assert!(snapshot.ends_with('中')); - } - - #[test] - fn truncate_to_tokens_does_not_split_multibyte_chars() { - let mut buf = OutputBuffer::new(1 << 20); - buf.push(&"中".repeat(50)); - buf.truncate_to_tokens(1); - let snapshot = buf.snapshot(); - assert!(snapshot.contains("...[token limit]...")); - assert!(snapshot.ends_with('中')); - } - - #[test] - fn utf8_chunk_decoder_reassembles_split_codepoint() { - let bytes = "héllo 中文".as_bytes(); - for split in 1..bytes.len() { - let mut decoder = Utf8ChunkDecoder::default(); - let mut out = decoder.decode(&bytes[..split]); - out.push_str(&decoder.decode(&bytes[split..])); - out.push_str(&decoder.finish()); - assert_eq!(out, "héllo 中文", "split at byte {split} corrupted output"); - } - } - - #[test] - fn utf8_chunk_decoder_flushes_invalid_bytes_instead_of_growing_forever() { - let mut decoder = Utf8ChunkDecoder::default(); - let out = decoder.decode(&[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, b'x']); - assert!(out.contains('x')); - assert!(decoder.finish().is_empty()); - } -} diff --git a/crates/pulsing-forge/src/execpolicy/mod.rs b/crates/pulsing-forge/src/execpolicy/mod.rs deleted file mode 100644 index 983195b97..000000000 --- a/crates/pulsing-forge/src/execpolicy/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! Prefix-based exec policy (Codex-compatible decisions). - -mod policy; - -pub use policy::{Decision, ExecPolicy, PrefixRule}; diff --git a/crates/pulsing-forge/src/execpolicy/policy.rs b/crates/pulsing-forge/src/execpolicy/policy.rs deleted file mode 100644 index 5b369212c..000000000 --- a/crates/pulsing-forge/src/execpolicy/policy.rs +++ /dev/null @@ -1,176 +0,0 @@ -//! Lightweight execpolicy: prefix rules with Allow / Prompt / Forbidden. - -use serde::{Deserialize, Serialize}; -use std::path::Path; - -#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum Decision { - #[default] - Allow = 0, - Prompt = 1, - Forbidden = 2, -} - -impl Decision { - pub fn parse(raw: &str) -> Option { - match raw.trim().to_lowercase().as_str() { - "allow" => Some(Self::Allow), - "prompt" => Some(Self::Prompt), - "forbidden" | "deny" => Some(Self::Forbidden), - _ => None, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct PrefixRule { - pub pattern: Vec, - #[serde(default)] - pub decision: Decision, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub justification: Option, -} - -impl PrefixRule { - fn matches(&self, cmd: &[String]) -> bool { - if cmd.len() < self.pattern.len() { - return false; - } - cmd.iter().zip(self.pattern.iter()).all(|(a, b)| a == b) - } -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -pub struct ExecPolicyFile { - #[serde(default)] - pub rules: Vec, -} - -#[derive(Clone, Debug)] -pub struct ExecPolicy { - rules: Vec, -} - -#[derive(Clone, Debug)] -pub struct PolicyMatch { - pub decision: Decision, - pub matched_prefix: Vec, - pub justification: Option, -} - -impl ExecPolicy { - pub fn new(rules: Vec) -> Self { - Self { rules } - } - - pub fn default_codex_like() -> Self { - Self::new(vec![ - PrefixRule { - pattern: vec!["git".into(), "reset".into(), "--hard".into()], - decision: Decision::Forbidden, - justification: Some("destructive git reset --hard".into()), - }, - PrefixRule { - pattern: vec!["rm".into(), "-rf".into()], - decision: Decision::Prompt, - justification: Some("recursive force delete".into()), - }, - PrefixRule { - pattern: vec!["curl".into()], - decision: Decision::Prompt, - justification: Some("network access via curl".into()), - }, - PrefixRule { - pattern: vec!["wget".into()], - decision: Decision::Prompt, - justification: Some("network access via wget".into()), - }, - PrefixRule { - pattern: vec!["sudo".into()], - decision: Decision::Forbidden, - justification: Some("elevated privileges".into()), - }, - ]) - } - - pub fn from_json_str(raw: &str) -> Result { - let file: ExecPolicyFile = - serde_json::from_str(raw).map_err(|e| format!("invalid exec policy JSON: {e}"))?; - Ok(Self::new(file.rules)) - } - - pub fn load_path(path: &Path) -> Result { - let raw = std::fs::read_to_string(path) - .map_err(|e| format!("read exec policy {}: {e}", path.display()))?; - Self::from_json_str(&raw) - } - - pub fn add_allow_prefix(&mut self, prefix: Vec) { - if prefix.is_empty() { - return; - } - self.rules.retain(|r| r.pattern != prefix); - self.rules.push(PrefixRule { - pattern: prefix, - decision: Decision::Allow, - justification: None, - }); - } - - pub fn evaluate(&self, cmd: &[String]) -> PolicyMatch { - let mut best: Option<&PrefixRule> = None; - for rule in &self.rules { - if !rule.matches(cmd) { - continue; - } - match best { - None => best = Some(rule), - Some(prev) if rule.pattern.len() > prev.pattern.len() => best = Some(rule), - Some(prev) - if rule.pattern.len() == prev.pattern.len() - && rule.decision > prev.decision => - { - best = Some(rule) - } - _ => {} - } - } - match best { - Some(rule) => PolicyMatch { - decision: rule.decision, - matched_prefix: rule.pattern.clone(), - justification: rule.justification.clone(), - }, - None => PolicyMatch { - decision: Decision::Prompt, - matched_prefix: cmd.to_vec(), - justification: Some("no matching execpolicy rule".into()), - }, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn forbidden_git_reset_hard() { - let p = ExecPolicy::default_codex_like(); - let m = p.evaluate(&tokens(&["git", "reset", "--hard", "HEAD"])); - assert_eq!(m.decision, Decision::Forbidden); - } - - #[test] - fn allow_amendment_prefix() { - let mut p = ExecPolicy::default_codex_like(); - p.add_allow_prefix(tokens(&["echo", "ok"])); - let m = p.evaluate(&tokens(&["echo", "ok"])); - assert_eq!(m.decision, Decision::Allow); - } - - fn tokens(parts: &[&str]) -> Vec { - parts.iter().map(|s| s.to_string()).collect() - } -} diff --git a/crates/pulsing-forge/src/executor.rs b/crates/pulsing-forge/src/executor.rs deleted file mode 100644 index 4869c7c5c..000000000 --- a/crates/pulsing-forge/src/executor.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Shared runtime contract for model-visible tools. -//! -//! Adapted from `codex-tools` `tool_executor.rs` (Apache-2.0). - -use std::future::Future; -use std::pin::Pin; - -use crate::error::ToolError; -use crate::registry::ToolSpec; -use crate::result::ToolResult; - -pub type ToolExecutorFuture<'a> = - Pin> + Send + 'a>>; - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum ToolExposure { - Direct, - Deferred, - DirectModelOnly, - Hidden, -} - -impl ToolExposure { - pub fn is_direct(self) -> bool { - matches!(self, Self::Direct | Self::DirectModelOnly) - } -} - -pub trait ToolExecutor: Send + Sync { - fn tool_name(&self) -> &str; - - /// Provider-neutral model schema. Keeping this on the executable contract - /// prevents the agent loop from drifting into a second tool catalog. - fn spec(&self) -> ToolSpec; - - fn exposure(&self) -> ToolExposure { - ToolExposure::Direct - } - - fn supports_parallel(&self) -> bool { - false - } - - fn handle<'a>( - &'a self, - ctx: &'a crate::context::ToolCallContext, - arguments: serde_json::Value, - ) -> ToolExecutorFuture<'a>; -} diff --git a/crates/pulsing-forge/src/handlers/apply_patch.rs b/crates/pulsing-forge/src/handlers/apply_patch.rs deleted file mode 100644 index 43fac3e6a..000000000 --- a/crates/pulsing-forge/src/handlers/apply_patch.rs +++ /dev/null @@ -1,78 +0,0 @@ -use serde_json::Value; - -use super::{err, ok}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; -use crate::patch::{MaybeApplyPatch, apply_parsed_patch, parse_patch}; - -pub struct ApplyPatchHandler; - -impl ToolExecutor for ApplyPatchHandler { - fn tool_name(&self) -> &str { - "apply_patch" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - let cwd = ctx.cwd.clone(); - Box::pin(async move { apply_patch_impl(&cwd, arguments) }) - } -} - -fn apply_patch_impl( - cwd: &std::path::Path, - arguments: Value, -) -> Result { - if let Some(raw) = arguments.as_str() { - return apply_patch_text(raw, cwd); - } - if let Some(patch) = arguments.get("patch").and_then(|v| v.as_str()) { - return apply_patch_text(patch, cwd); - } - if let Some(input) = arguments.get("input").and_then(|v| v.as_str()) { - return apply_patch_text(input, cwd); - } - if let Some(cmd) = arguments.get("command").and_then(|v| v.as_array()) { - let argv: Vec = cmd - .iter() - .filter_map(|v| v.as_str().map(str::to_string)) - .collect(); - return apply_patch_argv(&argv, cwd); - } - Err(ToolError::respond( - "apply_patch expects patch text, {\"patch\": \"...\"}, or {\"command\": [\"apply_patch\", \"...\"]}", - )) -} - -fn apply_patch_text( - patch: &str, - cwd: &std::path::Path, -) -> Result { - let args = parse_patch(patch).map_err(|e| ToolError::respond(e.to_string()))?; - match apply_parsed_patch(&args, cwd) { - Ok(summary) => ok(summary), - Err(e) => err(e), - } -} - -fn apply_patch_argv( - argv: &[String], - cwd: &std::path::Path, -) -> Result { - match crate::patch::maybe_parse_apply_patch(argv) { - MaybeApplyPatch::Body(args) => match apply_parsed_patch(&args, cwd) { - Ok(summary) => ok(summary), - Err(e) => err(e), - }, - MaybeApplyPatch::ImplicitInvocation => { - err("patch detected without explicit apply_patch invocation; use apply_patch tool") - } - MaybeApplyPatch::PatchParseError(e) => err(e.to_string()), - MaybeApplyPatch::ShellParseError(e) => err(e), - MaybeApplyPatch::NotApplyPatch => err("not an apply_patch command"), - } -} diff --git a/crates/pulsing-forge/src/handlers/bash.rs b/crates/pulsing-forge/src/handlers/bash.rs deleted file mode 100644 index f71910d24..000000000 --- a/crates/pulsing-forge/src/handlers/bash.rs +++ /dev/null @@ -1,22 +0,0 @@ -use serde_json::Value; - -use super::shell_exec::run_shell; -use crate::context::ToolCallContext; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -/// Legacy Claude-style alias; Codex uses `shell_command` / `exec_command`. -pub struct BashHandler; - -impl ToolExecutor for BashHandler { - fn tool_name(&self) -> &str { - "Bash" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { run_shell(ctx, &arguments).await }) - } -} diff --git a/crates/pulsing-forge/src/handlers/discovery.rs b/crates/pulsing-forge/src/handlers/discovery.rs deleted file mode 100644 index 59f3b1b84..000000000 --- a/crates/pulsing-forge/src/handlers/discovery.rs +++ /dev/null @@ -1,675 +0,0 @@ -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -use super::ok; -use crate::context::ToolCallContext; -use crate::discovery::{ - DeferredToolEntry, DiscoverablePlugin, TOOL_SEARCH_DEFAULT_LIMIT, TOOL_SEARCH_MAX_LIMIT, -}; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum DiscoverableToolType { - Connector, - Plugin, -} - -#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum DiscoverableToolAction { - Install, - Enable, -} - -#[derive(Debug, Deserialize)] -pub struct RequestPluginInstallArgs { - #[serde(alias = "plugin_id", alias = "tool_id")] - pub tool_id: String, - #[serde(default)] - pub tool_type: Option, - #[serde(default)] - pub action_type: Option, - #[serde(default, alias = "reason")] - pub suggest_reason: Option, -} - -#[derive(Debug, Serialize)] -pub struct RequestPluginInstallResult { - pub completed: bool, - pub user_confirmed: bool, - pub tool_type: DiscoverableToolType, - pub action_type: DiscoverableToolAction, - pub tool_id: String, - pub tool_name: String, - pub suggest_reason: String, - pub tools_registered: usize, -} - -fn loadable_tool_json(entry: &DeferredToolEntry) -> Value { - serde_json::json!({ - "type": "function", - "name": entry.name, - "description": entry.description, - "parameters": entry.parameters, - "defer_loading": entry.defer_loading, - "namespace": entry.namespace, - "plugin_id": entry.plugin_id, - "source": entry.source, - }) -} - -const DESCRIPTION_MAX_LEN: usize = 240; - -fn truncate_description(desc: Option<&str>) -> Option { - desc.map(|s| { - let char_count = s.chars().count(); - if char_count <= DESCRIPTION_MAX_LEN { - s.to_string() - } else { - let truncated: String = s.chars().take(DESCRIPTION_MAX_LEN - 1).collect(); - format!("{truncated}…") - } - }) -} - -fn discoverable_entry_json(p: &DiscoverablePlugin) -> Value { - serde_json::json!({ - "id": p.id, - "name": p.name, - "description": truncate_description(p.description.as_deref()), - "tool_type": "plugin", - "has_skills": p.has_skills, - "mcp_server_names": p.mcp_server_names, - "app_connector_ids": p.app_connector_ids, - }) -} - -pub struct ToolSearchHandler; - -impl ToolExecutor for ToolSearchHandler { - fn tool_name(&self) -> &str { - "tool_search" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { tool_search_impl(ctx, arguments) }) - } -} - -/// Defensive cap on query length so a pathological/huge query can't blow up -/// tokenization cost; Codex's tool_search runs server-side and has no such -/// concern, but this handler scores locally against the deferred-tool catalog. -const TOOL_SEARCH_MAX_QUERY_CHARS: usize = 2000; - -fn tool_search_impl( - ctx: &ToolCallContext, - arguments: Value, -) -> Result { - let query = arguments - .get("query") - .and_then(|v| v.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .ok_or_else(|| ToolError::respond("tool_search requires non-empty query"))?; - let query: String = query.chars().take(TOOL_SEARCH_MAX_QUERY_CHARS).collect(); - // `limit` must be a positive JSON integer; anything else (missing, 0, - // negative, non-numeric) falls back to the default, and the result is - // clamped so a huge value can't force an unbounded response. - let limit = arguments - .get("limit") - .and_then(|v| v.as_u64()) - .map(|n| n as usize) - .filter(|&n| n > 0) - .unwrap_or(TOOL_SEARCH_DEFAULT_LIMIT) - .min(TOOL_SEARCH_MAX_LIMIT); - let hits = ctx.tool_catalog.lock().unwrap().search(&query, limit); - let tools: Vec = hits.iter().map(loadable_tool_json).collect(); - let text = serde_json::to_string_pretty(&serde_json::json!({ "tools": tools })) - .map_err(|e| ToolError::respond(e.to_string()))?; - ok(text) -} - -#[cfg(test)] -mod tool_search_tests { - use super::*; - use crate::approval::{ApprovalCache, new_exec_policy}; - use crate::context::LocalToolSession; - use crate::discovery::{DeferredToolEntry, new_tool_catalog}; - use crate::unified_exec::UnifiedExecManager; - use std::sync::Arc; - - fn test_ctx(catalog: Arc>) -> ToolCallContext { - ToolCallContext::new( - ".", - "off", - Arc::new(LocalToolSession::default()), - Arc::new(UnifiedExecManager::new()), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - catalog, - ) - } - - fn catalog_with_github_tool() -> Arc> { - let catalog = new_tool_catalog(); - catalog - .lock() - .unwrap() - .register_deferred(DeferredToolEntry::from_function( - "github_mcp", - "GitHub MCP integration", - serde_json::json!({"type": "object"}), - )); - catalog - } - - #[test] - fn rejects_empty_query() { - let ctx = test_ctx(new_tool_catalog()); - for args in [ - serde_json::json!({"query": ""}), - serde_json::json!({"query": " "}), - serde_json::json!({}), - ] { - let err = tool_search_impl(&ctx, args).unwrap_err(); - assert!(err.to_string().contains("non-empty query")); - } - } - - #[test] - fn returns_loadable_tool_json() { - let ctx = test_ctx(catalog_with_github_tool()); - let out = tool_search_impl(&ctx, serde_json::json!({"query": "github mcp"})).unwrap(); - assert!(!out.is_error); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - let tool = &payload["tools"][0]; - assert_eq!(tool["type"], "function"); - assert_eq!(tool["name"], "github_mcp"); - assert_eq!(tool["defer_loading"], true); - } - - #[test] - fn limit_zero_or_negative_falls_back_to_default() { - let catalog = new_tool_catalog(); - for name in ["github_mcp", "github_issues", "github_actions"] { - catalog - .lock() - .unwrap() - .register_deferred(DeferredToolEntry::from_function( - name, - "GitHub integration", - serde_json::json!({"type": "object"}), - )); - } - let ctx = test_ctx(catalog); - for args in [ - serde_json::json!({"query": "github", "limit": 0}), - serde_json::json!({"query": "github", "limit": -5}), - ] { - let out = tool_search_impl(&ctx, args).unwrap(); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - assert_eq!(payload["tools"].as_array().unwrap().len(), 3); - } - } - - #[test] - fn huge_limit_is_clamped() { - let ctx = test_ctx(catalog_with_github_tool()); - let out = tool_search_impl( - &ctx, - serde_json::json!({"query": "github", "limit": 999_999_999_u64}), - ) - .unwrap(); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - assert_eq!(payload["tools"].as_array().unwrap().len(), 1); - } - - #[test] - fn truncates_overlong_query() { - let ctx = test_ctx(catalog_with_github_tool()); - let query = format!("github {}", "x".repeat(TOOL_SEARCH_MAX_QUERY_CHARS)); - let out = tool_search_impl(&ctx, serde_json::json!({"query": query})).unwrap(); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - assert_eq!(payload["tools"].as_array().unwrap().len(), 1); - } -} - -pub struct ListAvailablePluginsHandler; - -impl ToolExecutor for ListAvailablePluginsHandler { - fn tool_name(&self) -> &str { - "list_available_plugins_to_install" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, _arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { list_plugins_impl(ctx) }) - } -} - -fn list_plugins_impl(ctx: &ToolCallContext) -> Result { - let plugins = { - let mut catalog = ctx.tool_catalog.lock().unwrap(); - catalog - .refresh_from_codex(&[]) - .map_err(ToolError::respond)?; - catalog.list_installable() - }; - let tools: Vec = plugins.iter().map(discoverable_entry_json).collect(); - let text = serde_json::to_string_pretty(&serde_json::json!({ "tools": tools })) - .map_err(|e| ToolError::respond(e.to_string()))?; - ok(text) -} - -pub struct RequestPluginInstallHandler; - -impl ToolExecutor for RequestPluginInstallHandler { - fn tool_name(&self) -> &str { - "request_plugin_install" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { request_plugin_install_impl(ctx, arguments) }) - } -} - -fn request_plugin_install_impl( - ctx: &ToolCallContext, - arguments: Value, -) -> Result { - let args: RequestPluginInstallArgs = serde_json::from_value(arguments).map_err(|e| { - ToolError::respond(format!("invalid request_plugin_install arguments: {e}")) - })?; - let tool_id = args.tool_id.trim().to_string(); - if tool_id.is_empty() { - return Err(ToolError::respond( - "request_plugin_install requires tool_id", - )); - } - let tool_type = args.tool_type.unwrap_or(DiscoverableToolType::Plugin); - let action_type = args.action_type.unwrap_or(DiscoverableToolAction::Install); - if action_type != DiscoverableToolAction::Install { - return Err(ToolError::respond( - "plugin install requests currently support only action_type=\"install\"", - )); - } - let suggest_reason = args - .suggest_reason - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| { - ToolError::respond("request_plugin_install requires non-empty suggest_reason") - })?; - - let plugin = ctx - .tool_catalog - .lock() - .unwrap() - .find_plugin(&tool_id) - .ok_or_else(|| ToolError::respond(format!("unknown plugin {tool_id:?}")))?; - - let confirmed = ctx.session.request_plugin_install( - tool_id.clone(), - plugin.name.clone(), - suggest_reason.clone(), - )?; - - let tools_registered = if confirmed { - ctx.tool_catalog - .lock() - .unwrap() - .install_plugin(&tool_id) - .map_err(ToolError::respond)? - .len() - } else { - 0 - }; - - let result = RequestPluginInstallResult { - completed: true, - user_confirmed: confirmed, - tool_type, - action_type, - tool_id, - tool_name: plugin.name, - suggest_reason, - tools_registered, - }; - let text = - serde_json::to_string_pretty(&result).map_err(|e| ToolError::respond(e.to_string()))?; - ok(text) -} - -#[cfg(test)] -mod request_plugin_install_tests { - use super::*; - use crate::approval::{ApprovalCache, new_exec_policy}; - use crate::context::LocalToolSession; - use crate::discovery::new_tool_catalog; - use crate::unified_exec::UnifiedExecManager; - use std::fs; - use std::sync::Arc; - use tempfile::TempDir; - - struct CatalogFixture { - _dir: TempDir, - catalog: Arc>, - plugin_id: String, - } - - fn test_ctx( - session: Arc, - catalog: Arc>, - ) -> ToolCallContext { - ToolCallContext::new( - ".", - "off", - session, - Arc::new(UnifiedExecManager::new()), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - catalog, - ) - } - - fn catalog_with_demo_plugin() -> CatalogFixture { - let dir = TempDir::new().unwrap(); - let plugin_dir = dir.path().join("demo"); - fs::create_dir_all(&plugin_dir).unwrap(); - fs::write( - plugin_dir.join("plugin.json"), - r#"{ - "id": "demo@local-dev", - "name": "Demo Plugin", - "description": "For tests", - "tools": [{"name": "demo_tool", "description": "hello", "parameters": {"type":"object"}}] - }"#, - ) - .unwrap(); - let catalog = new_tool_catalog(); - catalog - .lock() - .unwrap() - .load_codex_plugins(&[dir.path().to_path_buf()]); - CatalogFixture { - _dir: dir, - catalog, - plugin_id: "demo@local-dev".to_string(), - } - } - - #[test] - fn request_plugin_install_requires_suggest_reason() { - let ctx = test_ctx( - Arc::new(LocalToolSession::default().with_plugin_install(|_, _, _| Ok(true))), - new_tool_catalog(), - ); - let err = request_plugin_install_impl( - &ctx, - serde_json::json!({ - "tool_id": "demo@local-dev", - "suggest_reason": " ", - }), - ) - .unwrap_err(); - assert!(err.to_string().contains("non-empty suggest_reason")); - } - - #[test] - fn request_plugin_install_rejects_enable_action() { - let fixture = catalog_with_demo_plugin(); - let ctx = test_ctx( - Arc::new(LocalToolSession::default().with_plugin_install(|_, _, _| Ok(true))), - fixture.catalog, - ); - let err = request_plugin_install_impl( - &ctx, - serde_json::json!({ - "tool_id": fixture.plugin_id, - "action_type": "enable", - "suggest_reason": "Need it", - }), - ) - .unwrap_err(); - assert!(err.to_string().contains("action_type=\"install\"")); - } - - #[test] - fn request_plugin_install_unknown_plugin() { - let ctx = test_ctx( - Arc::new(LocalToolSession::default().with_plugin_install(|_, _, _| Ok(true))), - new_tool_catalog(), - ); - let err = request_plugin_install_impl( - &ctx, - serde_json::json!({ - "tool_id": "missing@local-dev", - "suggest_reason": "Need it", - }), - ) - .unwrap_err(); - assert!(err.to_string().contains("unknown plugin")); - } - - #[test] - fn request_plugin_install_denied_skips_install() { - let fixture = catalog_with_demo_plugin(); - let ctx = test_ctx( - Arc::new(LocalToolSession::default().with_plugin_install(|_, _, _| Ok(false))), - fixture.catalog.clone(), - ); - let out = request_plugin_install_impl( - &ctx, - serde_json::json!({ - "tool_id": fixture.plugin_id, - "suggest_reason": "Need it", - }), - ) - .unwrap(); - assert!(!out.is_error); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - assert_eq!(payload["user_confirmed"], false); - assert_eq!(payload["tools_registered"], 0); - assert!( - !fixture - .catalog - .lock() - .unwrap() - .is_plugin_installed(&fixture.plugin_id) - ); - } - - #[test] - fn request_plugin_install_confirmed_registers_tools() { - let fixture = catalog_with_demo_plugin(); - let ctx = test_ctx( - Arc::new(LocalToolSession::default().with_plugin_install(|_, _, _| Ok(true))), - fixture.catalog.clone(), - ); - let out = request_plugin_install_impl( - &ctx, - serde_json::json!({ - "plugin_id": fixture.plugin_id, - "reason": "Need demo tools", - }), - ) - .unwrap(); - assert!(!out.is_error); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - assert_eq!(payload["user_confirmed"], true); - assert_eq!(payload["tools_registered"], 1); - assert!( - fixture - .catalog - .lock() - .unwrap() - .is_plugin_installed(&fixture.plugin_id) - ); - } - - #[test] - fn request_plugin_install_requires_session() { - let fixture = catalog_with_demo_plugin(); - let ctx = test_ctx(Arc::new(LocalToolSession::default()), fixture.catalog); - let err = request_plugin_install_impl( - &ctx, - serde_json::json!({ - "tool_id": fixture.plugin_id, - "suggest_reason": "Need it", - }), - ) - .unwrap_err(); - assert!(err.to_string().contains("not configured")); - } -} - -#[cfg(test)] -mod list_available_plugins_tests { - use super::*; - use crate::approval::{ApprovalCache, new_exec_policy}; - use crate::context::LocalToolSession; - use crate::discovery::new_tool_catalog; - use crate::unified_exec::UnifiedExecManager; - use std::fs; - use std::path::Path; - use std::sync::{Arc, Mutex}; - use tempfile::TempDir; - - static CODEX_HOME_ENV_LOCK: Mutex<()> = Mutex::new(()); - - struct CodexHomeEnv { - _lock: std::sync::MutexGuard<'static, ()>, - } - - impl CodexHomeEnv { - fn set(home: &Path, discover_all: bool) -> Self { - let lock = CODEX_HOME_ENV_LOCK.lock().unwrap(); - unsafe { - std::env::set_var("CODEX_HOME", home); - if discover_all { - std::env::set_var("FORGE_PLUGIN_DISCOVER_ALL", "1"); - } else { - std::env::remove_var("FORGE_PLUGIN_DISCOVER_ALL"); - } - } - Self { _lock: lock } - } - } - - impl Drop for CodexHomeEnv { - fn drop(&mut self) { - unsafe { - std::env::remove_var("CODEX_HOME"); - std::env::remove_var("FORGE_PLUGIN_DISCOVER_ALL"); - } - } - } - - fn test_ctx(catalog: Arc>) -> ToolCallContext { - ToolCallContext::new( - ".", - "off", - Arc::new(LocalToolSession::default()), - Arc::new(UnifiedExecManager::new()), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - catalog, - ) - } - - fn scaffold_marketplace(codex_home: &Path) -> String { - let agents = codex_home.join(".agents").join("plugins"); - fs::create_dir_all(&agents).unwrap(); - let plugin_src = agents.join("demo"); - let manifest_dir = plugin_src.join(".codex-plugin"); - fs::create_dir_all(&manifest_dir).unwrap(); - fs::write( - manifest_dir.join("plugin.json"), - r#"{ - "name": "demo", - "version": "1.0.0", - "description": "Demo plugin", - "mcpServers": ".mcp.json" - }"#, - ) - .unwrap(); - fs::write( - plugin_src.join(".mcp.json"), - r#"{"mcpServers": {"demo-mcp": {"command": "echo"}}}"#, - ) - .unwrap(); - fs::write( - agents.join("marketplace.json"), - r#"{ - "name": "local-dev", - "plugins": [{ - "name": "demo", - "source": {"source": "local", "path": "./demo"}, - "policy": {"installation": "AVAILABLE"} - }] - }"#, - ) - .unwrap(); - "demo@local-dev".to_string() - } - - #[test] - fn list_available_plugins_codex_wire() { - let dir = TempDir::new().unwrap(); - let _env = CodexHomeEnv::set(dir.path(), true); - let plugin_id = scaffold_marketplace(dir.path()); - let ctx = test_ctx(new_tool_catalog()); - let out = list_plugins_impl(&ctx).unwrap(); - assert!(!out.is_error); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - let tools = payload["tools"].as_array().expect("tools array"); - assert_eq!(tools.len(), 1, "expected one installable plugin"); - let entry = &tools[0]; - assert_eq!(entry["tool_type"], "plugin"); - assert_eq!(entry["id"], plugin_id); - let keys: std::collections::BTreeSet<_> = entry - .as_object() - .unwrap() - .keys() - .map(String::as_str) - .collect(); - assert_eq!( - keys, - [ - "app_connector_ids", - "description", - "has_skills", - "id", - "mcp_server_names", - "name", - "tool_type", - ] - .into_iter() - .collect::>() - ); - } - - #[test] - fn list_available_plugins_empty_catalog() { - let dir = TempDir::new().unwrap(); - let _env = CodexHomeEnv::set(dir.path(), false); - let ctx = test_ctx(new_tool_catalog()); - let out = list_plugins_impl(&ctx).unwrap(); - assert!(!out.is_error); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - assert!(payload["tools"].as_array().unwrap().is_empty()); - } -} diff --git a/crates/pulsing-forge/src/handlers/edit.rs b/crates/pulsing-forge/src/handlers/edit.rs deleted file mode 100644 index 96bf7ce00..000000000 --- a/crates/pulsing-forge/src/handlers/edit.rs +++ /dev/null @@ -1,222 +0,0 @@ -use std::io::Write as _; -use std::path::Path; -use std::sync::atomic::{AtomicU64, Ordering}; - -use serde_json::Value; - -use super::write::{assert_canonical_within_cwd, resolve_within_cwd}; -use super::{err, json_str, ok}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -pub struct EditHandler; - -impl ToolExecutor for EditHandler { - fn tool_name(&self) -> &str { - "Edit" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - let cwd = ctx.cwd.clone(); - Box::pin(async move { edit_impl(&cwd, &arguments) }) - } -} - -fn edit_impl(cwd: &Path, args: &Value) -> Result { - let path = json_str(args, "file_path")?; - let abs = resolve_within_cwd(cwd, path).map_err(ToolError::respond)?; - let old = json_str(args, "old_string")?; - let new = json_str(args, "new_string")?; - - if !abs.exists() { - return err(format!("file not found: {}", abs.display())); - } - if !abs.is_file() { - return err(format!("not a file: {}", abs.display())); - } - assert_canonical_within_cwd(cwd, &abs).map_err(ToolError::respond)?; - let text = std::fs::read_to_string(&abs) - .map_err(|e| ToolError::respond(format!("failed to read {}: {e}", abs.display())))?; - - let count = text.matches(old).count(); - if count == 0 { - return err(format!("old_string not found in {}", abs.display())); - } - if count > 1 { - return err(format!( - "old_string is not unique in {} ({count} occurrences); refusing ambiguous edit", - abs.display() - )); - } - - let updated = text.replacen(old, new, 1); - write_atomic(&abs, &updated) - .map_err(|e| ToolError::respond(format!("failed to write {}: {e}", abs.display())))?; - ok("ok") -} - -/// Writes `contents` to `path` via a sibling temp file + rename, so a failed -/// write (disk full, process killed, etc.) never leaves `path` truncated or -/// half-written. The rename is atomic on the same filesystem (POSIX and -/// Windows via `std::fs::rename`). -fn write_atomic(path: &Path, contents: &str) -> std::io::Result<()> { - static COUNTER: AtomicU64 = AtomicU64::new(0); - - let dir = path.parent().unwrap_or_else(|| Path::new(".")); - let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("edit"); - let unique = COUNTER.fetch_add(1, Ordering::Relaxed); - let tmp_path = dir.join(format!(".{file_name}.{}.{unique}.tmp", std::process::id())); - - let result = (|| -> std::io::Result<()> { - let mut f = std::fs::File::create(&tmp_path)?; - f.write_all(contents.as_bytes())?; - f.sync_all() - })(); - if result.is_err() { - let _ = std::fs::remove_file(&tmp_path); - return result; - } - if let Ok(meta) = std::fs::metadata(path) { - let _ = std::fs::set_permissions(&tmp_path, meta.permissions()); - } - std::fs::rename(&tmp_path, path) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn args(file_path: &str, old: &str, new: &str) -> Value { - json!({"file_path": file_path, "old_string": old, "new_string": new}) - } - - #[test] - fn replaces_unique_occurrence() { - let dir = tempfile::tempdir().unwrap(); - let f = dir.path().join("a.txt"); - std::fs::write(&f, "hello world").unwrap(); - let out = edit_impl(dir.path(), &args("a.txt", "world", "there")).unwrap(); - assert!(!out.is_error); - assert_eq!(std::fs::read_to_string(&f).unwrap(), "hello there"); - } - - #[test] - fn rejects_missing_old_string() { - let dir = tempfile::tempdir().unwrap(); - let f = dir.path().join("a.txt"); - std::fs::write(&f, "hello world").unwrap(); - let out = edit_impl(dir.path(), &args("a.txt", "nope", "x")).unwrap(); - assert!(out.is_error); - assert!(out.content.contains("not found")); - assert_eq!(std::fs::read_to_string(&f).unwrap(), "hello world"); - } - - #[test] - fn rejects_ambiguous_old_string_with_count() { - let dir = tempfile::tempdir().unwrap(); - let f = dir.path().join("a.txt"); - std::fs::write(&f, "a a a").unwrap(); - let out = edit_impl(dir.path(), &args("a.txt", "a", "b")).unwrap(); - assert!(out.is_error); - assert!(out.content.contains("3 occurrences"), "{}", out.content); - assert_eq!(std::fs::read_to_string(&f).unwrap(), "a a a"); - } - - #[test] - fn rejects_missing_file() { - let dir = tempfile::tempdir().unwrap(); - let out = edit_impl(dir.path(), &args("missing.txt", "a", "b")).unwrap(); - assert!(out.is_error); - assert!(out.content.contains("file not found")); - } - - #[test] - fn rejects_directory_path() { - let dir = tempfile::tempdir().unwrap(); - std::fs::create_dir(dir.path().join("sub")).unwrap(); - let out = edit_impl(dir.path(), &args("sub", "a", "b")).unwrap(); - assert!(out.is_error); - assert!(out.content.contains("not a file")); - } - - #[test] - fn rejects_relative_escape_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let f = dir.path().join("a.txt"); - std::fs::write(&f, "hello world").unwrap(); - let err = edit_impl(dir.path(), &args("../a.txt", "world", "there")).unwrap_err(); - assert!( - matches!(err, ToolError::RespondToModel(ref msg) if msg.contains("outside working directory")), - "{err:?}" - ); - assert_eq!(std::fs::read_to_string(&f).unwrap(), "hello world"); - assert!(!dir.path().parent().unwrap().join("a.txt").exists()); - } - - #[test] - fn rejects_absolute_path_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let outside = - std::env::temp_dir().join(format!("pulsing-forge-edit-outside-{}", std::process::id())); - std::fs::write(&outside, "secret").unwrap(); - let err = edit_impl( - dir.path(), - &args(outside.to_str().unwrap(), "secret", "leaked"), - ) - .unwrap_err(); - assert!( - matches!(err, ToolError::RespondToModel(ref msg) if msg.contains("outside working directory")), - "{err:?}" - ); - assert_eq!(std::fs::read_to_string(&outside).unwrap(), "secret"); - let _ = std::fs::remove_file(&outside); - } - - #[test] - fn allows_absolute_path_inside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let f = dir.path().join("inside.txt"); - std::fs::write(&f, "hello world").unwrap(); - let out = edit_impl(dir.path(), &args(f.to_str().unwrap(), "world", "there")).unwrap(); - assert!(!out.is_error); - assert_eq!(std::fs::read_to_string(&f).unwrap(), "hello there"); - } - - #[cfg(unix)] - #[test] - fn rejects_symlink_escape_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let outside = tempfile::tempdir().unwrap(); - let outside_file = outside.path().join("secret.txt"); - std::fs::write(&outside_file, "secret").unwrap(); - let link = dir.path().join("link.txt"); - std::os::unix::fs::symlink(&outside_file, &link).unwrap(); - let err = edit_impl(dir.path(), &args("link.txt", "secret", "leaked")).unwrap_err(); - assert!( - matches!(err, ToolError::RespondToModel(ref msg) if msg.contains("outside working directory")), - "{err:?}" - ); - assert_eq!(std::fs::read_to_string(&outside_file).unwrap(), "secret"); - assert!(link.is_symlink()); - } - - #[test] - fn no_leftover_temp_file_after_success() { - let dir = tempfile::tempdir().unwrap(); - let f = dir.path().join("a.txt"); - std::fs::write(&f, "hello world").unwrap(); - edit_impl(dir.path(), &args("a.txt", "world", "there")).unwrap(); - let leftovers: Vec<_> = std::fs::read_dir(dir.path()) - .unwrap() - .filter_map(|e| e.ok()) - .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp")) - .collect(); - assert!(leftovers.is_empty(), "{leftovers:?}"); - } -} diff --git a/crates/pulsing-forge/src/handlers/glob.rs b/crates/pulsing-forge/src/handlers/glob.rs deleted file mode 100644 index d437ea64a..000000000 --- a/crates/pulsing-forge/src/handlers/glob.rs +++ /dev/null @@ -1,153 +0,0 @@ -use std::path::{Path, PathBuf}; - -use serde_json::Value; - -use super::{err, json_str, ok}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -/// Cap on returned matches, mirroring Grep's `GREP_MAX` — keeps tool output -/// bounded for the model without requiring pagination plumbing. -const GLOB_MAX_MATCHES: usize = 500; - -pub struct GlobHandler; - -impl ToolExecutor for GlobHandler { - fn tool_name(&self) -> &str { - "Glob" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - let cwd = ctx.cwd.clone(); - Box::pin(async move { glob_impl(&cwd, &arguments) }) - } -} - -fn resolve_path(cwd: &Path, path: &str) -> PathBuf { - let p = Path::new(path); - if p.is_absolute() { - p.to_path_buf() - } else { - cwd.join(p) - } -} - -fn glob_impl(cwd: &Path, args: &Value) -> Result { - let pattern = json_str(args, "pattern")?; - if Path::new(pattern).is_absolute() { - return err( - "pattern must be relative to path/cwd; absolute glob patterns are not supported", - ); - } - let base = args - .get("path") - .and_then(|v| v.as_str()) - .map(|p| resolve_path(cwd, p)) - .unwrap_or_else(|| cwd.to_path_buf()); - if !base.exists() { - return err(format!("path does not exist: {}", base.display())); - } - let pat_str = base.join(pattern).to_string_lossy().replace('\\', "/"); - let mut matches: Vec = glob::glob(&pat_str) - .map_err(|e| ToolError::respond(format!("invalid glob pattern {pattern:?}: {e}")))? - .filter_map(|p| p.ok()) - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - matches.sort(); - let total = matches.len(); - matches.truncate(GLOB_MAX_MATCHES); - if matches.is_empty() { - return ok("(no matches)"); - } - if total > GLOB_MAX_MATCHES { - matches.push(format!( - "… truncated: showing {GLOB_MAX_MATCHES} of {total} matches …" - )); - } - ok(matches.join("\n")) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn args(pattern: &str, path: Option<&str>) -> Value { - let mut v = json!({"pattern": pattern}); - if let Some(p) = path { - v["path"] = json!(p); - } - v - } - - #[test] - fn finds_matching_files() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("a.txt"), "x").unwrap(); - std::fs::write(dir.path().join("b.rs"), "x").unwrap(); - let out = glob_impl(dir.path(), &args("*.txt", None)).unwrap(); - assert!(!out.is_error); - assert!(out.content.ends_with("a.txt"), "{}", out.content); - } - - #[test] - fn reports_no_matches() { - let dir = tempfile::tempdir().unwrap(); - let out = glob_impl(dir.path(), &args("*.nope", None)).unwrap(); - assert!(!out.is_error); - assert_eq!(out.content, "(no matches)"); - } - - #[test] - fn rejects_missing_path() { - let dir = tempfile::tempdir().unwrap(); - let out = glob_impl(dir.path(), &args("*", Some("does/not/exist"))).unwrap(); - assert!(out.is_error); - assert!(out.content.contains("does not exist")); - } - - #[test] - fn relative_path_resolves_against_cwd() { - let dir = tempfile::tempdir().unwrap(); - let sub = dir.path().join("sub"); - std::fs::create_dir(&sub).unwrap(); - std::fs::write(sub.join("a.txt"), "x").unwrap(); - let out = glob_impl(dir.path(), &args("*.txt", Some("sub"))).unwrap(); - assert!(!out.is_error); - assert!(out.content.ends_with("a.txt"), "{}", out.content); - } - - #[test] - fn rejects_absolute_pattern() { - // Without this check `base.join(pattern)` silently drops `base` - // (PathBuf::join replaces the whole path when the RHS is absolute), - // letting the pattern glob outside of `path`/cwd entirely. - let dir = tempfile::tempdir().unwrap(); - let out = glob_impl(dir.path(), &args("/etc/*", None)).unwrap(); - assert!(out.is_error); - assert!(out.content.contains("absolute"), "{}", out.content); - } - - #[test] - fn truncates_at_glob_max_with_clear_message() { - let dir = tempfile::tempdir().unwrap(); - for i in 0..GLOB_MAX_MATCHES + 10 { - std::fs::write(dir.path().join(format!("f{i}.txt")), "x").unwrap(); - } - let out = glob_impl(dir.path(), &args("*.txt", None)).unwrap(); - assert!(!out.is_error); - assert!( - out.content.contains(&format!( - "truncated: showing {GLOB_MAX_MATCHES} of {} matches", - GLOB_MAX_MATCHES + 10 - )), - "{}", - out.content - ); - } -} diff --git a/crates/pulsing-forge/src/handlers/grep.rs b/crates/pulsing-forge/src/handlers/grep.rs deleted file mode 100644 index aa8035268..000000000 --- a/crates/pulsing-forge/src/handlers/grep.rs +++ /dev/null @@ -1,282 +0,0 @@ -use std::path::{Path, PathBuf}; - -use regex::Regex; -use serde_json::Value; - -use super::{err, json_str, ok}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -const GREP_MAX: usize = 200; -const GREP_PATTERN_MAX: usize = 1000; - -pub struct GrepHandler; - -impl ToolExecutor for GrepHandler { - fn tool_name(&self) -> &str { - "Grep" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - let cwd = ctx.cwd.clone(); - Box::pin(async move { grep_impl(&cwd, &arguments) }) - } -} - -fn resolve_path(cwd: &Path, path: &str) -> PathBuf { - let p = Path::new(path); - if p.is_absolute() { - p.to_path_buf() - } else { - cwd.join(p) - } -} - -/// When the search root lives under `cwd`, skip files that resolve outside `cwd` -/// (e.g. symlinks) while still allowing an explicit absolute `path` outside cwd. -fn search_boundary(cwd: &Path, root: &Path) -> Option { - let cwd_canon = cwd.canonicalize().ok()?; - let root_canon = root.canonicalize().ok()?; - root_canon.starts_with(&cwd_canon).then_some(cwd_canon) -} - -fn grep_impl(cwd: &Path, args: &Value) -> Result { - let raw_pat = json_str(args, "pattern")?; - if raw_pat.len() > GREP_PATTERN_MAX { - return err(format!( - "Pattern too long ({} > {GREP_PATTERN_MAX} chars); simplify the regex", - raw_pat.len() - )); - } - let root = args - .get("path") - .and_then(|v| v.as_str()) - .map(|p| resolve_path(cwd, p)) - .unwrap_or_else(|| cwd.to_path_buf()); - let glob_pat = args.get("glob").and_then(|v| v.as_str()); - let cre = Regex::new(raw_pat).map_err(|e| ToolError::respond(format!("Invalid regex: {e}")))?; - if !root.exists() { - return err("path not found"); - } - let boundary = search_boundary(cwd, &root); - let mut hits: Vec = Vec::new(); - let mut total = 0usize; - if root.is_file() { - consider_file( - &root, - &cre, - glob_pat, - boundary.as_deref(), - &mut hits, - &mut total, - ); - } else { - walk( - &root, - &cre, - glob_pat, - boundary.as_deref(), - &mut hits, - &mut total, - ); - } - if hits.is_empty() { - ok("(no matches)") - } else { - let extra = if total > GREP_MAX { - format!("\n… truncated: showing {GREP_MAX} of {total} matches …") - } else { - String::new() - }; - ok(format!("{}{}", hits.join("\n"), extra)) - } -} - -fn walk( - dir: &Path, - cre: &Regex, - glob_pat: Option<&str>, - boundary: Option<&Path>, - hits: &mut Vec, - total: &mut usize, -) { - let Ok(read) = std::fs::read_dir(dir) else { - return; - }; - for ent in read.flatten() { - let path = ent.path(); - if path.is_dir() { - walk(&path, cre, glob_pat, boundary, hits, total); - } else if path.is_file() { - consider_file(&path, cre, glob_pat, boundary, hits, total); - } - } -} - -fn consider_file( - fp: &Path, - cre: &Regex, - glob_pat: Option<&str>, - boundary: Option<&Path>, - hits: &mut Vec, - total: &mut usize, -) { - if let Some(b) = boundary { - let Ok(fp_canon) = fp.canonicalize() else { - return; - }; - if !fp_canon.starts_with(b) { - return; - } - } - if let Some(g) = glob_pat { - let name = fp.file_name().and_then(|n| n.to_str()).unwrap_or(""); - if !glob_match(g, name) { - return; - } - } - let Ok(text) = std::fs::read_to_string(fp) else { - return; - }; - for (i, line) in text.lines().enumerate() { - if cre.is_match(line) { - *total += 1; - if hits.len() < GREP_MAX { - hits.push(format!( - "{}:{}:{}", - fp.display(), - i + 1, - &line[..line.len().min(500)] - )); - } - } - } -} - -fn glob_match(pat: &str, name: &str) -> bool { - glob::Pattern::new(pat) - .map(|p| p.matches(name)) - .unwrap_or(false) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn args(pattern: &str, path: Option<&str>) -> Value { - let mut v = json!({"pattern": pattern}); - if let Some(p) = path { - v["path"] = json!(p); - } - v - } - - #[test] - fn finds_matching_lines() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("a.txt"), "hello\nworld\nhello again").unwrap(); - let out = grep_impl(dir.path(), &args("hello", None)).unwrap(); - assert!(!out.is_error); - assert_eq!(out.content.lines().count(), 2); - assert!(out.content.contains("a.txt:1:hello")); - } - - #[test] - fn reports_no_matches() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("a.txt"), "hello world").unwrap(); - let out = grep_impl(dir.path(), &args("nope", None)).unwrap(); - assert!(!out.is_error); - assert_eq!(out.content, "(no matches)"); - } - - #[test] - fn rejects_invalid_regex() { - // Invalid input surfaces as `Err(ToolError::RespondToModel)`, which the - // runtime turns into an error `ToolResult` (see `runtime.rs`). - let dir = tempfile::tempdir().unwrap(); - let err = grep_impl(dir.path(), &args("(unclosed", None)).unwrap_err(); - assert!(err.to_string().contains("Invalid regex"), "{err}"); - } - - #[test] - fn rejects_missing_path() { - let dir = tempfile::tempdir().unwrap(); - let out = grep_impl(dir.path(), &args("x", Some("does/not/exist"))).unwrap(); - assert!(out.is_error); - assert!(out.content.contains("path not found")); - } - - #[test] - fn is_immune_to_catastrophic_backtracking_pattern() { - // The `regex` crate guarantees linear-time matching, so a pattern that - // would cause exponential backtracking in a backtracking engine (e.g. - // Python's `re`) must still return promptly here. - let dir = tempfile::tempdir().unwrap(); - let evil_line = "a".repeat(40) + "!"; - std::fs::write(dir.path().join("a.txt"), &evil_line).unwrap(); - let start = std::time::Instant::now(); - let out = grep_impl(dir.path(), &args("(a+)+b", None)).unwrap(); - assert!(start.elapsed() < std::time::Duration::from_secs(2)); - assert!(!out.is_error); - assert_eq!(out.content, "(no matches)"); - } - - #[test] - fn truncates_at_grep_max_with_clear_message() { - let dir = tempfile::tempdir().unwrap(); - let many_lines = "hit\n".repeat(GREP_MAX + 10); - std::fs::write(dir.path().join("a.txt"), many_lines).unwrap(); - let out = grep_impl(dir.path(), &args("hit", None)).unwrap(); - assert!(!out.is_error); - assert!( - out.content.contains(&format!( - "truncated: showing {GREP_MAX} of {} matches", - GREP_MAX + 10 - )), - "{}", - out.content - ); - } - - #[test] - fn resolves_relative_path_against_cwd() { - let dir = tempfile::tempdir().unwrap(); - let sub = dir.path().join("sub"); - std::fs::create_dir(&sub).unwrap(); - std::fs::write(sub.join("a.txt"), "needle\n").unwrap(); - let out = grep_impl(dir.path(), &args("needle", Some("sub"))).unwrap(); - assert!(!out.is_error); - assert!(out.content.contains("needle")); - } - - #[test] - fn rejects_pattern_too_long() { - let dir = tempfile::tempdir().unwrap(); - let out = grep_impl(dir.path(), &args(&"a".repeat(GREP_PATTERN_MAX + 1), None)).unwrap(); - assert!(out.is_error); - assert!(out.content.contains("Pattern too long")); - } - - #[test] - #[cfg(unix)] - fn skips_symlink_targets_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let outside = tempfile::tempdir().unwrap(); - std::fs::write(outside.path().join("secret.txt"), "outside_secret\n").unwrap(); - std::os::unix::fs::symlink( - outside.path().join("secret.txt"), - dir.path().join("link.txt"), - ) - .unwrap(); - let out = grep_impl(dir.path(), &args("outside_secret", None)).unwrap(); - assert!(!out.is_error); - assert_eq!(out.content, "(no matches)"); - } -} diff --git a/crates/pulsing-forge/src/handlers/mcp.rs b/crates/pulsing-forge/src/handlers/mcp.rs deleted file mode 100644 index 81e7e6676..000000000 --- a/crates/pulsing-forge/src/handlers/mcp.rs +++ /dev/null @@ -1,499 +0,0 @@ -//! MCP resource + dynamic tool handlers (Codex-aligned). - -use serde_json::Value; - -use rmcp::model::{PaginatedRequestParams, ReadResourceRequestParams}; - -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture, ToolExposure}; -use crate::mcp::{ - LEGACY_MCP_TOOL_NAME_PREFIX, McpRuntime, enforce_resource_size_limit, validate_mcp_resource_uri, -}; -use crate::mcp::{McpClientError, ToolInfo, tool_input_schema_json}; -use crate::registry::ToolSpec; -use crate::result::ToolResult; - -fn optional_server_name(arguments: &Value) -> Result, ToolError> { - match arguments.get("server") { - None => Ok(None), - Some(v) => { - let raw = v - .as_str() - .ok_or_else(|| ToolError::respond("server must be a string"))?; - let trimmed = raw.trim(); - if trimmed.is_empty() { - return Err(ToolError::respond("server must be a non-empty string")); - } - Ok(Some(trimmed.to_string())) - } - } -} - -fn require_non_empty_str<'a>(arguments: &'a Value, field: &str) -> Result<&'a str, ToolError> { - let raw = arguments - .get(field) - .and_then(|v| v.as_str()) - .ok_or_else(|| ToolError::respond(format!("{field} is required")))?; - let trimmed = raw.trim(); - if trimmed.is_empty() { - return Err(ToolError::respond(format!( - "{field} must be a non-empty string" - ))); - } - Ok(trimmed) -} - -macro_rules! mcp_handler { - ($ty:ident, $tool:literal) => { - pub struct $ty; - - impl ToolExecutor for $ty { - fn tool_name(&self) -> &str { - $tool - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn supports_parallel(&self) -> bool { - true - } - - fn handle<'a>( - &'a self, - ctx: &'a ToolCallContext, - arguments: Value, - ) -> ToolExecutorFuture<'a> { - Box::pin(async move { - let rt = ctx - .mcp_runtime - .as_ref() - .ok_or_else(|| ToolError::respond("MCP runtime is not initialized"))?; - let guard = rt.read().await; - let mcp = guard - .as_ref() - .ok_or_else(|| ToolError::respond("MCP runtime is not started"))?; - dispatch_mcp_host_tool($tool, mcp, arguments).await - }) - } - } - }; -} - -mcp_handler!(ListMcpResourcesHandler, "list_mcp_resources"); -mcp_handler!( - ListMcpResourceTemplatesHandler, - "list_mcp_resource_templates" -); -mcp_handler!(ReadMcpResourceHandler, "read_mcp_resource"); - -pub struct McpDynamicToolHandler { - pub model_name: String, - pub supports_parallel: bool, - description: String, - input_schema: Value, -} - -impl McpDynamicToolHandler { - pub fn new(model_name: impl Into) -> Self { - Self { - model_name: model_name.into(), - supports_parallel: false, - description: "Call a dynamically registered MCP tool.".into(), - input_schema: serde_json::json!({"type": "object", "properties": {}}), - } - } - - pub fn from_tool_info(info: &ToolInfo, prefix_mcp_tool_names: bool) -> Self { - Self { - model_name: info.model_tool_name(prefix_mcp_tool_names), - supports_parallel: info.supports_parallel_tool_calls, - description: info - .tool - .description - .as_deref() - .unwrap_or("Call a dynamically registered MCP tool.") - .to_string(), - input_schema: tool_input_schema_json(&info.tool), - } - } -} - -impl ToolExecutor for McpDynamicToolHandler { - fn tool_name(&self) -> &str { - &self.model_name - } - - fn exposure(&self) -> ToolExposure { - ToolExposure::Deferred - } - - fn spec(&self) -> ToolSpec { - ToolSpec::function( - self.model_name.clone(), - self.description.clone(), - self.input_schema.clone(), - ) - } - - fn supports_parallel(&self) -> bool { - self.supports_parallel - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - let name = self.model_name.clone(); - Box::pin(async move { - let rt = ctx - .mcp_runtime - .as_ref() - .ok_or_else(|| ToolError::respond("MCP runtime is not initialized"))?; - let guard = rt.read().await; - let mcp = guard - .as_ref() - .ok_or_else(|| ToolError::respond("MCP runtime is not started"))?; - dispatch_mcp_dynamic_tool(mcp, &name, arguments).await - }) - } -} - -/// Dispatch an MCP function tool by model-visible name. Used by [`McpDynamicToolHandler`] -/// and [`ToolRuntime::call_tool`] fall-through. -pub async fn dispatch_mcp_dynamic_tool( - mcp: &McpRuntime, - model_name: &str, - arguments: Value, -) -> Result { - let tool = mcp.manager.find_tool(model_name).ok_or_else(|| { - ToolError::respond(format!( - "unknown MCP tool {model_name:?}; refresh MCP or list names via mcp_tool_names()" - )) - })?; - let result = mcp - .manager - .call_tool_by_model_name(model_name, arguments) - .await - .map_err(|e| format_mcp_dynamic_tool_error(&tool.server_name, &tool.tool.name, e))?; - Ok(format_call_tool_result(result)) -} - -/// Returns `Some` when `name` is a registered MCP dynamic tool, or uses the -/// ``mcp__`` prefix while MCP runtime is started (unknown names get MCP errors). -pub async fn try_call_mcp_dynamic_tool( - ctx: &ToolCallContext, - name: &str, - arguments: Value, -) -> Option> { - let slot = ctx.mcp_runtime.as_ref()?; - let guard = slot.read().await; - let mcp = guard.as_ref()?; - if name.starts_with(LEGACY_MCP_TOOL_NAME_PREFIX) || mcp.manager.find_tool(name).is_some() { - return Some(dispatch_mcp_dynamic_tool(mcp, name, arguments).await); - } - None -} - -fn format_mcp_dynamic_tool_error(server: &str, tool: &str, err: McpClientError) -> ToolError { - ToolError::respond(format!("MCP tool {server}/{tool} failed: {err}")) -} - -fn format_mcp_read_resource_error(server: &str, uri: &str, err: McpClientError) -> ToolError { - ToolError::respond(format!("MCP resource {server}/{uri} failed: {err}")) -} - -async fn dispatch_mcp_host_tool( - tool: &str, - mcp: &McpRuntime, - arguments: Value, -) -> Result { - match tool { - "list_mcp_resources" => { - let server = optional_server_name(&arguments)?; - let cursor = arguments - .get("cursor") - .and_then(|v| v.as_str()) - .map(str::to_string); - if let Some(server_name) = server { - let params = cursor.map(|c| PaginatedRequestParams::default().with_cursor(Some(c))); - let resources = mcp - .manager - .list_resources(&server_name, params) - .await - .map_err(|e| ToolError::respond(e.to_string()))?; - Ok(ToolResult::ok( - serde_json::to_string(&resources).unwrap_or_default(), - )) - } else { - if cursor.is_some() { - return Err(ToolError::respond( - "cursor can only be used when a server is specified", - )); - } - let all = mcp.manager.list_all_resources().await; - Ok(ToolResult::ok( - serde_json::to_string(&all).unwrap_or_default(), - )) - } - } - "list_mcp_resource_templates" => { - let server = require_non_empty_str(&arguments, "server")?; - let cursor = arguments - .get("cursor") - .and_then(|v| v.as_str()) - .map(str::to_string); - let params = cursor.map(|c| PaginatedRequestParams::default().with_cursor(Some(c))); - let templates = mcp - .manager - .list_resource_templates(server, params) - .await - .map_err(|e| ToolError::respond(e.to_string()))?; - Ok(ToolResult::ok( - serde_json::to_string(&templates).unwrap_or_default(), - )) - } - "read_mcp_resource" => { - let server = require_non_empty_str(&arguments, "server")?; - let uri = require_non_empty_str(&arguments, "uri")?; - validate_mcp_resource_uri(uri).map_err(ToolError::respond)?; - let params = ReadResourceRequestParams::new(uri.to_string()); - let result = mcp - .manager - .read_resource(server, params) - .await - .map_err(|e| format_mcp_read_resource_error(server, uri, e))?; - let result = enforce_resource_size_limit(result) - .map_err(|e| ToolError::respond(format!("MCP resource {server}/{uri}: {e}")))?; - Ok(ToolResult::ok( - serde_json::to_string(&result).unwrap_or_default(), - )) - } - _ => Err(ToolError::respond(format!("unknown MCP host tool: {tool}"))), - } -} - -fn format_call_tool_result(result: rmcp::model::CallToolResult) -> ToolResult { - let mut out = ToolResult::ok(serde_json::to_string(&result).unwrap_or_default()); - out.is_error = result.is_error.unwrap_or(false); - out -} - -pub fn mcp_resource_handlers() -> Vec> { - vec![ - Box::new(ListMcpResourcesHandler), - Box::new(ListMcpResourceTemplatesHandler), - Box::new(ReadMcpResourceHandler), - ] -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::mcp::{McpConnectionManager, McpRuntime, build_default_catalog}; - - async fn empty_runtime() -> McpRuntime { - let catalog = build_default_catalog(vec![], std::collections::HashMap::new()); - let manager = McpConnectionManager::start(&catalog, true).await; - McpRuntime { catalog, manager } - } - - #[tokio::test] - async fn dynamic_tool_unknown_name() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_dynamic_tool( - &mcp, - "mcp__missing__tool", - Value::Object(Default::default()), - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("unknown MCP tool")); - } - - #[tokio::test] - async fn read_mcp_resource_requires_server() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "read_mcp_resource", - &mcp, - serde_json::json!({"uri": "file:///tmp/x"}), - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("server is required")); - } - - #[tokio::test] - async fn read_mcp_resource_rejects_invalid_uri() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "read_mcp_resource", - &mcp, - serde_json::json!({"server": "demo", "uri": "not-a-uri"}), - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("invalid uri")); - } - - #[tokio::test] - async fn read_mcp_resource_rejects_empty_server() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "read_mcp_resource", - &mcp, - serde_json::json!({"server": " ", "uri": "file:///tmp/x"}), - ) - .await - .unwrap_err(); - assert!( - err.to_string() - .contains("server must be a non-empty string") - ); - } - - #[tokio::test] - async fn read_mcp_resource_requires_uri() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "read_mcp_resource", - &mcp, - serde_json::json!({"server": "demo"}), - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("uri is required")); - } - - #[tokio::test] - async fn read_mcp_resource_rejects_empty_uri() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "read_mcp_resource", - &mcp, - serde_json::json!({"server": "demo", "uri": " "}), - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("uri must be a non-empty string")); - } - - #[tokio::test] - async fn read_mcp_resource_unknown_server_includes_context() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "read_mcp_resource", - &mcp, - serde_json::json!({"server": "missing", "uri": "file:///tmp/x"}), - ) - .await - .unwrap_err(); - let msg = err.to_string(); - assert!(msg.contains("MCP resource missing/file:///tmp/x failed")); - assert!(msg.contains("MCP server not connected")); - } - - #[tokio::test] - async fn list_mcp_resource_templates_requires_server() { - let mcp = empty_runtime().await; - let err = - dispatch_mcp_host_tool("list_mcp_resource_templates", &mcp, serde_json::json!({})) - .await - .unwrap_err(); - assert!(err.to_string().contains("server is required")); - } - - #[tokio::test] - async fn list_mcp_resource_templates_rejects_empty_server() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "list_mcp_resource_templates", - &mcp, - serde_json::json!({"server": " "}), - ) - .await - .unwrap_err(); - assert!( - err.to_string() - .contains("server must be a non-empty string") - ); - } - - #[tokio::test] - async fn list_mcp_resource_templates_unknown_server() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "list_mcp_resource_templates", - &mcp, - serde_json::json!({"server": "missing"}), - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("MCP server not connected")); - } - - #[tokio::test] - async fn list_mcp_resources_empty_catalog_returns_object() { - let mcp = empty_runtime().await; - let out = dispatch_mcp_host_tool("list_mcp_resources", &mcp, serde_json::json!({})) - .await - .expect("list all resources"); - assert!(!out.is_error); - assert_eq!(out.content, "{}"); - } - - #[tokio::test] - async fn list_mcp_resources_cursor_requires_server() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "list_mcp_resources", - &mcp, - serde_json::json!({"cursor": "next"}), - ) - .await - .unwrap_err(); - assert!( - err.to_string() - .contains("cursor can only be used when a server is specified") - ); - } - - #[tokio::test] - async fn list_mcp_resources_unknown_server_errors() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "list_mcp_resources", - &mcp, - serde_json::json!({"server": "missing-server"}), - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("MCP server not connected")); - } - - #[tokio::test] - async fn list_mcp_resources_rejects_blank_server() { - let mcp = empty_runtime().await; - let err = dispatch_mcp_host_tool( - "list_mcp_resources", - &mcp, - serde_json::json!({"server": " "}), - ) - .await - .unwrap_err(); - assert!( - err.to_string() - .contains("server must be a non-empty string") - ); - } - - #[tokio::test] - async fn list_mcp_resources_rejects_non_string_server() { - let mcp = empty_runtime().await; - let err = - dispatch_mcp_host_tool("list_mcp_resources", &mcp, serde_json::json!({"server": 1})) - .await - .unwrap_err(); - assert!(err.to_string().contains("server must be a string")); - } -} diff --git a/crates/pulsing-forge/src/handlers/mod.rs b/crates/pulsing-forge/src/handlers/mod.rs deleted file mode 100644 index 379e89786..000000000 --- a/crates/pulsing-forge/src/handlers/mod.rs +++ /dev/null @@ -1,396 +0,0 @@ -//! Built-in tool handlers. - -mod apply_patch; -mod bash; -mod discovery; -mod edit; -mod glob; -mod grep; -mod plan; -mod read; -mod request_permissions; -mod session; -mod shell; -pub(crate) mod shell_exec; -mod view_image; -mod write; - -mod mcp; - -pub use mcp::{ - ListMcpResourceTemplatesHandler, ListMcpResourcesHandler, McpDynamicToolHandler, - ReadMcpResourceHandler, dispatch_mcp_dynamic_tool, mcp_resource_handlers, - try_call_mcp_dynamic_tool, -}; - -pub use apply_patch::ApplyPatchHandler; -pub use bash::BashHandler; -pub use discovery::{ListAvailablePluginsHandler, RequestPluginInstallHandler, ToolSearchHandler}; -pub use edit::EditHandler; -pub use glob::GlobHandler; -pub use grep::GrepHandler; -pub use plan::UpdatePlanHandler; -pub use read::ReadHandler; -pub use request_permissions::RequestPermissionsHandler; -pub use session::{ - GetContextRemainingHandler, NEW_CONTEXT_MESSAGE, NewContextHandler, RequestUserInputHandler, -}; -pub use shell::{ExecCommandHandler, ShellCommandHandler, WriteStdinHandler}; -pub use view_image::ViewImageHandler; -pub use write::WriteHandler; - -use crate::error::ToolError; -use crate::executor::ToolExecutor; -use crate::registry::ToolSpec; -use crate::result::ToolResult; -use serde_json::json; - -/// Canonical model schemas for built-in Forge executors. -/// -/// Built-in executors explicitly return their entry from this catalog, so both -/// registry exposure and dispatch are rooted in the same registered object. -/// Dynamic executors such as MCP tools provide their own `ToolExecutor::spec`. -pub(crate) fn builtin_spec(name: &str) -> ToolSpec { - let object = |properties, required: &[&str]| { - json!({ - "type": "object", - "properties": properties, - "required": required, - "additionalProperties": false, - }) - }; - match name { - "shell_command" => ToolSpec::function( - name, - "Run a shell command in the workspace.", - object( - json!({ - "command": {"type": "string"}, - "cmd": {"type": "string"}, - "workdir": {"type": "string"}, - "timeout_ms": {"type": "integer"}, - "login": {"type": "boolean"}, - "sandbox_permissions": {"type": "string"}, - "justification": {"type": "string"} - }), - &[], - ), - ), - "exec_command" => ToolSpec::function( - name, - "Start a command, optionally keeping an interactive PTY session.", - object( - json!({ - "cmd": {"type": "string"}, - "command": {"type": "string"}, - "workdir": {"type": "string"}, - "yield_time_ms": {"type": "integer"}, - "max_output_tokens": {"type": "integer"}, - "tty": {"type": "boolean"}, - "login": {"type": "boolean"}, - "sandbox_permissions": {"type": "string"}, - "justification": {"type": "string"}, - "prefix_rule": {"type": "array", "items": {"type": "string"}} - }), - &[], - ), - ), - "write_stdin" => ToolSpec::function( - name, - "Write input to or poll a running exec_command session.", - object( - json!({ - "session_id": {"type": "integer"}, - "chars": {"type": "string"}, - "yield_time_ms": {"type": "integer"}, - "max_output_tokens": {"type": "integer"} - }), - &["session_id"], - ), - ), - "apply_patch" => ToolSpec::function( - name, - "Apply a structured patch to files in the workspace.", - object(json!({"patch": {"type": "string"}}), &["patch"]), - ), - "view_image" => ToolSpec::function( - name, - "Load a local image for visual inspection.", - object( - json!({ - "path": {"type": "string"}, - "detail": {"type": "string", "enum": ["high", "original"]} - }), - &["path"], - ), - ), - "update_plan" => ToolSpec::function( - name, - "Update the multi-step plan visible to the user.", - object( - json!({ - "plan": { - "type": "array", - "items": { - "type": "object", - "properties": { - "step": {"type": "string"}, - "status": { - "type": "string", - "enum": ["pending", "in_progress", "completed"] - } - }, - "required": ["step", "status"], - "additionalProperties": false - } - }, - "explanation": {"type": "string"} - }), - &["plan"], - ), - ), - "new_context" => ToolSpec::function( - name, - "Request a fresh context window for the current Forge session.", - object(json!({}), &[]), - ), - "get_context_remaining" => ToolSpec::function( - name, - "Return the estimated tokens remaining in the current context.", - object(json!({}), &[]), - ), - "request_user_input" => ToolSpec::function( - name, - "Ask the user one or more short structured questions.", - object( - json!({ - "questions": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "properties": { - "id": {"type": "string"}, - "header": {"type": "string"}, - "question": {"type": "string"}, - "isOther": {"type": "boolean"}, - "isSecret": {"type": "boolean"}, - "options": { - "type": "array", - "items": { - "type": "object", - "properties": { - "label": {"type": "string"}, - "description": {"type": "string"} - }, - "required": ["label", "description"], - "additionalProperties": false - } - } - }, - "required": ["id", "header", "question"], - "additionalProperties": false - } - }, - "autoResolutionMs": {"type": "integer", "minimum": 60000, "maximum": 240000} - }), - &["questions"], - ), - ), - "request_permissions" => ToolSpec::function( - name, - "Request scoped network or filesystem permissions from the host.", - object( - json!({ - "permissions": { - "type": "object", - "properties": { - "network": {"type": "object"}, - "file_system": {"type": "object"} - } - }, - "reason": {"type": "string"} - }), - &["permissions"], - ), - ), - "tool_search" => ToolSpec::function( - name, - "Search deferred tools and integrations available to this session.", - object( - json!({ - "query": {"type": "string"}, - "limit": {"type": "integer", "minimum": 1} - }), - &["query"], - ), - ), - "list_available_plugins_to_install" => ToolSpec::function( - name, - "List Forge plugins that are available but not installed.", - object(json!({}), &[]), - ), - "request_plugin_install" => ToolSpec::function( - name, - "Request installation of a specific Forge plugin.", - object( - json!({ - "tool_id": {"type": "string"}, - "tool_type": {"type": "string", "enum": ["plugin", "connector"]}, - "action_type": {"type": "string", "enum": ["install", "enable"]}, - "suggest_reason": {"type": "string"} - }), - &["tool_id", "suggest_reason"], - ), - ), - "list_mcp_resources" => ToolSpec::function( - name, - "List resources exposed by connected MCP servers.", - object( - json!({ - "server": {"type": "string"}, - "cursor": {"type": "string"} - }), - &[], - ), - ), - "list_mcp_resource_templates" => ToolSpec::function( - name, - "List resource templates exposed by one MCP server.", - object( - json!({ - "server": {"type": "string"}, - "cursor": {"type": "string"} - }), - &["server"], - ), - ), - "read_mcp_resource" => ToolSpec::function( - name, - "Read a resource from a connected MCP server.", - object( - json!({ - "server": {"type": "string"}, - "uri": {"type": "string"} - }), - &["server", "uri"], - ), - ), - "Read" => ToolSpec::function( - name, - "Read a UTF-8 file from the workspace.", - object( - json!({ - "file_path": {"type": "string"}, - "offset": {"type": "integer", "minimum": 1}, - "limit": {"type": "integer", "minimum": 1} - }), - &["file_path"], - ), - ), - "Glob" => ToolSpec::function( - name, - "Find files by glob pattern.", - object( - json!({ - "pattern": {"type": "string"}, - "path": {"type": "string"} - }), - &["pattern"], - ), - ), - "Grep" => ToolSpec::function( - name, - "Search workspace file contents with a regular expression.", - object( - json!({ - "pattern": {"type": "string"}, - "path": {"type": "string"}, - "glob": {"type": "string"} - }), - &["pattern"], - ), - ), - "Edit" => ToolSpec::function( - name, - "Replace one unique string occurrence in a workspace file.", - object( - json!({ - "file_path": {"type": "string"}, - "old_string": {"type": "string"}, - "new_string": {"type": "string"} - }), - &["file_path", "old_string", "new_string"], - ), - ), - "Write" => ToolSpec::function( - name, - "Create or overwrite a file inside the workspace.", - object( - json!({ - "file_path": {"type": "string"}, - "content": {"type": "string"} - }), - &["file_path", "content"], - ), - ), - "Bash" => ToolSpec::function( - name, - "Legacy alias for running a shell command in the workspace.", - object( - json!({ - "command": {"type": "string"}, - "workdir": {"type": "string"}, - "timeout_ms": {"type": "integer"} - }), - &["command"], - ), - ), - _ => panic!("tool {name:?} must implement ToolExecutor::spec"), - } -} - -pub fn builtin_handlers() -> Vec> { - vec![ - // Codex shell / file - Box::new(ShellCommandHandler), - Box::new(ExecCommandHandler), - Box::new(WriteStdinHandler), - Box::new(ApplyPatchHandler), - Box::new(ViewImageHandler), - // Codex plan / session - Box::new(UpdatePlanHandler), - Box::new(NewContextHandler), - Box::new(GetContextRemainingHandler), - Box::new(RequestUserInputHandler), - Box::new(RequestPermissionsHandler), - Box::new(ToolSearchHandler), - Box::new(ListAvailablePluginsHandler), - Box::new(RequestPluginInstallHandler), - // MCP resource helpers (Codex core tools) - Box::new(ListMcpResourcesHandler), - Box::new(ListMcpResourceTemplatesHandler), - Box::new(ReadMcpResourceHandler), - // Claude-style helpers (kept for Craft compatibility) - Box::new(ReadHandler), - Box::new(GlobHandler), - Box::new(GrepHandler), - Box::new(EditHandler), - Box::new(WriteHandler), - Box::new(BashHandler), - ] -} - -pub(crate) fn json_str<'a>(v: &'a serde_json::Value, key: &str) -> Result<&'a str, ToolError> { - v.get(key) - .and_then(|x| x.as_str()) - .ok_or_else(|| ToolError::respond(format!("missing or invalid string field {key:?}"))) -} - -pub(crate) fn ok(content: impl Into) -> Result { - Ok(ToolResult::ok(content)) -} - -pub(crate) fn err(content: impl Into) -> Result { - Ok(ToolResult::err(content)) -} diff --git a/crates/pulsing-forge/src/handlers/plan.rs b/crates/pulsing-forge/src/handlers/plan.rs deleted file mode 100644 index 3c88d9b47..000000000 --- a/crates/pulsing-forge/src/handlers/plan.rs +++ /dev/null @@ -1,130 +0,0 @@ -use serde_json::Value; - -use super::ok; -use crate::context::{StepStatus, ToolCallContext, UpdatePlanArgs}; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -/// Must stay byte-for-byte identical to `PLAN_UPDATED` in -/// `python/pulsing/forge/handlers.py` — that pure-Python fallback path does not -/// link against this crate, so the string is duplicated rather than shared. -const PLAN_UPDATED: &str = "Plan updated"; - -pub struct UpdatePlanHandler; - -impl ToolExecutor for UpdatePlanHandler { - fn tool_name(&self) -> &str { - "update_plan" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { update_plan_impl(ctx, arguments) }) - } -} - -fn validate_update_plan(value: &Value) -> Result { - let args: UpdatePlanArgs = serde_json::from_value(value.clone()) - .map_err(|e| ToolError::respond(format!("failed to parse update_plan arguments: {e}")))?; - - let in_progress = args - .plan - .iter() - .filter(|item| item.status == StepStatus::InProgress) - .count(); - if in_progress > 1 { - return Err(ToolError::respond( - "update_plan allows at most one step with status \"in_progress\"", - )); - } - - Ok(args) -} - -fn update_plan_impl( - ctx: &ToolCallContext, - arguments: Value, -) -> Result { - let args = validate_update_plan(&arguments)?; - ctx.session.update_plan(args)?; - ok(PLAN_UPDATED) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::approval::{ApprovalCache, new_exec_policy}; - use crate::context::LocalToolSession; - use crate::discovery::new_tool_catalog; - use crate::unified_exec::UnifiedExecManager; - use std::sync::Arc; - - fn test_ctx(session: Arc) -> ToolCallContext { - ToolCallContext::new( - ".", - "off", - session, - Arc::new(UnifiedExecManager::new()), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - new_tool_catalog(), - ) - } - - #[test] - fn rejects_multiple_in_progress() { - let raw = serde_json::json!({ - "plan": [ - {"step": "one", "status": "in_progress"}, - {"step": "two", "status": "in_progress"} - ] - }); - let err = validate_update_plan(&raw).unwrap_err(); - assert_eq!( - err, - ToolError::respond("update_plan allows at most one step with status \"in_progress\"") - ); - } - - #[test] - fn accepts_single_in_progress() { - let raw = serde_json::json!({ - "plan": [ - {"step": "one", "status": "completed"}, - {"step": "two", "status": "in_progress"} - ] - }); - let args = validate_update_plan(&raw).unwrap(); - assert_eq!(args.plan.len(), 2); - } - - #[test] - fn rejects_missing_plan_field() { - let raw = serde_json::json!({}); - let err = validate_update_plan(&raw).unwrap_err(); - let msg = err.to_string(); - assert!( - msg.contains("plan"), - "expected parse error mentioning plan, got: {msg}" - ); - } - - #[test] - fn update_plan_impl_updates_session() { - let session = Arc::new(LocalToolSession::default()); - let ctx = test_ctx(session.clone()); - let out = update_plan_impl( - &ctx, - serde_json::json!({ - "plan": [{"step": "one", "status": "pending"}] - }), - ) - .unwrap(); - assert!(!out.is_error); - assert_eq!(out.content, PLAN_UPDATED); - assert_eq!(session.plan_snapshot().len(), 1); - } -} diff --git a/crates/pulsing-forge/src/handlers/read.rs b/crates/pulsing-forge/src/handlers/read.rs deleted file mode 100644 index ae7f6879b..000000000 --- a/crates/pulsing-forge/src/handlers/read.rs +++ /dev/null @@ -1,199 +0,0 @@ -use std::io::{self, BufRead}; -use std::path::{Path, PathBuf}; - -use serde_json::Value; - -use super::{err, json_str, ok}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -/// Hard cap for a single read (or for the slice returned by a paginated read). -/// Larger files must be read with `offset`/`limit` instead of being rejected outright. -const READ_CAP: usize = 2 * 1024 * 1024; - -pub struct ReadHandler; - -impl ToolExecutor for ReadHandler { - fn tool_name(&self) -> &str { - "Read" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - let cwd = ctx.cwd.clone(); - Box::pin(async move { read_impl(&cwd, &arguments) }) - } -} - -fn resolve_path(cwd: &Path, path: &str) -> PathBuf { - let p = Path::new(path); - if p.is_absolute() { - p.to_path_buf() - } else { - cwd.join(p) - } -} - -fn read_impl(cwd: &Path, args: &Value) -> Result { - let path = json_str(args, "file_path")?; - let abs = resolve_path(cwd, path); - let offset = args.get("offset").and_then(Value::as_u64); - let limit = args.get("limit").and_then(Value::as_u64); - - if abs.is_dir() { - return err(format!( - "Path is a directory, not a file: {}", - abs.display() - )); - } - - if offset.is_some() || limit.is_some() { - let start_line = offset.unwrap_or(1).max(1) as usize; - return read_range(&abs, start_line, limit.map(|l| l as usize)); - } - - let data = std::fs::read(&abs).map_err(|e| read_error(&abs, &e))?; - if data.len() > READ_CAP { - return err(format!( - "File too large for Read tool ({} bytes > {READ_CAP} cap); retry with offset/limit to page through it.", - data.len() - )); - } - let text = String::from_utf8(data) - .map_err(|_| ToolError::respond(format!("Not valid UTF-8: {}", abs.display())))?; - ok(text) -} - -/// Streams the file line by line so a paginated read doesn't need the whole file in memory. -fn read_range( - path: &Path, - start_line: usize, - limit: Option, -) -> Result { - let file = std::fs::File::open(path).map_err(|e| read_error(path, &e))?; - let end_line = limit.map(|n| start_line.saturating_add(n)); - let mut out = String::new(); - - for (idx, line) in io::BufReader::new(file).lines().enumerate() { - let lineno = idx + 1; - if lineno < start_line { - continue; - } - if end_line.is_some_and(|end| lineno >= end) { - break; - } - let line = line.map_err(|_| { - ToolError::respond(format!( - "Not valid UTF-8 at line {lineno}: {}", - path.display() - )) - })?; - out.push_str(&line); - out.push('\n'); - if out.len() > READ_CAP { - return err("Requested range too large for Read tool; use a smaller limit."); - } - } - ok(out) -} - -fn read_error(path: &Path, e: &io::Error) -> ToolError { - let reason = match e.kind() { - io::ErrorKind::NotFound => "No such file".to_string(), - io::ErrorKind::PermissionDenied => "Permission denied".to_string(), - _ => e.to_string(), - }; - ToolError::respond(format!("{reason}: {}", path.display())) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Mirrors how `ToolRuntime::call_tool` turns a propagated `ToolError` into - /// a model-visible error result (see `runtime.rs`), so tests can assert on - /// `ToolResult` regardless of whether a handler used `err(..)` or `?`. - fn run(cwd: &Path, args: Value) -> crate::result::ToolResult { - match read_impl(cwd, &args) { - Ok(r) => r, - Err(e) => crate::result::ToolResult::err(e.to_string()), - } - } - - #[test] - fn reads_whole_file() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("a.txt"), "hello").unwrap(); - let out = run(dir.path(), serde_json::json!({"file_path": "a.txt"})); - assert!(!out.is_error); - assert_eq!(out.content, "hello"); - } - - #[test] - fn rejects_oversized_file() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("big.txt"), vec![b'x'; READ_CAP + 1]).unwrap(); - let out = run(dir.path(), serde_json::json!({"file_path": "big.txt"})); - assert!(out.is_error); - assert!(out.content.contains("too large")); - } - - #[test] - fn rejects_non_utf8() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("bin.dat"), [0xff, 0xfe, 0x00, 0xff]).unwrap(); - let out = run(dir.path(), serde_json::json!({"file_path": "bin.dat"})); - assert!(out.is_error); - assert!(out.content.contains("Not valid UTF-8")); - } - - #[test] - fn missing_file_reports_path() { - let dir = tempfile::tempdir().unwrap(); - let out = run(dir.path(), serde_json::json!({"file_path": "missing.txt"})); - assert!(out.is_error); - assert!(out.content.contains("missing.txt")); - assert!(out.content.contains("No such file")); - } - - #[test] - fn rejects_directory() { - let dir = tempfile::tempdir().unwrap(); - std::fs::create_dir(dir.path().join("sub")).unwrap(); - let out = run(dir.path(), serde_json::json!({"file_path": "sub"})); - assert!(out.is_error); - assert!(out.content.contains("directory")); - } - - #[test] - fn offset_and_limit_page_through_lines() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("lines.txt"), "l1\nl2\nl3\nl4\nl5\n").unwrap(); - let out = run( - dir.path(), - serde_json::json!({"file_path": "lines.txt", "offset": 2, "limit": 2}), - ); - assert!(!out.is_error); - assert_eq!(out.content, "l2\nl3\n"); - } - - #[test] - fn offset_beyond_cap_still_streams_without_loading_whole_file() { - let dir = tempfile::tempdir().unwrap(); - let mut content = String::new(); - for i in 0..100_000 { - content.push_str(&format!("line {i}\n")); - } - std::fs::write(dir.path().join("huge.txt"), &content).unwrap(); - let out = run( - dir.path(), - serde_json::json!({"file_path": "huge.txt", "offset": 99_999, "limit": 1}), - ); - assert!(!out.is_error); - assert_eq!(out.content, "line 99998\n"); - } -} diff --git a/crates/pulsing-forge/src/handlers/request_permissions.rs b/crates/pulsing-forge/src/handlers/request_permissions.rs deleted file mode 100644 index b4d71bac1..000000000 --- a/crates/pulsing-forge/src/handlers/request_permissions.rs +++ /dev/null @@ -1,247 +0,0 @@ -use serde_json::Value; - -use super::ok; -use crate::approval::RequestPermissionsArgs; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -pub struct RequestPermissionsHandler; - -impl ToolExecutor for RequestPermissionsHandler { - fn tool_name(&self) -> &str { - "request_permissions" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { request_permissions_impl(ctx, arguments) }) - } -} - -fn request_permissions_impl( - ctx: &ToolCallContext, - arguments: Value, -) -> Result { - let args: RequestPermissionsArgs = serde_json::from_value(arguments) - .map_err(|e| ToolError::respond(format!("failed to parse request_permissions: {e}")))?; - if !args.permissions.has_actionable_request() { - return Err(ToolError::respond( - "request_permissions requires non-empty network or file_system permissions", - )); - } - args.permissions - .validate_paths(&ctx.cwd) - .map_err(ToolError::respond)?; - let response = ctx.session.request_permissions(args)?; - if response.permissions.is_effectively_empty() { - return Err(ToolError::respond("permissions denied by host")); - } - ctx.approval_cache - .record_permission_grant(response.permissions.clone(), &response.scope); - if response.strict_auto_review { - ctx.approval_cache.set_strict_auto_review(true); - } - let text = serde_json::to_string_pretty(&response) - .map_err(|e| ToolError::respond(format!("encode request_permissions response: {e}")))?; - ok(text) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::approval::{ - ApprovalCache, RequestPermissionProfile, RequestPermissionsArgs, RequestPermissionsResponse, - }; - use crate::context::LocalToolSession; - use crate::runtime::{ToolRuntime, ToolRuntimeConfig}; - use std::sync::Arc; - - fn rt_with_perms(f: F) -> ToolRuntime - where - F: Fn(RequestPermissionsArgs) -> Result - + Send - + Sync - + 'static, - { - let session = Arc::new(LocalToolSession::default().with_request_permissions(f)); - ToolRuntime::new(ToolRuntimeConfig { - session, - ..Default::default() - }) - } - - #[tokio::test] - async fn rejects_missing_permission_sections() { - let rt = rt_with_perms(|_| { - Ok(RequestPermissionsResponse { - permissions: RequestPermissionProfile { - network: Some(serde_json::json!({"enabled": true})), - file_system: None, - }, - scope: "turn".into(), - strict_auto_review: false, - }) - }); - let out = rt - .call_tool( - "request_permissions", - serde_json::json!({"permissions": {}}), - ) - .await; - assert!(out.is_error); - assert!(out.content.contains("non-empty")); - } - - #[tokio::test] - async fn rejects_empty_nested_network_object() { - let rt = rt_with_perms(|_| { - Ok(RequestPermissionsResponse { - permissions: RequestPermissionProfile { - network: Some(serde_json::json!({"enabled": true})), - file_system: None, - }, - scope: "turn".into(), - strict_auto_review: false, - }) - }); - let out = rt - .call_tool( - "request_permissions", - serde_json::json!({"permissions": {"network": {}}}), - ) - .await; - assert!(out.is_error); - } - - #[tokio::test] - async fn rejects_host_empty_grant() { - let rt = rt_with_perms(|_| { - Ok(RequestPermissionsResponse { - permissions: RequestPermissionProfile::default(), - scope: "turn".into(), - strict_auto_review: false, - }) - }); - let out = rt - .call_tool( - "request_permissions", - serde_json::json!({"permissions": {"network": {"enabled": true}}}), - ) - .await; - assert!(out.is_error); - assert!(out.content.contains("denied")); - } - - #[tokio::test] - async fn sets_strict_auto_review_on_host_grant() { - let cache = Arc::new(ApprovalCache::default()); - let session = Arc::new( - LocalToolSession::default().with_request_permissions(|args| { - Ok(RequestPermissionsResponse { - permissions: args.permissions, - scope: "turn".into(), - strict_auto_review: true, - }) - }), - ); - let rt = ToolRuntime::new(ToolRuntimeConfig { - session, - approval_cache: cache.clone(), - ..Default::default() - }); - let out = rt - .call_tool( - "request_permissions", - serde_json::json!({"permissions": {"network": {"enabled": true}}}), - ) - .await; - assert!(!out.is_error); - assert!(cache.strict_auto_review()); - } - - #[tokio::test] - async fn new_context_clears_strict_auto_review() { - let cache = Arc::new(ApprovalCache::default()); - cache.set_strict_auto_review(true); - cache.record_permission_grant( - RequestPermissionProfile { - network: Some(serde_json::json!({"enabled": true})), - file_system: None, - }, - "turn", - ); - let session = Arc::new(LocalToolSession::default()); - let rt = ToolRuntime::new(ToolRuntimeConfig { - session, - approval_cache: cache.clone(), - ..Default::default() - }); - let out = rt.call_tool("new_context", serde_json::json!({})).await; - assert!(!out.is_error); - assert!(!cache.strict_auto_review()); - assert!(!cache.network_granted()); - } - - #[tokio::test] - async fn records_session_grant_after_approval() { - let cache = Arc::new(ApprovalCache::default()); - let session = Arc::new( - LocalToolSession::default().with_request_permissions(|args| { - Ok(RequestPermissionsResponse { - permissions: args.permissions, - scope: "session".into(), - strict_auto_review: false, - }) - }), - ); - let rt = ToolRuntime::new(ToolRuntimeConfig { - session, - approval_cache: cache.clone(), - ..Default::default() - }); - let out = rt - .call_tool( - "request_permissions", - serde_json::json!({"permissions": {"network": {"enabled": true}}}), - ) - .await; - assert!(!out.is_error); - assert!(cache.network_granted()); - } - - #[tokio::test] - async fn rejects_path_outside_cwd() { - let rt = rt_with_perms(|_| { - Ok(RequestPermissionsResponse { - permissions: RequestPermissionProfile { - network: None, - file_system: Some(serde_json::json!({"write": ["/etc/passwd"]})), - }, - scope: "turn".into(), - strict_auto_review: false, - }) - }); - let out = rt - .call_tool( - "request_permissions", - serde_json::json!({"permissions": {"file_system": {"write": ["/etc/passwd"]}}}), - ) - .await; - assert!(out.is_error); - assert!(out.content.contains("outside working directory")); - } - - #[test] - fn permission_profile_detects_codex_empty_shapes() { - let profile = RequestPermissionProfile { - network: Some(serde_json::json!({"enabled": null})), - file_system: Some(serde_json::json!({"entries": []})), - }; - assert!(profile.is_effectively_empty()); - assert!(!profile.has_actionable_request()); - } -} diff --git a/crates/pulsing-forge/src/handlers/session.rs b/crates/pulsing-forge/src/handlers/session.rs deleted file mode 100644 index 5ab21d807..000000000 --- a/crates/pulsing-forge/src/handlers/session.rs +++ /dev/null @@ -1,235 +0,0 @@ -use serde_json::Value; - -use super::ok; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -use crate::session_input::{args_to_value, validate_request_user_input}; - -/// Must stay byte-for-byte identical to `NEW_CONTEXT_MESSAGE` in -/// `python/pulsing/forge/handlers.py` — that pure-Python fallback path does not -/// link against this crate, so the string is duplicated rather than shared. -pub const NEW_CONTEXT_MESSAGE: &str = - "A new context window will start without summarizing conversation history."; - -pub struct NewContextHandler; - -impl ToolExecutor for NewContextHandler { - fn tool_name(&self) -> &str { - "new_context" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, _arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { new_context_impl(ctx) }) - } -} - -fn new_context_impl(ctx: &ToolCallContext) -> Result { - ctx.approval_cache.clear_turn_state(); - ctx.session.request_new_context()?; - ok(NEW_CONTEXT_MESSAGE) -} - -pub struct GetContextRemainingHandler; - -impl ToolExecutor for GetContextRemainingHandler { - fn tool_name(&self) -> &str { - "get_context_remaining" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, _arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { get_context_remaining_impl(ctx) }) - } -} - -fn get_context_remaining_impl( - ctx: &ToolCallContext, -) -> Result { - let remaining = ctx.session.tokens_remaining(); - let payload = match remaining { - Some(n) => serde_json::json!({ - "tokens_remaining": n, - "status": "ok", - }), - None => serde_json::json!({ - "tokens_remaining": null, - "status": "unknown", - }), - }; - let text = serde_json::to_string_pretty(&payload) - .map_err(|e| ToolError::respond(format!("failed to encode context remaining: {e}")))?; - ok(text) -} - -pub struct RequestUserInputHandler; - -impl ToolExecutor for RequestUserInputHandler { - fn tool_name(&self) -> &str { - "request_user_input" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { request_user_input_impl(ctx, arguments) }) - } -} - -fn request_user_input_impl( - ctx: &ToolCallContext, - arguments: Value, -) -> Result { - let validated = validate_request_user_input(&arguments)?; - let response = ctx.session.request_user_input(args_to_value(&validated))?; - let text = serde_json::to_string_pretty(&response) - .map_err(|e| ToolError::respond(format!("failed to encode user input response: {e}")))?; - ok(text) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::approval::{ApprovalCache, new_exec_policy}; - use crate::context::LocalToolSession; - use crate::discovery::new_tool_catalog; - use crate::unified_exec::UnifiedExecManager; - use std::sync::Arc; - - fn test_ctx(session: Arc) -> ToolCallContext { - ToolCallContext::new( - ".", - "off", - session, - Arc::new(UnifiedExecManager::new()), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - new_tool_catalog(), - ) - } - - struct FailingSession; - - impl crate::context::ToolSession for FailingSession { - fn update_plan(&self, _args: crate::context::UpdatePlanArgs) -> Result<(), ToolError> { - Ok(()) - } - - fn request_new_context(&self) -> Result<(), ToolError> { - Err(ToolError::respond("session unavailable")) - } - - fn tokens_remaining(&self) -> Option { - None - } - - fn request_user_input(&self, _arguments: Value) -> Result { - Err(ToolError::respond("not supported")) - } - } - - #[test] - fn new_context_requests_reset_and_returns_message() { - let session = Arc::new(LocalToolSession::default()); - let ctx = test_ctx(session.clone()); - let out = new_context_impl(&ctx).unwrap(); - assert!(!out.is_error); - assert_eq!(out.content, NEW_CONTEXT_MESSAGE); - assert!(session.new_context_requested()); - } - - #[test] - fn new_context_propagates_session_error() { - let ctx = test_ctx(Arc::new(FailingSession)); - let err = new_context_impl(&ctx).unwrap_err(); - assert_eq!(err.to_string(), "session unavailable"); - } - - #[test] - fn get_context_remaining_reports_budget_when_known() { - let ctx = test_ctx(Arc::new(LocalToolSession::new(Some(42_000)))); - let out = get_context_remaining_impl(&ctx).unwrap(); - assert!(!out.is_error); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - assert_eq!(payload["tokens_remaining"], 42_000); - assert_eq!(payload["status"], "ok"); - } - - #[test] - fn get_context_remaining_reports_unknown_without_budget() { - let ctx = test_ctx(Arc::new(LocalToolSession::default())); - let out = get_context_remaining_impl(&ctx).unwrap(); - assert!(!out.is_error); - let payload: Value = serde_json::from_str(&out.content).unwrap(); - assert!(payload["tokens_remaining"].is_null()); - assert_eq!(payload["status"], "unknown"); - } - - #[test] - fn request_user_input_rejects_empty_questions() { - let ctx = test_ctx(Arc::new(LocalToolSession::default())); - let err = - request_user_input_impl(&ctx, serde_json::json!({ "questions": [] })).unwrap_err(); - assert!(err.to_string().contains("question")); - } - - #[test] - fn request_user_input_reports_malformed_auto_resolution_ms() { - let ctx = test_ctx(Arc::new(LocalToolSession::default())); - let err = request_user_input_impl( - &ctx, - serde_json::json!({ - "questions": [{"id": "q1", "header": "H", "question": "Q?"}], - "autoResolutionMs": {"bad": true} - }), - ) - .unwrap_err(); - assert!(err.to_string().to_lowercase().contains("autoresolutionms")); - } - - #[test] - fn request_user_input_passes_clamped_payload_to_session() { - use crate::session_input::MIN_AUTO_RESOLUTION_MS; - use std::sync::Mutex; - - let seen = Arc::new(Mutex::new(None::)); - let seen_cb = seen.clone(); - let session = Arc::new(LocalToolSession::default().with_user_input(move |args| { - *seen_cb.lock().unwrap() = Some(args); - Ok(serde_json::json!({ - "answers": { "q1": { "answers": ["A"] } } - })) - })); - let ctx = test_ctx(session); - let out = request_user_input_impl( - &ctx, - serde_json::json!({ - "questions": [{ - "id": "q1", - "header": "Pick", - "question": "Which?", - "options": [{"label": "A", "description": "first"}] - }], - "autoResolutionMs": 1 - }), - ) - .unwrap(); - assert!(!out.is_error); - let payload = seen - .lock() - .unwrap() - .clone() - .expect("session callback invoked"); - assert_eq!(payload["autoResolutionMs"], MIN_AUTO_RESOLUTION_MS); - } -} diff --git a/crates/pulsing-forge/src/handlers/shell.rs b/crates/pulsing-forge/src/handlers/shell.rs deleted file mode 100644 index fb45f74d7..000000000 --- a/crates/pulsing-forge/src/handlers/shell.rs +++ /dev/null @@ -1,53 +0,0 @@ -use serde_json::Value; - -use super::shell_exec::run_shell; -use crate::context::ToolCallContext; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -pub struct ShellCommandHandler; - -impl ToolExecutor for ShellCommandHandler { - fn tool_name(&self) -> &str { - "shell_command" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { run_shell(ctx, &arguments).await }) - } -} - -pub struct ExecCommandHandler; - -impl ToolExecutor for ExecCommandHandler { - fn tool_name(&self) -> &str { - "exec_command" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { ctx.exec.exec_command(ctx, &arguments).await }) - } -} - -pub struct WriteStdinHandler; - -impl ToolExecutor for WriteStdinHandler { - fn tool_name(&self) -> &str { - "write_stdin" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - Box::pin(async move { ctx.exec.write_stdin(ctx, &arguments).await }) - } -} diff --git a/crates/pulsing-forge/src/handlers/shell_exec.rs b/crates/pulsing-forge/src/handlers/shell_exec.rs deleted file mode 100644 index 83b8f39ad..000000000 --- a/crates/pulsing-forge/src/handlers/shell_exec.rs +++ /dev/null @@ -1,204 +0,0 @@ -//! Shared subprocess execution for Codex shell tools and legacy `Bash`. - -use std::path::PathBuf; -use std::process::Stdio; -use std::time::Duration; - -use serde_json::Value; -use tokio::process::Command; -use tokio::time::timeout; - -use crate::approval::{ - args_dangerously_disable_sandbox, effective_sandbox_policy, ensure_shell_allowed, -}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::exec_output::{SHELL_MAX_BYTES, shell_timeout_ms}; -use crate::handlers::write::resolve_within_cwd; -use crate::patch::{MaybeApplyPatch, apply_parsed_patch, maybe_parse_apply_patch}; -use crate::process_group::{ProcessGroupGuard, configure}; -use crate::result::ToolResult; -use crate::sandbox::build_bash_exec; - -pub(crate) fn resolve_shell_workdir( - ctx: &ToolCallContext, - args: &Value, -) -> Result { - match args - .get("workdir") - .or_else(|| args.get("cwd")) - .and_then(|v| v.as_str()) - { - Some(w) => resolve_within_cwd(&ctx.cwd, w).map_err(ToolError::respond), - None => Ok(ctx.cwd.clone()), - } -} - -pub(crate) async fn run_shell( - ctx: &ToolCallContext, - args: &Value, -) -> Result { - let cmd = args - .get("cmd") - .or_else(|| args.get("command")) - .and_then(|v| v.as_str()) - .ok_or_else(|| ToolError::respond("missing cmd/command"))?; - let cwd = resolve_shell_workdir(ctx, args)?; - let login = args.get("login").and_then(|v| v.as_bool()).unwrap_or(false); - let timeout_ms = shell_timeout_ms(args); - if ctx.turn.as_ref().is_some_and(|turn| turn.is_cancelled()) { - return Ok(ToolResult::err("shell command cancelled before start")); - } - - ensure_shell_allowed(ctx, args, cmd)?; - let policy = effective_sandbox_policy(ctx, args); - let dangerous = args_dangerously_disable_sandbox(ctx, args); - - let plan = build_bash_exec(cmd, Some(&cwd), policy, dangerous, login); - - match maybe_parse_apply_patch(&plan.argv) { - MaybeApplyPatch::Body(patch_args) => { - return Ok(match apply_parsed_patch(&patch_args, &cwd) { - Ok(summary) => ToolResult::ok(summary), - Err(e) => ToolResult::err(e), - }); - } - MaybeApplyPatch::ImplicitInvocation => { - return Ok(ToolResult::err( - "patch detected without explicit apply_patch invocation; use apply_patch tool", - )); - } - MaybeApplyPatch::ShellParseError(e) => { - return Ok(ToolResult::err(format!("shell parse error: {e}"))); - } - MaybeApplyPatch::PatchParseError(e) => { - return Ok(ToolResult::err(e.to_string())); - } - MaybeApplyPatch::NotApplyPatch => {} - } - - let mut command = Command::new(&plan.argv[0]); - command.args(&plan.argv[1..]); - configure(&mut command); - command.kill_on_drop(true); - command - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .current_dir(&cwd); - if let Some(env) = &plan.env { - command.env_clear(); - for (k, v) in env { - command.env(k, v); - } - } - - let _turn_resource = ctx - .turn - .as_ref() - .map(|turn| turn.resources().register_passive("shell_command")); - let dur = Duration::from_millis(timeout_ms); - let child = match command.spawn() { - Ok(child) => child, - Err(err) => return Ok(ToolResult::err(err.to_string())), - }; - let mut process_group = ProcessGroupGuard::new(child.id()); - let output = child.wait_with_output(); - tokio::pin!(output); - let result = if let Some(turn) = &ctx.turn { - let cancellation = turn.cancellation(); - tokio::select! { - _ = cancellation.cancelled() => { - process_group.kill_now(); - let _ = timeout(Duration::from_secs(2), &mut output).await; - return Ok(ToolResult::err("shell command cancelled")); - } - result = timeout(dur, &mut output) => result, - } - } else { - timeout(dur, &mut output).await - }; - let out = match result { - Ok(Ok(o)) => o, - Ok(Err(e)) => return Ok(ToolResult::err(e.to_string())), - Err(_) => { - process_group.kill_now(); - let _ = timeout(Duration::from_secs(2), &mut output).await; - return Ok(ToolResult::err(format!("timed out after {timeout_ms}ms"))); - } - }; - process_group.disarm(); - let mut text = String::new(); - text.push_str(&String::from_utf8_lossy(&out.stdout)); - text.push_str(&String::from_utf8_lossy(&out.stderr)); - if text.len() > SHELL_MAX_BYTES { - text.truncate(SHELL_MAX_BYTES); - text.push_str("\n… truncated …"); - } - text.push_str(&format!( - "\nexit={}\n[{}]", - out.status.code().unwrap_or(-1), - plan.label - )); - if out.status.success() { - Ok(ToolResult::ok(text)) - } else { - Ok(ToolResult::err(text)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::approval::{ApprovalCache, ApprovalPolicy, new_exec_policy}; - use crate::context::{LocalToolSession, ToolCallContext}; - use crate::discovery::new_tool_catalog; - use crate::unified_exec::UnifiedExecManager; - use std::path::Path; - use std::sync::Arc; - - fn test_ctx(cwd: &Path) -> ToolCallContext { - ToolCallContext::new( - cwd, - "off", - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)), - Arc::new(UnifiedExecManager::new()), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - new_tool_catalog(), - ) - } - - #[test] - fn rejects_workdir_escape_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let ctx = test_ctx(dir.path()); - let err = - resolve_shell_workdir(&ctx, &serde_json::json!({"workdir": "../escape"})).unwrap_err(); - assert!(err.to_string().contains("outside working directory")); - } - - #[tokio::test] - async fn turn_cancellation_kills_the_shell_process_group() { - let dir = tempfile::tempdir().unwrap(); - let marker = dir.path().join("should-not-exist"); - let turn = Arc::new(crate::turn::TurnExecutionContext::new( - crate::SessionId::new(), - crate::TurnId::new(), - )); - let ctx = test_ctx(dir.path()).with_turn(turn.clone()); - let args = serde_json::json!({ - "cmd": "(sleep 0.3; touch should-not-exist) & wait", - "timeout_ms": 5_000 - }); - - let cancel = async { - tokio::time::sleep(Duration::from_millis(50)).await; - turn.cancel(); - }; - let (result, ()) = tokio::join!(run_shell(&ctx, &args), cancel); - assert!(result.unwrap().is_error); - assert!(turn.resources().wait_for_idle(Duration::from_secs(1)).await); - tokio::time::sleep(Duration::from_millis(400)).await; - assert!(!marker.exists(), "cancelled process tree produced a file"); - } -} diff --git a/crates/pulsing-forge/src/handlers/view_image.rs b/crates/pulsing-forge/src/handlers/view_image.rs deleted file mode 100644 index 044c5d1cb..000000000 --- a/crates/pulsing-forge/src/handlers/view_image.rs +++ /dev/null @@ -1,213 +0,0 @@ -use std::path::Path; - -use base64::Engine; -use image::imageops::FilterType; -use image::{GenericImageView, ImageFormat}; -use serde_json::Value; -use serde_json::json; - -use super::write::resolve_within_cwd; -use super::{err, json_str}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -const VIEW_IMAGE_CAP: usize = 8 * 1024 * 1024; -/// Matches `codex_utils_image::MAX_DIMENSION`: the longer side is capped at -/// this many pixels before the image is attached at "high" detail. -const HIGH_DETAIL_MAX_PX: u32 = 2048; - -pub struct ViewImageHandler; - -impl ToolExecutor for ViewImageHandler { - fn tool_name(&self) -> &str { - "view_image" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - let cwd = ctx.cwd.clone(); - Box::pin(async move { view_image_impl(&cwd, &arguments) }) - } -} - -fn view_image_impl(cwd: &Path, args: &Value) -> Result { - let path = json_str(args, "path")?; - let detail = args - .get("detail") - .and_then(|v| v.as_str()) - .unwrap_or("high"); - if !matches!(detail, "high" | "original") { - return err(format!( - "view_image.detail only supports `high` or `original`; omit `detail` for default \ - high resized behavior, got `{detail}`" - )); - } - - let abs = resolve_within_cwd(cwd, path).map_err(ToolError::respond)?; - if !abs.is_file() { - return err(format!("image path `{}` is not a file", abs.display())); - } - - let raw = std::fs::read(&abs).map_err(|e| { - ToolError::respond(format!("unable to read image at `{}`: {e}", abs.display())) - })?; - if raw.len() > VIEW_IMAGE_CAP { - return err(format!( - "Image too large for view_image: {} bytes exceeds the {} byte cap.", - raw.len(), - VIEW_IMAGE_CAP - )); - } - - let (bytes, mime) = encode_for_prompt(&raw, detail)?; - let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes); - let data_url = format!("data:{mime};base64,{b64}"); - - let structured = json!({ - "content_items": [{ - "type": "input_image", - "image_url": data_url, - "detail": detail, - }], - "path": abs.to_string_lossy(), - "bytes": bytes.len(), - }); - - Ok(crate::result::ToolResult { - content: format!( - "Attached image {} (detail={detail}, {} bytes)", - abs.display(), - bytes.len() - ), - is_error: false, - structured: Some(structured), - }) -} - -/// Determines the MIME type from the file's magic bytes rather than its -/// extension, so a mislabeled extension (e.g. a JPEG named `foo.png`) can't -/// smuggle in a mismatched `data:` MIME type. Mirrors how Codex's -/// `codex_utils_image::load_for_prompt_bytes` sniffs the format via -/// `image::guess_format` before trusting any file metadata. -fn sniff_format(raw: &[u8]) -> Result { - image::guess_format(raw) - .map_err(|_| ToolError::respond("not a recognized image format (png/jpeg/gif/webp)")) -} - -fn format_to_mime(format: ImageFormat) -> Result<&'static str, ToolError> { - match format { - ImageFormat::Png => Ok("image/png"), - ImageFormat::Jpeg => Ok("image/jpeg"), - ImageFormat::Gif => Ok("image/gif"), - ImageFormat::WebP => Ok("image/webp"), - other => Err(ToolError::respond(format!( - "unsupported image format: {other:?}" - ))), - } -} - -fn encode_for_prompt(raw: &[u8], detail: &str) -> Result<(Vec, String), ToolError> { - let format = sniff_format(raw)?; - let mime = format_to_mime(format)?; - - if detail == "original" { - return Ok((raw.to_vec(), mime.to_string())); - } - - let img = image::load_from_memory_with_format(raw, format) - .map_err(|e| ToolError::respond(e.to_string()))?; - let (w, h) = img.dimensions(); - if w.max(h) <= HIGH_DETAIL_MAX_PX { - return Ok((raw.to_vec(), mime.to_string())); - } - - let resized = img.resize(HIGH_DETAIL_MAX_PX, HIGH_DETAIL_MAX_PX, FilterType::Triangle); - let mut buf = Vec::new(); - resized - .write_to(&mut std::io::Cursor::new(&mut buf), format) - .map_err(|e| ToolError::respond(e.to_string()))?; - Ok((buf, mime.to_string())) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - use std::path::Path; - - // Valid 1x1 RGBA PNG (CRC-checked). - const TINY_PNG: &[u8] = &[ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, - 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, - 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, - 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, - 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, - ]; - - fn write_tiny_png(path: &Path) { - std::fs::write(path, TINY_PNG).expect("write png"); - } - - fn run(cwd: &Path, args: Value) -> crate::result::ToolResult { - match view_image_impl(cwd, &args) { - Ok(r) => r, - Err(e) => crate::result::ToolResult::err(e.to_string()), - } - } - - #[test] - fn attaches_png_with_structured_output() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("x.png"); - write_tiny_png(&path); - let out = run(dir.path(), json!({"path": "x.png", "detail": "high"})); - assert!(!out.is_error, "view_image failed: {}", out.content); - let structured = out.structured.expect("structured"); - let items = structured["content_items"].as_array().expect("items"); - let url = items[0]["image_url"].as_str().expect("url"); - assert!(url.starts_with("data:image/png;base64,")); - } - - #[test] - fn rejects_relative_escape_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let outside = dir.path().parent().unwrap().join("escape.png"); - write_tiny_png(&outside); - let out = run(dir.path(), json!({"path": "../escape.png"})); - assert!(out.is_error); - assert!(out.content.contains("outside working directory")); - } - - #[test] - fn rejects_absolute_path_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let outside = tempfile::tempdir().unwrap(); - let path = outside.path().join("outside.png"); - write_tiny_png(&path); - let out = run(dir.path(), json!({"path": path.to_str().expect("utf8")})); - assert!(out.is_error); - assert!(out.content.contains("outside working directory")); - } - - #[test] - fn rejects_invalid_detail() { - let dir = tempfile::tempdir().unwrap(); - write_tiny_png(&dir.path().join("x.png")); - let out = run(dir.path(), json!({"path": "x.png", "detail": "low"})); - assert!(out.is_error); - assert!(out.content.contains("view_image.detail only supports")); - } - - #[test] - fn rejects_unrecognized_format() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("x.bin"), b"not an image").unwrap(); - let out = run(dir.path(), json!({"path": "x.bin"})); - assert!(out.is_error); - assert!(out.content.contains("not a recognized image format")); - } -} diff --git a/crates/pulsing-forge/src/handlers/write.rs b/crates/pulsing-forge/src/handlers/write.rs deleted file mode 100644 index 05ea015c9..000000000 --- a/crates/pulsing-forge/src/handlers/write.rs +++ /dev/null @@ -1,264 +0,0 @@ -use std::path::{Component, Path, PathBuf}; - -use serde_json::Value; - -use super::{json_str, ok}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::executor::{ToolExecutor, ToolExecutorFuture}; - -pub struct WriteHandler; - -impl ToolExecutor for WriteHandler { - fn tool_name(&self) -> &str { - "Write" - } - - fn spec(&self) -> crate::registry::ToolSpec { - super::builtin_spec(self.tool_name()) - } - - fn handle<'a>(&'a self, ctx: &'a ToolCallContext, arguments: Value) -> ToolExecutorFuture<'a> { - let cwd = ctx.cwd.clone(); - Box::pin(async move { write_impl(&cwd, &arguments) }) - } -} - -fn write_impl(cwd: &Path, args: &Value) -> Result { - let path = json_str(args, "file_path")?; - let content = json_str(args, "content")?; - let target = resolve_within_cwd(cwd, path).map_err(ToolError::respond)?; - - let existed = target.exists(); - if let Some(parent) = target.parent() { - std::fs::create_dir_all(parent).map_err(|e| { - ToolError::respond(format!( - "failed to create parent directory {}: {e}", - parent.display() - )) - })?; - } - atomic_write(&target, content) - .map_err(|e| ToolError::respond(format!("failed to write {}: {e}", target.display())))?; - ok(if existed { "overwritten" } else { "created" }) -} - -/// Resolve `path` against `cwd` and reject any target that would land outside -/// of it. Unlike `apply_patch`/`Bash`, `Write` runs with no OS-level sandbox, -/// so this is the only boundary check standing between the model and the rest -/// of the filesystem. -pub(crate) fn resolve_within_cwd(cwd: &Path, path: &str) -> Result { - let joined = if Path::new(path).is_absolute() { - Path::new(path).to_path_buf() - } else { - cwd.join(path) - }; - let target = normalize_lexically(&joined); - let root = normalize_lexically(cwd); - if !target.starts_with(&root) { - return Err(format!( - "refusing to write outside working directory: {} (cwd: {})", - target.display(), - root.display() - )); - } - reject_symlink_escape(cwd, &target)?; - Ok(target) -} - -/// Follow symlinks on the longest existing prefix of `target` and reject if the -/// resolved location escapes `cwd`. Lexical `..` checks alone are not enough: a -/// symlink inside the workspace can still redirect writes to the rest of the -/// filesystem. -fn reject_symlink_escape(cwd: &Path, target: &Path) -> Result<(), String> { - let cwd_canon = cwd - .canonicalize() - .map_err(|e| format!("invalid working directory {}: {e}", cwd.display()))?; - let mut probe = target.to_path_buf(); - loop { - if probe.exists() { - let canon = probe - .canonicalize() - .map_err(|e| format!("cannot resolve {}: {e}", probe.display()))?; - if !canon.starts_with(&cwd_canon) { - return Err(format!( - "refusing to write outside working directory: {} (cwd: {})", - target.display(), - cwd.display() - )); - } - return Ok(()); - } - match probe.parent() { - Some(parent) if !parent.as_os_str().is_empty() => probe = parent.to_path_buf(), - _ => return Ok(()), - } - } -} - -/// Reject paths whose canonical location escapes `cwd` (e.g. symlinks to outside). -/// Call only after confirming `target` exists. -pub(crate) fn assert_canonical_within_cwd(cwd: &Path, target: &Path) -> Result<(), String> { - let root = cwd - .canonicalize() - .map_err(|e| format!("failed to resolve working directory: {e}"))?; - let canon = target - .canonicalize() - .map_err(|e| format!("failed to resolve {}: {e}", target.display()))?; - if canon.starts_with(&root) { - Ok(()) - } else { - Err(format!( - "refusing to write outside working directory: {} (cwd: {})", - canon.display(), - root.display() - )) - } -} - -/// Collapse `.`/`..` components without touching the filesystem, since the -/// write target may not exist yet. Mirrors the common `path-clean` behavior: -/// a leading `..` beyond the root is kept as-is rather than panicking. -fn normalize_lexically(path: &Path) -> PathBuf { - let mut out = PathBuf::new(); - for component in path.components() { - match component { - Component::CurDir => {} - Component::ParentDir => match out.components().next_back() { - Some(Component::Normal(_)) => { - out.pop(); - } - _ => out.push(component), - }, - other => out.push(other), - } - } - out -} - -/// Write via a sibling temp file + rename so a mid-write failure (disk full, -/// process kill) never leaves `target` truncated or half-written. -fn atomic_write(target: &Path, content: &str) -> std::io::Result<()> { - let parent = target - .parent() - .filter(|p| !p.as_os_str().is_empty()) - .unwrap_or_else(|| Path::new(".")); - let file_name = target - .file_name() - .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "missing file name"))? - .to_string_lossy(); - let tmp_path = parent.join(format!(".{file_name}.{}.tmp", uuid::Uuid::new_v4())); - - let write_result = std::fs::write(&tmp_path, content); - if write_result.is_err() { - let _ = std::fs::remove_file(&tmp_path); - return write_result; - } - std::fs::rename(&tmp_path, target).inspect_err(|_| { - let _ = std::fs::remove_file(&tmp_path); - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn call( - cwd: &Path, - file_path: &str, - content: &str, - ) -> Result { - write_impl( - cwd, - &serde_json::json!({"file_path": file_path, "content": content}), - ) - } - - #[test] - fn creates_new_file() { - let dir = tempfile::tempdir().unwrap(); - let out = call(dir.path(), "out.txt", "hello").unwrap(); - assert!(!out.is_error); - assert_eq!(out.content, "created"); - assert_eq!( - std::fs::read_to_string(dir.path().join("out.txt")).unwrap(), - "hello" - ); - } - - #[test] - fn overwrites_existing_file() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("out.txt"), "old").unwrap(); - let out = call(dir.path(), "out.txt", "new").unwrap(); - assert!(!out.is_error); - assert_eq!(out.content, "overwritten"); - assert_eq!( - std::fs::read_to_string(dir.path().join("out.txt")).unwrap(), - "new" - ); - } - - #[test] - fn creates_deep_parent_dirs_inside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let out = call(dir.path(), "a/b/c/out.txt", "deep").unwrap(); - assert!(!out.is_error); - assert_eq!( - std::fs::read_to_string(dir.path().join("a/b/c/out.txt")).unwrap(), - "deep" - ); - } - - #[test] - fn rejects_relative_escape_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let err = call(dir.path(), "../escape.txt", "x").unwrap_err(); - assert!( - matches!(err, ToolError::RespondToModel(msg) if msg.contains("outside working directory")) - ); - assert!(!dir.path().parent().unwrap().join("escape.txt").exists()); - } - - #[test] - fn rejects_absolute_path_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let err = call( - dir.path(), - "/etc/pulsing-forge-write-test-should-not-exist", - "x", - ) - .unwrap_err(); - assert!( - matches!(err, ToolError::RespondToModel(msg) if msg.contains("outside working directory")) - ); - } - - #[test] - fn allows_absolute_path_inside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let abs = dir.path().join("inside.txt"); - let out = call(dir.path(), abs.to_str().unwrap(), "ok").unwrap(); - assert!(!out.is_error); - assert_eq!(std::fs::read_to_string(&abs).unwrap(), "ok"); - } - - #[test] - fn rejects_symlink_escape_outside_cwd() { - let dir = tempfile::tempdir().unwrap(); - let outside = dir.path().join("outside"); - std::fs::create_dir_all(&outside).unwrap(); - let workspace = dir.path().join("workspace"); - std::fs::create_dir_all(&workspace).unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::symlink; - symlink(&outside, workspace.join("link")).unwrap(); - let err = call(&workspace, "link/escape.txt", "x").unwrap_err(); - assert!( - matches!(err, ToolError::RespondToModel(msg) if msg.contains("outside working directory")) - ); - assert!(!outside.join("escape.txt").exists()); - } - } -} diff --git a/crates/pulsing-forge/src/lib.rs b/crates/pulsing-forge/src/lib.rs deleted file mode 100644 index b79e5c92a..000000000 --- a/crates/pulsing-forge/src/lib.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! **Pulsing Forge** — agent tool & environment runtime for the Pulsing ecosystem. -//! -//! Sandboxed shell, filesystem, and session tools. Handlers under [`handlers`]; -//! host callbacks under [`context`]. - -pub mod agent; -pub mod approval; -pub mod cli; -pub mod context; -pub mod discovery; -pub mod error; -pub mod exec_output; -pub mod execpolicy; -pub mod executor; -pub mod handlers; -pub mod llm; -pub mod mcp; -pub mod patch; -mod process_group; -pub mod protocol; -pub mod pty_session; -pub mod registry; -pub mod result; -pub mod runtime; -pub mod sandbox; -pub mod session; -pub mod session_input; -pub mod turn; -pub mod unified_exec; - -pub use context::{ - LocalToolSession, NullToolSession, PlanItem, StepStatus, ToolCallContext, ToolSession, - UpdatePlanArgs, -}; - -pub use agent::{ - AgentCancelled, AgentConfig, AgentEvent, AgentEventHandler, AgentEventTx, DEFAULT_TOOL_NAMES, - INIT_TOOL_NAMES, InteractiveConfig, default_model_for_provider, default_provider, - run_agent_turn, run_agent_turn_observed, run_init_guide, run_interactive, run_oneshot, -}; -pub use error::ToolError; -pub use executor::{ToolExecutor, ToolExposure}; -pub use llm::{LlmClient, LlmError, LlmMessage, LlmStream, LlmUsage, Provider, StreamRequest}; -pub use protocol::{ - CandidateId, CommandId, CommandReceipt, EventId, ForgeEvent, ForgeEventKind, - ForgeProtocolError, ProtocolVersion, SessionId, SessionSpec, TurnId, -}; -pub use registry::{ToolName, ToolRegistry, ToolRegistryError, ToolSpec}; -pub use result::ToolResult; -pub use runtime::ToolRuntime; -pub use session::{ - EventSubscription, ForgeService, InMemoryEventStore, LocalForgeClient, SessionSnapshot, -}; -pub use turn::{TurnExecutionContext, TurnResourceGuard, TurnResourceRegistry}; diff --git a/crates/pulsing-forge/src/llm/anthropic.rs b/crates/pulsing-forge/src/llm/anthropic.rs deleted file mode 100644 index d21b5785f..000000000 --- a/crates/pulsing-forge/src/llm/anthropic.rs +++ /dev/null @@ -1,177 +0,0 @@ -use std::collections::BTreeMap; - -use futures_util::StreamExt; -use reqwest::Client; -use reqwest_eventsource::{Event as SseEvent, EventSource}; -use serde_json::{Value, json}; - -use super::error::LlmError; -use super::message::build_anthropic_request; -use super::types::{LlmMessage, LlmUsage, StreamRequest}; - -pub struct AnthropicStream { - text_chunks: Vec, - final_message: LlmMessage, -} - -impl AnthropicStream { - pub async fn start( - client: &Client, - api_key: &str, - base_url: &str, - req: &StreamRequest, - ) -> Result { - let url = format!("{}/messages", base_url.trim_end_matches('/')); - let body = build_anthropic_request(req, true); - - let request = client - .post(url) - .header("x-api-key", api_key) - .header("anthropic-version", "2023-06-01") - .header("Content-Type", "application/json") - .header("Accept", "text/event-stream") - .json(&body); - - let mut es = EventSource::new(request).map_err(|e| LlmError::Stream(e.to_string()))?; - let mut text_parts = String::new(); - let mut text_chunks = Vec::new(); - let mut tool_blocks: BTreeMap = BTreeMap::new(); - let mut usage: Option = None; - let mut stop_reason: Option = None; - - while let Some(event) = es.next().await { - match event { - Ok(SseEvent::Open) => {} - Ok(SseEvent::Message(message)) => { - let data: Value = serde_json::from_str(message.data.trim())?; - let event_type = data.get("type").and_then(|v| v.as_str()).unwrap_or(""); - match event_type { - "content_block_start" => { - let index = - data.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as usize; - let block = data - .get("content_block") - .cloned() - .unwrap_or_else(|| json!({})); - if block.get("type").and_then(|v| v.as_str()) == Some("tool_use") { - let id = block - .get("id") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - let name = block - .get("name") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - tool_blocks.insert(index, (id, name, String::new())); - } - } - "content_block_delta" => { - let index = - data.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as usize; - let delta = data.get("delta").cloned().unwrap_or_else(|| json!({})); - let delta_type = - delta.get("type").and_then(|v| v.as_str()).unwrap_or(""); - match delta_type { - "text_delta" => { - if let Some(text) = delta.get("text").and_then(|v| v.as_str()) { - text_parts.push_str(text); - text_chunks.push(text.to_string()); - } - } - "input_json_delta" => { - if let Some(entry) = tool_blocks.get_mut(&index) - && let Some(partial) = - delta.get("partial_json").and_then(|v| v.as_str()) - { - entry.2.push_str(partial); - } - } - _ => {} - } - } - "message_delta" => { - if let Some(delta) = data.get("delta") { - if let Some(reason) = - delta.get("stop_reason").and_then(|v| v.as_str()) - { - stop_reason = Some(reason.to_string()); - } - if let Some(u) = delta.get("usage") { - usage = Some(LlmUsage { - input_tokens: usage - .as_ref() - .map(|x| x.input_tokens) - .unwrap_or(0) - .max( - u.get("input_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(0), - ), - output_tokens: u - .get("output_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(0), - }); - } - } - } - "message_start" => { - if let Some(u) = data.get("message").and_then(|m| m.get("usage")) { - usage = Some(LlmUsage { - input_tokens: u - .get("input_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(0), - output_tokens: u - .get("output_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(0), - }); - } - } - _ => {} - } - } - Err(e) => return Err(LlmError::Stream(e.to_string())), - } - } - - let mut content = Vec::new(); - if !text_parts.is_empty() { - content.push(json!({ "type": "text", "text": text_parts })); - } - for (_idx, (id, name, args)) in tool_blocks { - let parsed: Value = serde_json::from_str(args.trim()).unwrap_or_else(|_| json!({})); - let input = if parsed.is_object() { - parsed - } else { - json!({}) - }; - content.push(json!({ - "type": "tool_use", - "id": id, - "name": name, - "input": input, - })); - } - - Ok(Self { - text_chunks, - final_message: LlmMessage { - content, - usage, - stop_reason, - }, - }) - } - - pub fn text_chunks(&self) -> &[String] { - &self.text_chunks - } - - pub fn final_message(&self) -> LlmMessage { - self.final_message.clone() - } -} diff --git a/crates/pulsing-forge/src/llm/client.rs b/crates/pulsing-forge/src/llm/client.rs deleted file mode 100644 index 5783f3bdb..000000000 --- a/crates/pulsing-forge/src/llm/client.rs +++ /dev/null @@ -1,143 +0,0 @@ -use reqwest::Client; - -use super::anthropic::AnthropicStream; -use super::demo::DemoStream; -use super::error::LlmError; -use super::openai::OpenAiStream; -use super::types::{LlmMessage, Provider, StreamRequest}; - -#[derive(Debug, Clone)] -pub struct LlmClientConfig { - pub provider: Provider, - pub api_key: Option, - pub base_url: Option, -} - -#[derive(Clone)] -pub struct LlmClient { - config: LlmClientConfig, - http: Client, -} - -pub enum LlmStream { - Demo(DemoStream), - OpenAi(OpenAiStream), - Anthropic(AnthropicStream), -} - -impl LlmStream { - pub fn text_chunks(&self) -> Vec { - match self { - Self::Demo(s) => s.text_chunks(), - Self::OpenAi(s) => s.text_chunks().to_vec(), - Self::Anthropic(s) => s.text_chunks().to_vec(), - } - } - - pub fn final_message(&self) -> LlmMessage { - match self { - Self::Demo(s) => s.final_message(), - Self::OpenAi(s) => s.final_message(), - Self::Anthropic(s) => s.final_message(), - } - } -} - -impl LlmClient { - pub fn new( - provider: &str, - api_key: Option, - base_url: Option, - ) -> Result { - let provider = Provider::parse(provider) - .ok_or_else(|| LlmError::UnsupportedProvider(provider.to_string()))?; - let http = Client::builder() - .connect_timeout(std::time::Duration::from_secs(30)) - .timeout(std::time::Duration::from_secs(600)) - .build()?; - Ok(Self { - config: LlmClientConfig { - provider, - api_key, - base_url, - }, - http, - }) - } - - pub fn provider(&self) -> Provider { - self.config.provider - } - - pub async fn stream_messages(&self, req: StreamRequest) -> Result { - match self.config.provider { - Provider::Demo => Ok(LlmStream::Demo(DemoStream::new(&req.messages, &req.tools))), - Provider::Openai => { - let api_key = self.resolve_api_key("OPENAI_API_KEY")?; - let base = self - .config - .base_url - .clone() - .unwrap_or_else(|| "https://api.openai.com/v1".to_string()); - let stream = OpenAiStream::start(&self.http, &api_key, &base, &req).await?; - Ok(LlmStream::OpenAi(stream)) - } - Provider::Anthropic => { - let api_key = self.resolve_api_key("ANTHROPIC_API_KEY")?; - let base = self - .config - .base_url - .clone() - .unwrap_or_else(|| "https://api.anthropic.com/v1".to_string()); - let stream = AnthropicStream::start(&self.http, &api_key, &base, &req).await?; - Ok(LlmStream::Anthropic(stream)) - } - } - } - - fn resolve_api_key(&self, env_name: &str) -> Result { - if let Some(key) = self.config.api_key.as_deref().filter(|k| !k.is_empty()) { - return Ok(key.to_string()); - } - if let Ok(key) = std::env::var(env_name) - && !key.is_empty() - { - return Ok(key); - } - Err(LlmError::MissingApiKey( - self.config.provider.as_str().into(), - )) - } - - pub fn classify_error(err: &LlmError) -> (bool, bool, bool) { - ( - err.is_authentication_error(), - err.is_retryable_error(), - err.is_api_error(), - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[tokio::test] - async fn demo_stream_glob_reply() { - let client = LlmClient::new("demo", None, None).expect("demo client"); - let req = StreamRequest { - model: "demo".into(), - max_tokens: 1024, - messages: vec![json!({ "role": "user", "content": "list files with Glob" })], - system: None, - tools: vec![json!({ "name": "Glob", "input_schema": {} })], - }; - let stream = client.stream_messages(req).await.expect("stream"); - let msg = stream.final_message(); - assert_eq!( - msg.content[0].get("type").and_then(|v| v.as_str()), - Some("tool_use") - ); - } -} diff --git a/crates/pulsing-forge/src/llm/demo.rs b/crates/pulsing-forge/src/llm/demo.rs deleted file mode 100644 index d82da7da1..000000000 --- a/crates/pulsing-forge/src/llm/demo.rs +++ /dev/null @@ -1,216 +0,0 @@ -use regex::Regex; -use serde_json::{Value, json}; -use uuid::Uuid; - -use super::types::{LlmMessage, LlmUsage}; - -const DEMO_PEERS: &[&str] = &["bard", "smith", "sage", "guide"]; - -fn is_tool_result_user_message(msg: &Value) -> bool { - let Some(content) = msg.get("content").and_then(|v| v.as_array()) else { - return false; - }; - !content.is_empty() - && content - .iter() - .all(|b| b.get("type").and_then(|v| v.as_str()) == Some("tool_result")) -} - -fn last_user_text(messages: &[Value]) -> String { - for msg in messages.iter().rev() { - if msg.get("role").and_then(|v| v.as_str()) != Some("user") { - continue; - } - let content = msg.get("content").cloned().unwrap_or(Value::Null); - if let Some(s) = content.as_str() { - return s.trim().to_string(); - } - if let Some(arr) = content.as_array() { - if is_tool_result_user_message(msg) { - continue; - } - let parts: Vec = arr - .iter() - .filter_map(|b| { - if b.get("type").and_then(|v| v.as_str()) == Some("text") { - b.get("text").and_then(|v| v.as_str()).map(str::to_string) - } else { - None - } - }) - .collect(); - return parts.join(" ").trim().to_string(); - } - } - String::new() -} - -fn tool_names(tools: &[Value]) -> Vec { - tools - .iter() - .filter_map(|t| t.get("name").and_then(|v| v.as_str()).map(str::to_string)) - .collect() -} - -enum DemoPlan { - Text(String), - Tool { name: String, input: Value }, -} - -fn plan_demo_turn(messages: &[Value], tools: &[Value]) -> DemoPlan { - if messages.last().is_some_and(is_tool_result_user_message) { - let original = last_user_text(messages); - let snippet = Regex::new(r"\s+") - .unwrap() - .replace_all(original.trim(), " ") - .chars() - .take(100) - .collect::(); - return DemoPlan::Text(format!( - "(demo) Finished tool run for: {}.", - if snippet.is_empty() { - "your request".to_string() - } else { - snippet - } - )); - } - - let text = last_user_text(messages); - let lower = text.to_lowercase(); - let allowed = tool_names(tools); - - let has = |keys: &[&str]| keys.iter().any(|k| lower.contains(k)); - - if has(&["glob", "files", "list project", "directory"]) && allowed.iter().any(|n| n == "Glob") { - return DemoPlan::Tool { - name: "Glob".into(), - input: json!({ "pattern": "*", "path": "." }), - }; - } - if (has(&["create", "write", "scaffold", "bootstrap", "init"]) || lower.contains("readme.md")) - && allowed.iter().any(|n| n == "Write") - { - return DemoPlan::Tool { - name: "Write".into(), - input: json!({ - "file_path": "README.md", - "content": "# Project\n\n(demo) Workspace initialized by Pulsing init guide.\n", - }), - }; - } - if has(&["read", "readme", "summary"]) && allowed.iter().any(|n| n == "Read") { - return DemoPlan::Tool { - name: "Read".into(), - input: json!({ "file_path": "README.md" }), - }; - } - if has(&["quest", "puzzle", "unit-test", "questreport"]) - && allowed.iter().any(|n| n == "QuestReport") - { - return DemoPlan::Tool { - name: "QuestReport".into(), - input: json!({ - "quest_id": "unit-tests", - "status": "in_progress", - "note": "demo chatter", - }), - }; - } - if (lower.contains("messageclusteragent") - || lower.contains("coordinate") - || lower.contains("peer")) - && allowed.iter().any(|n| n == "MessageClusterAgent") - { - let target = DEMO_PEERS - .iter() - .find(|p| lower.contains(**p)) - .unwrap_or(&"smith"); - return DemoPlan::Tool { - name: "MessageClusterAgent".into(), - input: json!({ - "agent": target, - "message": "Demo ping — reply in one short sentence.", - "wait": false, - }), - }; - } - - let snippet = Regex::new(r"\s+") - .unwrap() - .replace_all(text.trim(), " ") - .chars() - .take(100) - .collect::(); - DemoPlan::Text(format!( - "(demo) Noted: {}", - if snippet.is_empty() { - "(empty)".to_string() - } else { - snippet - } - )) -} - -pub struct DemoStream { - plan: DemoPlan, - text: String, -} - -impl DemoStream { - pub fn new(messages: &[Value], tools: &[Value]) -> Self { - let plan = plan_demo_turn(messages, tools); - let text = match &plan { - DemoPlan::Text(t) => t.clone(), - DemoPlan::Tool { .. } => String::new(), - }; - Self { plan, text } - } - - pub fn text_chunks(&self) -> Vec { - if self.text.is_empty() { - vec![] - } else { - vec![self.text.clone()] - } - } - - pub fn final_message(&self) -> LlmMessage { - match &self.plan { - DemoPlan::Tool { name, input } => LlmMessage { - content: vec![json!({ - "type": "tool_use", - "id": format!("demo-{}", &Uuid::new_v4().simple().to_string()[..12]), - "name": name, - "input": input, - })], - usage: Some(LlmUsage { - input_tokens: 1, - output_tokens: 1, - }), - stop_reason: Some("tool_use".into()), - }, - DemoPlan::Text(text) => LlmMessage { - content: vec![json!({ "type": "text", "text": text })], - usage: Some(LlmUsage { - input_tokens: 1, - output_tokens: (text.len().max(1) / 4) as u64, - }), - stop_reason: Some("end_turn".into()), - }, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn glob_intent_triggers_tool() { - let messages = vec![json!({ "role": "user", "content": "list project files" })]; - let tools = vec![json!({ "name": "Glob", "input_schema": {} })]; - let stream = DemoStream::new(&messages, &tools); - assert!(matches!(stream.plan, DemoPlan::Tool { .. })); - } -} diff --git a/crates/pulsing-forge/src/llm/error.rs b/crates/pulsing-forge/src/llm/error.rs deleted file mode 100644 index 6d6a32b8c..000000000 --- a/crates/pulsing-forge/src/llm/error.rs +++ /dev/null @@ -1,50 +0,0 @@ -use thiserror::Error; - -#[derive(Debug, Error)] -pub enum LlmError { - #[error("unsupported provider: {0}")] - UnsupportedProvider(String), - - #[error("missing API key for provider {0}")] - MissingApiKey(String), - - #[error("http error: {0}")] - Http(#[from] reqwest::Error), - - #[error("api error ({status}): {body}")] - Api { status: u16, body: String }, - - #[error("stream error: {0}")] - Stream(String), - - #[error("json error: {0}")] - Json(#[from] serde_json::Error), - - #[error("{0}")] - Other(String), -} - -impl LlmError { - pub fn is_authentication_error(&self) -> bool { - matches!( - self, - Self::Api { - status: 401 | 403, - .. - } - ) - } - - pub fn is_retryable_error(&self) -> bool { - match self { - Self::Http(e) => e.is_timeout() || e.is_connect() || e.is_request(), - Self::Api { status, .. } => matches!(status, 408 | 429 | 500..=599), - Self::Stream(_) => true, - _ => false, - } - } - - pub fn is_api_error(&self) -> bool { - matches!(self, Self::Api { .. }) - } -} diff --git a/crates/pulsing-forge/src/llm/message.rs b/crates/pulsing-forge/src/llm/message.rs deleted file mode 100644 index ec14c1e71..000000000 --- a/crates/pulsing-forge/src/llm/message.rs +++ /dev/null @@ -1,211 +0,0 @@ -use serde_json::{Value, json}; - -pub fn tool_schema_to_openai(tool: &Value) -> Value { - json!({ - "type": "function", - "function": { - "name": tool.get("name").and_then(|v| v.as_str()).unwrap_or(""), - "description": tool.get("description").and_then(|v| v.as_str()).unwrap_or(""), - "parameters": tool.get("input_schema").cloned().unwrap_or_else(|| json!({})), - } - }) -} - -fn tool_result_to_text(content: &Value) -> String { - if let Some(s) = content.as_str() { - return s.to_string(); - } - if content.is_null() { - return String::new(); - } - serde_json::to_string(content).unwrap_or_default() -} - -fn is_tool_result_user_message(content: &[Value]) -> bool { - !content.is_empty() - && content - .iter() - .all(|b| b.get("type").and_then(|v| v.as_str()) == Some("tool_result")) -} - -fn user_content_blocks_to_openai(content: &[Value]) -> Vec { - let mut parts = Vec::new(); - for block in content { - let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or(""); - match block_type { - "text" => { - parts.push(json!({ - "type": "text", - "text": block.get("text").and_then(|v| v.as_str()).unwrap_or(""), - })); - } - "image" => { - let source = block.get("source").cloned().unwrap_or_else(|| json!({})); - let media_type = source - .get("media_type") - .and_then(|v| v.as_str()) - .unwrap_or("image/png"); - let data = source.get("data").and_then(|v| v.as_str()).unwrap_or(""); - parts.push(json!({ - "type": "image_url", - "image_url": { "url": format!("data:{media_type};base64,{data}") }, - })); - } - _ => {} - } - } - if parts.is_empty() { - parts.push(json!({ "type": "text", "text": "" })); - } - parts -} - -pub fn to_openai_messages(system: Option<&str>, messages: &[Value]) -> Vec { - let mut out = Vec::new(); - if let Some(sys) = system.filter(|s| !s.is_empty()) { - out.push(json!({ "role": "system", "content": sys })); - } - - for message in messages { - let role = message - .get("role") - .and_then(|v| v.as_str()) - .unwrap_or("user"); - let content = message.get("content").cloned().unwrap_or(Value::Null); - - if role == "user" - && let Some(arr) = content.as_array() - { - if is_tool_result_user_message(arr) { - for block in arr { - out.push(json!({ - "role": "tool", - "tool_call_id": block.get("tool_use_id").and_then(|v| v.as_str()).unwrap_or(""), - "content": tool_result_to_text(block.get("content").unwrap_or(&Value::Null)), - })); - } - continue; - } - out.push(json!({ - "role": "user", - "content": user_content_blocks_to_openai(arr), - })); - continue; - } - - if role == "assistant" - && let Some(arr) = content.as_array() - { - let mut text_parts = Vec::new(); - let mut tool_calls = Vec::new(); - for block in arr { - let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or(""); - match block_type { - "text" => { - text_parts.push( - block - .get("text") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(), - ); - } - "tool_use" => { - let input = block.get("input").cloned().unwrap_or_else(|| json!({})); - tool_calls.push(json!({ - "id": block.get("id").and_then(|v| v.as_str()).unwrap_or(""), - "type": "function", - "function": { - "name": block.get("name").and_then(|v| v.as_str()).unwrap_or(""), - "arguments": serde_json::to_string(&input).unwrap_or_else(|_| "{}".into()), - } - })); - } - _ => {} - } - } - let text = text_parts.concat(); - let mut assistant = json!({ - "role": "assistant", - "content": if text.is_empty() { Value::Null } else { json!(text) }, - }); - if !tool_calls.is_empty() { - assistant - .as_object_mut() - .expect("assistant object") - .insert("tool_calls".into(), Value::Array(tool_calls)); - } - out.push(assistant); - continue; - } - - out.push(json!({ "role": role, "content": content })); - } - - out -} - -pub fn build_openai_request(req: &super::types::StreamRequest, stream: bool) -> Value { - let mut body = json!({ - "model": req.model, - "messages": to_openai_messages(req.system.as_deref(), &req.messages), - "max_tokens": req.max_tokens, - "stream": stream, - }); - if !req.tools.is_empty() { - let tools: Vec = req.tools.iter().map(tool_schema_to_openai).collect(); - body.as_object_mut() - .expect("body object") - .insert("tools".into(), Value::Array(tools)); - } - body -} - -pub fn normalize_openai_stop_reason(reason: Option<&str>) -> Option { - reason.map(|r| match r { - "stop" => "end_turn".to_string(), - "length" => "max_tokens".to_string(), - "tool_calls" => "tool_use".to_string(), - other => other.to_string(), - }) -} - -pub fn build_anthropic_request(req: &super::types::StreamRequest, stream: bool) -> Value { - let mut body = json!({ - "model": req.model, - "max_tokens": req.max_tokens, - "messages": req.messages, - "stream": stream, - }); - if let Some(sys) = req.system.as_deref().filter(|s| !s.is_empty()) { - body.as_object_mut() - .expect("body object") - .insert("system".into(), json!(sys)); - } - if !req.tools.is_empty() { - body.as_object_mut() - .expect("body object") - .insert("tools".into(), Value::Array(req.tools.clone())); - } - body -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn openai_tool_result_roundtrip_shape() { - let messages = vec![json!({ - "role": "user", - "content": [{ - "type": "tool_result", - "tool_use_id": "t1", - "content": "ok", - }], - })]; - let out = to_openai_messages(None, &messages); - assert_eq!(out[0]["role"], "tool"); - assert_eq!(out[0]["tool_call_id"], "t1"); - } -} diff --git a/crates/pulsing-forge/src/llm/mod.rs b/crates/pulsing-forge/src/llm/mod.rs deleted file mode 100644 index ca2b4a0ce..000000000 --- a/crates/pulsing-forge/src/llm/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -mod anthropic; -mod client; -mod demo; -mod error; -mod message; -mod openai; -mod types; - -pub use client::{LlmClient, LlmClientConfig, LlmStream}; -pub use error::LlmError; -pub use types::{LlmMessage, LlmUsage, Provider, StreamRequest}; diff --git a/crates/pulsing-forge/src/llm/openai.rs b/crates/pulsing-forge/src/llm/openai.rs deleted file mode 100644 index d60e95c04..000000000 --- a/crates/pulsing-forge/src/llm/openai.rs +++ /dev/null @@ -1,142 +0,0 @@ -use std::collections::BTreeMap; - -use futures_util::StreamExt; -use reqwest::Client; -use reqwest_eventsource::{Event as SseEvent, EventSource}; -use serde_json::{Value, json}; - -use super::error::LlmError; -use super::message::{build_openai_request, normalize_openai_stop_reason}; -use super::types::{LlmMessage, LlmUsage, StreamRequest}; - -pub struct OpenAiStream { - text_chunks: Vec, - final_message: LlmMessage, -} - -impl OpenAiStream { - pub async fn start( - client: &Client, - api_key: &str, - base_url: &str, - req: &StreamRequest, - ) -> Result { - let url = format!("{}/chat/completions", base_url.trim_end_matches('/')); - let body = build_openai_request(req, true); - - let request = client - .post(url) - .header("Authorization", format!("Bearer {api_key}")) - .header("Content-Type", "application/json") - .header("Accept", "text/event-stream") - .json(&body); - - let mut es = EventSource::new(request).map_err(|e| LlmError::Stream(e.to_string()))?; - let mut text_parts = String::new(); - let mut text_chunks = Vec::new(); - let mut tool_calls: BTreeMap = BTreeMap::new(); - let mut usage: Option = None; - let mut finish_reason: Option = None; - - while let Some(event) = es.next().await { - match event { - Ok(SseEvent::Open) => {} - Ok(SseEvent::Message(message)) => { - let data = message.data.trim(); - if data == "[DONE]" { - break; - } - let json: Value = serde_json::from_str(data)?; - if let Some(u) = json.get("usage") { - usage = Some(LlmUsage { - input_tokens: u - .get("prompt_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(0), - output_tokens: u - .get("completion_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(0), - }); - } - let choices = json - .get("choices") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - for choice in choices { - if let Some(reason) = choice.get("finish_reason").and_then(|v| v.as_str()) { - finish_reason = Some(reason.to_string()); - } - let delta = choice.get("delta").cloned().unwrap_or_else(|| json!({})); - if let Some(content) = delta.get("content").and_then(|v| v.as_str()) { - text_parts.push_str(content); - text_chunks.push(content.to_string()); - } - if let Some(calls) = delta.get("tool_calls").and_then(|v| v.as_array()) { - for call in calls { - let index = call.get("index").and_then(|v| v.as_u64()).unwrap_or(0) - as usize; - let entry = tool_calls.entry(index).or_insert_with(|| { - (String::new(), String::new(), String::new()) - }); - if let Some(id) = call.get("id").and_then(|v| v.as_str()) { - entry.0 = id.to_string(); - } - if let Some(function) = call.get("function") { - if let Some(name) = - function.get("name").and_then(|v| v.as_str()) - { - entry.1 = name.to_string(); - } - if let Some(args) = - function.get("arguments").and_then(|v| v.as_str()) - { - entry.2.push_str(args); - } - } - } - } - } - } - Err(e) => return Err(LlmError::Stream(e.to_string())), - } - } - - let mut content = Vec::new(); - if !text_parts.is_empty() { - content.push(json!({ "type": "text", "text": text_parts })); - } - for (_idx, (id, name, args)) in tool_calls { - let parsed: Value = serde_json::from_str(args.trim()).unwrap_or_else(|_| json!({})); - let input = if parsed.is_object() { - parsed - } else { - json!({}) - }; - content.push(json!({ - "type": "tool_use", - "id": id, - "name": name, - "input": input, - })); - } - - Ok(Self { - text_chunks, - final_message: LlmMessage { - content, - usage, - stop_reason: normalize_openai_stop_reason(finish_reason.as_deref()), - }, - }) - } - - pub fn text_chunks(&self) -> &[String] { - &self.text_chunks - } - - pub fn final_message(&self) -> LlmMessage { - self.final_message.clone() - } -} diff --git a/crates/pulsing-forge/src/llm/types.rs b/crates/pulsing-forge/src/llm/types.rs deleted file mode 100644 index b0369b0b2..000000000 --- a/crates/pulsing-forge/src/llm/types.rs +++ /dev/null @@ -1,53 +0,0 @@ -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum Provider { - Anthropic, - Openai, - Demo, -} - -impl Provider { - pub fn parse(s: &str) -> Option { - match s.trim().to_lowercase().as_str() { - "anthropic" => Some(Self::Anthropic), - "openai" => Some(Self::Openai), - "demo" => Some(Self::Demo), - _ => None, - } - } - - pub fn as_str(self) -> &'static str { - match self { - Self::Anthropic => "anthropic", - Self::Openai => "openai", - Self::Demo => "demo", - } - } -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct LlmUsage { - pub input_tokens: u64, - pub output_tokens: u64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct LlmMessage { - pub content: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub usage: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub stop_reason: Option, -} - -#[derive(Debug, Clone)] -pub struct StreamRequest { - pub model: String, - pub max_tokens: u32, - pub messages: Vec, - pub system: Option, - pub tools: Vec, -} diff --git a/crates/pulsing-forge/src/mcp/catalog.rs b/crates/pulsing-forge/src/mcp/catalog.rs deleted file mode 100644 index 2c28c42c9..000000000 --- a/crates/pulsing-forge/src/mcp/catalog.rs +++ /dev/null @@ -1,275 +0,0 @@ -//! MCP catalog builder with Codex precedence: Plugin < Config < Compatibility < Extension. - -use std::cmp::Reverse; -use std::collections::{BTreeMap, BTreeSet, HashMap}; - -use super::config::McpServerConfig; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum McpServerSource { - Plugin { plugin_id: String }, - Config, - Compatibility { id: String }, - Extension { id: String }, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -enum RegistrationPrecedence { - Plugin(Reverse), - Config, - Compatibility, - Extension(usize), -} - -impl RegistrationPrecedence { - fn tier(self) -> u8 { - match self { - Self::Plugin(_) => 0, - Self::Config => 1, - Self::Compatibility => 2, - Self::Extension(_) => 3, - } - } -} - -#[derive(Clone, Debug, PartialEq)] -pub struct McpServerRegistration { - name: String, - source: McpServerSource, - config: McpServerConfig, - precedence: RegistrationPrecedence, -} - -impl McpServerRegistration { - pub fn from_config(name: String, config: McpServerConfig) -> Self { - Self::new( - name, - McpServerSource::Config, - config, - RegistrationPrecedence::Config, - ) - } - - pub fn from_plugin( - name: String, - plugin_id: String, - plugin_order: usize, - config: McpServerConfig, - ) -> Self { - Self::new( - name, - McpServerSource::Plugin { plugin_id }, - config, - RegistrationPrecedence::Plugin(Reverse(plugin_order)), - ) - } - - fn new( - name: String, - source: McpServerSource, - config: McpServerConfig, - precedence: RegistrationPrecedence, - ) -> Self { - Self { - name, - source, - config, - precedence, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum McpServerConflictAction { - Register(McpServerSource), - Remove(McpServerSource), -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct McpServerConflict { - pub name: String, - pub outcome: McpServerConflictAction, - pub contenders: Vec, -} - -#[derive(Clone, Debug)] -pub struct ResolvedMcpServer { - pub source: McpServerSource, - pub config: McpServerConfig, -} - -#[derive(Clone, Debug, Default)] -pub struct ResolvedMcpCatalog { - pub servers: HashMap, - pub conflicts: Vec, -} - -#[derive(Clone, Debug)] -enum CatalogAction { - Register(Box), - Remove { - name: String, - source: McpServerSource, - precedence: RegistrationPrecedence, - }, -} - -impl CatalogAction { - fn name(&self) -> &str { - match self { - Self::Register(r) => &r.name, - Self::Remove { name, .. } => name, - } - } - - fn precedence(&self) -> RegistrationPrecedence { - match self { - Self::Register(r) => r.precedence, - Self::Remove { precedence, .. } => *precedence, - } - } - - fn conflict_action(&self) -> McpServerConflictAction { - match self { - Self::Register(r) => McpServerConflictAction::Register(r.source.clone()), - Self::Remove { source, .. } => McpServerConflictAction::Remove(source.clone()), - } - } -} - -#[derive(Clone, Debug, Default)] -pub struct McpCatalogBuilder { - actions: Vec, - disabled_server_names: BTreeSet, -} - -impl McpCatalogBuilder { - pub fn register(&mut self, registration: McpServerRegistration) { - self.actions - .push(CatalogAction::Register(Box::new(registration))); - } - - pub fn disable(&mut self, name: String) { - self.disabled_server_names.insert(name); - } - - pub fn build(mut self) -> ResolvedMcpCatalog { - self.actions.sort_by_key(CatalogAction::precedence); - - let mut winners = BTreeMap::::new(); - let mut actions_by_name_and_tier = BTreeMap::<(String, u8), Vec<&CatalogAction>>::new(); - for action in &self.actions { - winners.insert(action.name().to_string(), action.clone()); - actions_by_name_and_tier - .entry((action.name().to_string(), action.precedence().tier())) - .or_default() - .push(action); - } - - let mut conflicts = Vec::new(); - for ((name, _), actions) in actions_by_name_and_tier { - if actions.len() < 2 { - continue; - } - let Some(outcome) = winners.get(&name).map(CatalogAction::conflict_action) else { - continue; - }; - conflicts.push(McpServerConflict { - name, - outcome, - contenders: actions - .into_iter() - .map(CatalogAction::conflict_action) - .collect(), - }); - } - - let mut disabled = self.disabled_server_names; - let servers = winners - .into_iter() - .filter_map(|(name, action)| match action { - CatalogAction::Register(registration) => { - let mut registration = *registration; - if !registration.config.enabled || disabled.contains(&name) { - registration.config.enabled = false; - disabled.insert(name.clone()); - } - Some(( - name, - ResolvedMcpServer { - source: registration.source, - config: registration.config, - }, - )) - } - CatalogAction::Remove { .. } => None, - }) - .collect(); - - ResolvedMcpCatalog { servers, conflicts } - } -} - -pub fn build_default_catalog( - plugin_servers: Vec<(String, String, usize, McpServerConfig)>, - config_servers: HashMap, -) -> ResolvedMcpCatalog { - let mut builder = McpCatalogBuilder::default(); - for (name, plugin_id, order, config) in plugin_servers { - builder.register(McpServerRegistration::from_plugin( - name, plugin_id, order, config, - )); - } - for (name, config) in config_servers { - builder.register(McpServerRegistration::from_config(name, config)); - } - builder.build() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::mcp::config::McpServerTransportConfig; - - fn stdio_cfg() -> McpServerConfig { - McpServerConfig { - transport: McpServerTransportConfig::Stdio { - command: "echo".into(), - args: vec![], - env: None, - env_vars: vec![], - cwd: None, - }, - environment_id: "local".into(), - enabled: true, - required: false, - supports_parallel_tool_calls: false, - startup_timeout_sec: None, - tool_timeout_sec: None, - default_tools_approval_mode: None, - enabled_tools: None, - disabled_tools: None, - scopes: None, - oauth: None, - oauth_resource: None, - tools: Default::default(), - } - } - - #[test] - fn config_overrides_plugin() { - let mut plugin = stdio_cfg(); - plugin.enabled = false; - let mut user = stdio_cfg(); - user.enabled = true; - let catalog = build_default_catalog( - vec![("demo".into(), "p@m".into(), 0, plugin)], - HashMap::from([("demo".into(), user)]), - ); - assert!(catalog.servers["demo"].config.enabled); - assert!(matches!( - catalog.servers["demo"].source, - McpServerSource::Config - )); - } -} diff --git a/crates/pulsing-forge/src/mcp/client.rs b/crates/pulsing-forge/src/mcp/client.rs deleted file mode 100644 index fe5a79f71..000000000 --- a/crates/pulsing-forge/src/mcp/client.rs +++ /dev/null @@ -1,218 +0,0 @@ -//! RMCP client wrapper for stdio and streamable HTTP transports. - -use std::collections::HashMap; -use std::time::Duration; - -use rmcp::ServiceExt; -use rmcp::model::{ - CallToolRequestParams, CallToolResult, PaginatedRequestParams, ReadResourceRequestParams, - ReadResourceResult, -}; -use rmcp::service::{ClientInitializeError, RoleClient, RunningService}; -use rmcp::transport::ConfigureCommandExt; -use rmcp::transport::StreamableHttpClientTransport; -use rmcp::transport::child_process::TokioChildProcess; -use tokio::process::Command; -use tokio::sync::Mutex; - -use super::DEFAULT_STARTUP_TIMEOUT_SECS; -use super::config::{McpServerConfig, McpServerEnvVar, McpServerTransportConfig}; -use super::tools::{ToolFilter, ToolInfo, filter_tools}; - -#[derive(Debug, thiserror::Error)] -pub enum McpClientError { - #[error("MCP initialize error: {0}")] - Initialize(#[from] ClientInitializeError), - #[error("MCP service error: {0}")] - Service(#[from] rmcp::service::ServiceError), - #[error("startup timed out after {0:?}")] - StartupTimeout(Duration), - #[error("server {server}: {message}")] - Startup { server: String, message: String }, -} - -pub struct McpManagedClient { - pub server_name: String, - service: RunningService, - pub tools: Vec, - pub tool_filter: ToolFilter, - pub tool_timeout: Duration, -} - -impl McpManagedClient { - pub async fn connect_stdio( - server_name: String, - config: &McpServerConfig, - ) -> Result { - let McpServerTransportConfig::Stdio { - command, - args, - env, - env_vars, - cwd, - } = &config.transport - else { - return Err(McpClientError::Startup { - server: server_name, - message: "expected stdio transport".into(), - }); - }; - - let transport = TokioChildProcess::new(Command::new(command).configure(|cmd| { - cmd.args(args); - if let Some(cwd) = cwd { - cmd.current_dir(cwd); - } - apply_env(cmd, env.as_ref(), env_vars); - })) - .map_err(|e| McpClientError::Startup { - server: server_name.clone(), - message: e.to_string(), - })?; - - Self::connect_with_transport(server_name, config, transport).await - } - - pub async fn connect_streamable_http( - server_name: String, - config: &McpServerConfig, - ) -> Result { - let McpServerTransportConfig::StreamableHttp { url, .. } = &config.transport else { - return Err(McpClientError::Startup { - server: server_name, - message: "expected streamable_http transport".into(), - }); - }; - - let transport = StreamableHttpClientTransport::from_uri(url.clone()); - Self::connect_with_transport(server_name, config, transport).await - } - - async fn connect_with_transport( - server_name: String, - config: &McpServerConfig, - transport: T, - ) -> Result - where - T: rmcp::transport::Transport + Send + 'static, - { - let timeout = config - .startup_timeout_sec - .map(Duration::from_secs) - .unwrap_or(Duration::from_secs(DEFAULT_STARTUP_TIMEOUT_SECS)); - - let connect = async { ().serve(transport).await }; - - let service = tokio::time::timeout(timeout, connect) - .await - .map_err(|_| McpClientError::StartupTimeout(timeout))??; - - let tool_filter = ToolFilter::from_config(config); - let listed = service.list_all_tools().await?; - let mut tools = Vec::new(); - for tool in listed { - let description = tool.description.as_ref().map(|d| d.to_string()); - tools.push(ToolInfo { - server_name: server_name.clone(), - supports_parallel_tool_calls: config.supports_parallel_tool_calls, - server_origin: Some("plugin".into()), - callable_name: tool.name.to_string(), - callable_namespace: server_name.clone(), - namespace_description: description, - tool, - connector_id: None, - connector_name: None, - plugin_display_names: vec![], - }); - } - tools = filter_tools(tools, &tool_filter); - - Ok(Self { - server_name, - service, - tools, - tool_filter, - tool_timeout: config.tool_timeout(), - }) - } - - pub async fn call_tool( - &self, - tool_name: &str, - arguments: serde_json::Value, - ) -> Result { - let args: rmcp::model::JsonObject = arguments - .as_object() - .cloned() - .unwrap_or_default() - .into_iter() - .collect(); - let params = CallToolRequestParams::new(tool_name.to_string()).with_arguments(args); - let call = self.service.call_tool(params); - tokio::time::timeout(self.tool_timeout, call) - .await - .map_err(|_| McpClientError::Startup { - server: self.server_name.clone(), - message: format!("tool call timed out after {:?}", self.tool_timeout), - })? - .map_err(McpClientError::Service) - } - - pub async fn list_resources( - &self, - params: Option, - ) -> Result { - self.service - .list_resources(params) - .await - .map_err(McpClientError::Service) - } - - pub async fn list_resource_templates( - &self, - params: Option, - ) -> Result { - self.service - .list_resource_templates(params) - .await - .map_err(McpClientError::Service) - } - - pub async fn read_resource( - &self, - params: ReadResourceRequestParams, - ) -> Result { - self.service - .read_resource(params) - .await - .map_err(McpClientError::Service) - } - - pub async fn close_connection(&mut self) { - let _ = self.service.close().await; - } - - pub async fn shutdown(mut self) -> Result<(), McpClientError> { - self.close_connection().await; - Ok(()) - } -} - -fn apply_env( - cmd: &mut Command, - env: Option<&HashMap>, - env_vars: &[McpServerEnvVar], -) { - if let Some(env) = env { - for (k, v) in env { - cmd.env(k, v); - } - } - for var in env_vars { - if let Ok(val) = std::env::var(var.name()) { - cmd.env(var.name(), val); - } - } -} - -pub type SharedMcpClient = std::sync::Arc>; diff --git a/crates/pulsing-forge/src/mcp/codex_home.rs b/crates/pulsing-forge/src/mcp/codex_home.rs deleted file mode 100644 index 25df9a0e7..000000000 --- a/crates/pulsing-forge/src/mcp/codex_home.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! Codex home paths and config.toml MCP server loading. - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; - -use super::config::McpServerConfig; - -pub fn codex_home() -> PathBuf { - if let Ok(raw) = std::env::var("CODEX_HOME") { - let trimmed = raw.trim(); - if !trimmed.is_empty() { - return PathBuf::from(trimmed); - } - } - dirs_home().join(".codex") -} - -pub fn credentials_path() -> PathBuf { - codex_home().join(".credentials.json") -} - -fn dirs_home() -> PathBuf { - std::env::var("HOME") - .map(PathBuf::from) - .unwrap_or_else(|_| PathBuf::from(".")) -} - -pub fn config_toml_path() -> PathBuf { - codex_home().join("config.toml") -} - -/// Load `[mcp_servers.]` from `~/.codex/config.toml`. -pub fn load_config_mcp_servers() -> HashMap { - let path = config_toml_path(); - let Ok(text) = std::fs::read_to_string(&path) else { - return HashMap::new(); - }; - parse_config_toml_mcp_servers(&text) -} - -pub fn parse_config_toml_mcp_servers(text: &str) -> HashMap { - let Ok(doc) = text.parse::() else { - return HashMap::new(); - }; - let Some(mcp_servers) = doc.get("mcp_servers").and_then(|v| v.as_table()) else { - return HashMap::new(); - }; - let mut out = HashMap::new(); - for (name, value) in mcp_servers { - let Some(table) = value.as_table() else { - continue; - }; - let table_value = toml_table_to_json(table); - match serde_json::from_value::(table_value) { - Ok(cfg) => { - out.insert(name.clone(), cfg); - } - Err(err) => { - tracing::warn!(server = %name, error = %err, "skip invalid mcp_servers entry"); - } - } - } - out -} - -fn toml_table_to_json(table: &toml::Table) -> serde_json::Value { - let mut map = serde_json::Map::new(); - for (k, v) in table { - map.insert(k.clone(), toml_value_to_json(v)); - } - serde_json::Value::Object(map) -} - -fn toml_value_to_json(v: &toml::Value) -> serde_json::Value { - match v { - toml::Value::String(s) => serde_json::Value::String(s.clone()), - toml::Value::Integer(i) => serde_json::Value::Number((*i).into()), - toml::Value::Float(f) => serde_json::Number::from_f64(*f) - .map(serde_json::Value::Number) - .unwrap_or(serde_json::Value::Null), - toml::Value::Boolean(b) => serde_json::Value::Bool(*b), - toml::Value::Datetime(dt) => serde_json::Value::String(dt.to_string()), - toml::Value::Array(arr) => { - serde_json::Value::Array(arr.iter().map(toml_value_to_json).collect()) - } - toml::Value::Table(t) => toml_table_to_json(t), - } -} - -pub fn plugins_cache_root() -> PathBuf { - codex_home().join("plugins/cache") -} - -pub fn resolve_plugin_root(marketplace: &str, name: &str, version: &str) -> PathBuf { - plugins_cache_root() - .join(marketplace) - .join(name) - .join(version) -} - -pub fn find_plugin_mcp_json(plugin_root: &Path, relative: &str) -> Option { - let path = plugin_root.join(relative); - if path.is_file() { Some(path) } else { None } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_mcp_servers_toml() { - let text = r#" -[mcp_servers.demo] -command = "echo" -args = ["hello"] -enabled = true -"#; - let servers = parse_config_toml_mcp_servers(text); - assert_eq!(servers.len(), 1); - assert!(servers.contains_key("demo")); - } -} diff --git a/crates/pulsing-forge/src/mcp/config.rs b/crates/pulsing-forge/src/mcp/config.rs deleted file mode 100644 index 04c9a0cdd..000000000 --- a/crates/pulsing-forge/src/mcp/config.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! MCP server configuration types (aligned with codex-config `mcp_types.rs`). - -use std::collections::HashMap; -use std::path::PathBuf; -use std::time::Duration; - -use serde::de::Error as SerdeError; -use serde::{Deserialize, Deserializer, Serialize}; - -pub const DEFAULT_MCP_SERVER_ENVIRONMENT_ID: &str = "local"; - -#[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum AppToolApproval { - #[default] - Auto, - Prompt, - Approve, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(untagged)] -pub enum McpServerEnvVar { - Name(String), - Config { - name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - source: Option, - }, -} - -impl McpServerEnvVar { - pub fn name(&self) -> &str { - match self { - Self::Name(name) => name, - Self::Config { name, .. } => name, - } - } - - pub fn validate_source(&self) -> Result<(), String> { - match self { - Self::Name(_) => Ok(()), - Self::Config { source, .. } => match source.as_deref() { - None | Some("local") | Some("remote") => Ok(()), - Some(s) => Err(format!( - "unsupported env_vars source `{s}`; expected `local` or `remote`" - )), - }, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct McpServerOAuthConfig { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub client_id: Option, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "transport", rename_all = "snake_case")] -pub enum McpServerTransportConfig { - Stdio { - command: String, - #[serde(default)] - args: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - env: Option>, - #[serde(default)] - env_vars: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - cwd: Option, - }, - StreamableHttp { - url: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - bearer_token_env_var: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - http_headers: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - env_http_headers: Option>, - }, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct McpServerToolConfig { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub approval_mode: Option, -} - -#[derive(Clone, Debug, PartialEq, Serialize)] -pub struct McpServerConfig { - #[serde(flatten)] - pub transport: McpServerTransportConfig, - - #[serde(default = "default_environment_id")] - pub environment_id: String, - - #[serde(default = "default_enabled")] - pub enabled: bool, - - #[serde(default, skip_serializing_if = "std::ops::Not::not")] - pub required: bool, - - #[serde(default, skip_serializing_if = "std::ops::Not::not")] - pub supports_parallel_tool_calls: bool, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub startup_timeout_sec: Option, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tool_timeout_sec: Option, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub default_tools_approval_mode: Option, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub enabled_tools: Option>, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub disabled_tools: Option>, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub scopes: Option>, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub oauth: Option, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub oauth_resource: Option, - - #[serde(default, skip_serializing_if = "HashMap::is_empty")] - pub tools: HashMap, -} - -impl McpServerConfig { - pub fn startup_timeout(&self) -> Duration { - Duration::from_secs(self.startup_timeout_sec.unwrap_or(30)) - } - - pub fn tool_timeout(&self) -> Duration { - Duration::from_secs(self.tool_timeout_sec.unwrap_or(120)) - } - - pub fn oauth_client_id(&self) -> Option<&str> { - self.oauth.as_ref().and_then(|o| o.client_id.as_deref()) - } -} - -fn default_enabled() -> bool { - true -} - -fn default_environment_id() -> String { - DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string() -} - -#[derive(Deserialize)] -struct RawMcpServerConfig { - command: Option, - #[serde(default)] - args: Option>, - #[serde(default)] - env: Option>, - #[serde(default)] - env_vars: Option>, - #[serde(default)] - cwd: Option, - url: Option, - #[serde(default)] - bearer_token_env_var: Option, - #[serde(default)] - http_headers: Option>, - #[serde(default)] - env_http_headers: Option>, - #[serde(default)] - environment_id: Option, - #[serde(default)] - startup_timeout_sec: Option, - #[serde(default)] - startup_timeout_ms: Option, - #[serde(default)] - tool_timeout_sec: Option, - #[serde(default)] - enabled: Option, - #[serde(default)] - required: Option, - #[serde(default)] - supports_parallel_tool_calls: Option, - #[serde(default)] - default_tools_approval_mode: Option, - #[serde(default)] - enabled_tools: Option>, - #[serde(default)] - disabled_tools: Option>, - #[serde(default)] - scopes: Option>, - #[serde(default)] - oauth: Option, - #[serde(default)] - oauth_resource: Option, - #[serde(default)] - tools: Option>, -} - -impl TryFrom for McpServerConfig { - type Error = String; - - fn try_from(raw: RawMcpServerConfig) -> Result { - let startup_timeout_sec = match (raw.startup_timeout_sec, raw.startup_timeout_ms) { - (Some(sec), _) if sec >= 0.0 => Some(sec.round() as u64), - (None, Some(ms)) => Some(ms / 1000), - _ => None, - }; - let tool_timeout_sec = raw - .tool_timeout_sec - .filter(|s| *s >= 0.0) - .map(|s| s.round() as u64); - - let transport = if let Some(command) = raw.command { - let env_vars = raw.env_vars.unwrap_or_default(); - for ev in &env_vars { - ev.validate_source()?; - } - McpServerTransportConfig::Stdio { - command, - args: raw.args.unwrap_or_default(), - env: raw.env, - env_vars, - cwd: raw.cwd, - } - } else if let Some(url) = raw.url { - McpServerTransportConfig::StreamableHttp { - url, - bearer_token_env_var: raw.bearer_token_env_var, - http_headers: raw.http_headers, - env_http_headers: raw.env_http_headers, - } - } else { - return Err("invalid transport: need command (stdio) or url (streamable_http)".into()); - }; - - Ok(Self { - transport, - environment_id: raw.environment_id.unwrap_or_else(default_environment_id), - enabled: raw.enabled.unwrap_or(true), - required: raw.required.unwrap_or(false), - supports_parallel_tool_calls: raw.supports_parallel_tool_calls.unwrap_or(false), - startup_timeout_sec, - tool_timeout_sec, - default_tools_approval_mode: raw.default_tools_approval_mode, - enabled_tools: raw.enabled_tools, - disabled_tools: raw.disabled_tools, - scopes: raw.scopes, - oauth: raw.oauth, - oauth_resource: raw.oauth_resource, - tools: raw.tools.unwrap_or_default(), - }) - } -} - -impl<'de> Deserialize<'de> for McpServerConfig { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - RawMcpServerConfig::deserialize(deserializer)? - .try_into() - .map_err(SerdeError::custom) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_stdio_config() { - let raw = r#"{"command":"npx","args":["-y","@modelcontextprotocol/server-everything"]}"#; - let cfg: McpServerConfig = serde_json::from_str(raw).unwrap(); - match cfg.transport { - McpServerTransportConfig::Stdio { command, .. } => assert_eq!(command, "npx"), - _ => panic!("expected stdio"), - } - } -} diff --git a/crates/pulsing-forge/src/mcp/connection_manager.rs b/crates/pulsing-forge/src/mcp/connection_manager.rs deleted file mode 100644 index e687a15c2..000000000 --- a/crates/pulsing-forge/src/mcp/connection_manager.rs +++ /dev/null @@ -1,275 +0,0 @@ -//! Aggregates MCP server connections (Codex `McpConnectionManager` subset). - -use std::collections::HashMap; -use std::sync::Arc; - -use rmcp::model::{ - CallToolResult, PaginatedRequestParams, ReadResourceRequestParams, ReadResourceResult, - Resource, ResourceTemplate, -}; -use tokio::sync::Mutex; -use tracing::{info, warn}; - -use super::catalog::ResolvedMcpCatalog; -use super::client::{McpClientError, McpManagedClient}; -use super::config::McpServerTransportConfig; -use super::tools::{ToolInfo, normalize_tools_for_model, tool_is_model_visible}; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum McpStartupStatus { - Starting, - Ready, - Failed, -} - -#[derive(Clone, Debug)] -pub struct McpStartupFailure { - pub server: String, - pub message: String, -} - -pub struct McpConnectionManager { - clients: HashMap>>, - all_tools: Vec, - prefix_mcp_tool_names: bool, - failures: Vec, -} - -impl McpConnectionManager { - pub async fn start(catalog: &ResolvedMcpCatalog, prefix_mcp_tool_names: bool) -> Self { - let mut clients = HashMap::new(); - let mut failures = Vec::new(); - let mut join = tokio::task::JoinSet::new(); - - for (name, server) in &catalog.servers { - if !server.config.enabled { - continue; - } - let name = name.clone(); - let config = server.config.clone(); - join.spawn(async move { - let result = match &config.transport { - McpServerTransportConfig::Stdio { .. } => { - McpManagedClient::connect_stdio(name.clone(), &config).await - } - McpServerTransportConfig::StreamableHttp { .. } => { - McpManagedClient::connect_streamable_http(name.clone(), &config).await - } - }; - (name, result) - }); - } - - while let Some(res) = join.join_next().await { - match res { - Ok((name, Ok(client))) => { - info!(server = %name, tools = client.tools.len(), "MCP server ready"); - clients.insert(name, Arc::new(Mutex::new(client))); - } - Ok((name, Err(err))) => { - warn!(server = %name, error = %err, "MCP server startup failed"); - failures.push(McpStartupFailure { - server: name, - message: err.to_string(), - }); - } - Err(err) => { - warn!(error = %err, "MCP startup task join failed"); - } - } - } - - let mut all_tools = Vec::new(); - for client in clients.values() { - let guard = client.lock().await; - for tool in &guard.tools { - if tool_is_model_visible(tool) { - all_tools.push(tool.clone()); - } - } - } - all_tools = normalize_tools_for_model(all_tools, prefix_mcp_tool_names); - - Self { - clients, - all_tools, - prefix_mcp_tool_names, - failures, - } - } - - pub fn failures(&self) -> &[McpStartupFailure] { - &self.failures - } - - pub fn list_all_tools(&self) -> &[ToolInfo] { - &self.all_tools - } - - pub fn find_tool(&self, model_name: &str) -> Option<&ToolInfo> { - self.all_tools - .iter() - .find(|t| t.model_tool_name(self.prefix_mcp_tool_names) == model_name) - } - - pub async fn call_tool_by_model_name( - &self, - model_name: &str, - arguments: serde_json::Value, - ) -> Result { - let tool = self.find_tool(model_name).ok_or_else(|| { - let hint = if self.all_tools.is_empty() { - "no MCP tools are registered (check server startup failures)".into() - } else { - format!( - "available tools: {}", - self.all_tools - .iter() - .map(|t| t.model_tool_name(self.prefix_mcp_tool_names)) - .collect::>() - .join(", ") - ) - }; - McpClientError::Startup { - server: model_name.into(), - message: format!("unknown MCP tool; {hint}"), - } - })?; - let client = - self.clients - .get(&tool.server_name) - .ok_or_else(|| McpClientError::Startup { - server: tool.server_name.clone(), - message: format!("MCP server not connected for tool {:?}", tool.tool.name), - })?; - client - .lock() - .await - .call_tool(&tool.tool.name, arguments) - .await - } - - pub async fn call_tool_raw( - &self, - server: &str, - tool_name: &str, - arguments: serde_json::Value, - ) -> Result { - let client = self - .clients - .get(server) - .ok_or_else(|| McpClientError::Startup { - server: server.into(), - message: "MCP server not connected".into(), - })?; - client.lock().await.call_tool(tool_name, arguments).await - } - - pub async fn list_resources( - &self, - server: &str, - params: Option, - ) -> Result, McpClientError> { - let client = self - .clients - .get(server) - .ok_or_else(|| McpClientError::Startup { - server: server.into(), - message: "MCP server not connected".into(), - })?; - Ok(client.lock().await.list_resources(params).await?.resources) - } - - pub async fn list_all_resources(&self) -> HashMap> { - let mut out = HashMap::new(); - for (name, client) in &self.clients { - if let Ok(result) = client.lock().await.list_resources(None).await { - out.insert(name.clone(), result.resources); - } - } - out - } - - /// Best-effort close of all live MCP transports (used before refresh). - pub async fn shutdown(&self) { - for client in self.clients.values() { - let mut guard = client.lock().await; - guard.close_connection().await; - } - } - - pub async fn list_resource_templates( - &self, - server: &str, - params: Option, - ) -> Result, McpClientError> { - let client = self - .clients - .get(server) - .ok_or_else(|| McpClientError::Startup { - server: server.into(), - message: "MCP server not connected".into(), - })?; - Ok(client - .lock() - .await - .list_resource_templates(params) - .await? - .resource_templates) - } - - pub async fn read_resource( - &self, - server: &str, - params: ReadResourceRequestParams, - ) -> Result { - let client = self - .clients - .get(server) - .ok_or_else(|| McpClientError::Startup { - server: server.into(), - message: "MCP server not connected".into(), - })?; - client.lock().await.read_resource(params).await - } - - pub fn server_names(&self) -> Vec { - let mut names: Vec<_> = self.clients.keys().cloned().collect(); - names.sort(); - names - } -} - -#[cfg(test)] -impl McpConnectionManager { - pub fn from_tools(tools: Vec, prefix_mcp_tool_names: bool) -> Self { - Self { - clients: HashMap::new(), - all_tools: normalize_tools_for_model(tools, prefix_mcp_tool_names), - prefix_mcp_tool_names, - failures: Vec::new(), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::mcp::build_default_catalog; - - #[tokio::test] - async fn list_all_resources_empty_when_no_clients() { - let catalog = build_default_catalog(vec![], HashMap::new()); - let manager = McpConnectionManager::start(&catalog, true).await; - let all = manager.list_all_resources().await; - assert!(all.is_empty()); - } - - #[tokio::test] - async fn list_resources_unknown_server_errors() { - let catalog = build_default_catalog(vec![], HashMap::new()); - let manager = McpConnectionManager::start(&catalog, true).await; - let err = manager.list_resources("missing", None).await.unwrap_err(); - assert!(err.to_string().contains("MCP server not connected")); - } -} diff --git a/crates/pulsing-forge/src/mcp/mod.rs b/crates/pulsing-forge/src/mcp/mod.rs deleted file mode 100644 index ed3635929..000000000 --- a/crates/pulsing-forge/src/mcp/mod.rs +++ /dev/null @@ -1,155 +0,0 @@ -//! Codex-aligned MCP client runtime + Forge integration. -//! -//! Ports essential behavior of `codex-mcp` + `codex-rmcp-client` without the full Codex workspace. - -mod catalog; -mod client; -mod codex_home; -mod config; -mod connection_manager; -mod oauth; -mod plugin_config; -mod resources; -mod tools; - -pub use catalog::{ - McpCatalogBuilder, McpServerConflict, McpServerConflictAction, McpServerRegistration, - McpServerSource, ResolvedMcpCatalog, ResolvedMcpServer, build_default_catalog, -}; -pub use client::{McpClientError, McpManagedClient}; -pub use codex_home::{codex_home, credentials_path, load_config_mcp_servers, plugins_cache_root}; -pub use config::{ - AppToolApproval, DEFAULT_MCP_SERVER_ENVIRONMENT_ID, McpServerConfig, McpServerEnvVar, - McpServerOAuthConfig, McpServerToolConfig, McpServerTransportConfig, -}; -pub use connection_manager::{McpConnectionManager, McpStartupFailure, McpStartupStatus}; -pub use oauth::{OAuthCredentialsStore, OAuthLoginHandle, perform_oauth_login}; -pub use plugin_config::{ - PluginMcpConfigParseOutcome, PluginMcpServerParseError, PluginMcpServerPlacement, - parse_plugin_mcp_config, -}; -pub use resources::{ - MAX_MCP_RESOURCE_BYTES, enforce_resource_size_limit, validate_mcp_resource_uri, -}; -pub use tools::{ - ToolFilter, ToolInfo, tool_input_schema_json, tool_is_model_visible, tool_spec_for_model, -}; - -pub const DIRECT_MCP_TOOL_EXPOSURE_THRESHOLD: usize = 100; -pub const LEGACY_MCP_TOOL_NAME_PREFIX: &str = "mcp__"; -pub const DEFAULT_STARTUP_TIMEOUT_SECS: u64 = 30; -pub const DEFAULT_TOOL_TIMEOUT_SECS: u64 = 120; - -use std::path::Path; -use std::sync::Arc; - -pub struct McpRuntime { - pub catalog: ResolvedMcpCatalog, - pub manager: McpConnectionManager, -} - -impl McpRuntime { - pub async fn from_codex_home(prefix_mcp_tool_names: bool) -> Self { - let catalog = load_codex_mcp_catalog(); - let manager = McpConnectionManager::start(&catalog, prefix_mcp_tool_names).await; - Self { catalog, manager } - } - - pub fn tool_model_names(&self) -> Vec { - self.manager - .list_all_tools() - .iter() - .map(|t| t.model_tool_name(true)) - .collect() - } - - pub fn tool_specs_for_model(&self) -> Vec { - self.manager - .list_all_tools() - .iter() - .map(|t| tool_spec_for_model(t, true)) - .collect() - } -} - -pub fn load_codex_mcp_catalog() -> ResolvedMcpCatalog { - let config_servers = load_config_mcp_servers(); - let mut plugin_servers = Vec::new(); - let cache = plugins_cache_root(); - if cache.is_dir() { - collect_plugin_mcp_servers(&cache, &mut plugin_servers); - } - build_default_catalog(plugin_servers, config_servers) -} - -fn collect_plugin_mcp_servers( - cache: &Path, - out: &mut Vec<(String, String, usize, McpServerConfig)>, -) { - let Ok(entries) = std::fs::read_dir(cache) else { - return; - }; - let mut order = 0usize; - for marketplace in entries.flatten() { - let Ok(name_entries) = std::fs::read_dir(marketplace.path()) else { - continue; - }; - for plugin in name_entries.flatten() { - let Ok(version_entries) = std::fs::read_dir(plugin.path()) else { - continue; - }; - for version in version_entries.flatten() { - let root = version.path(); - let manifest = root.join(".codex-plugin/plugin.json"); - if !manifest.is_file() { - continue; - } - let Ok(text) = std::fs::read_to_string(&manifest) else { - continue; - }; - let Ok(raw) = serde_json::from_str::(&text) else { - continue; - }; - let mcp_ref = raw.get("mcpServers").or_else(|| raw.get("mcp_servers")); - let Some(mcp_ref) = mcp_ref.and_then(|v| v.as_str()) else { - continue; - }; - let mcp_path = root.join(mcp_ref); - let Ok(contents) = std::fs::read_to_string(&mcp_path) else { - continue; - }; - let plugin_id = format!( - "{}@{}", - plugin.file_name().to_string_lossy(), - marketplace.file_name().to_string_lossy() - ); - if let Ok(outcome) = - parse_plugin_mcp_config(&root, &contents, PluginMcpServerPlacement::Declared) - { - for (server_name, config) in outcome.servers { - out.push((server_name, plugin_id.clone(), order, config)); - order += 1; - } - } - } - } - } -} - -pub type SharedMcpRuntime = Arc>>; - -pub fn new_shared_mcp_runtime() -> SharedMcpRuntime { - Arc::new(tokio::sync::RwLock::new(None)) -} - -pub async fn refresh_mcp_runtime(slot: &SharedMcpRuntime) { - { - let mut guard = slot.write().await; - if let Some(old) = guard.take() { - old.manager.shutdown().await; - } - } - let runtime = McpRuntime::from_codex_home(true).await; - let mut guard = slot.write().await; - *guard = Some(runtime); -} diff --git a/crates/pulsing-forge/src/mcp/oauth.rs b/crates/pulsing-forge/src/mcp/oauth.rs deleted file mode 100644 index 6ffc175c1..000000000 --- a/crates/pulsing-forge/src/mcp/oauth.rs +++ /dev/null @@ -1,99 +0,0 @@ -//! OAuth token storage and login flow (Codex `rmcp-client/oauth.rs` subset). - -use std::collections::HashMap; -use std::path::PathBuf; -use std::sync::{Arc, Mutex}; - -use serde::{Deserialize, Serialize}; - -use super::codex_home::credentials_path; - -#[derive(Clone, Debug, Serialize, Deserialize, Default)] -pub struct StoredOAuthTokens { - pub access_token: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub refresh_token: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub expires_at: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub token_type: Option, -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -struct CredentialsFile { - #[serde(default)] - mcp_oauth_tokens: HashMap, -} - -#[derive(Clone, Default)] -pub struct OAuthCredentialsStore { - path: PathBuf, - inner: Arc>, -} - -impl OAuthCredentialsStore { - pub fn load_default() -> Self { - Self::load(credentials_path()) - } - - pub fn load(path: PathBuf) -> Self { - let inner = std::fs::read_to_string(&path) - .ok() - .and_then(|text| serde_json::from_str(&text).ok()) - .unwrap_or_default(); - Self { - path, - inner: Arc::new(Mutex::new(inner)), - } - } - - pub fn get(&self, server_name: &str) -> Option { - self.inner - .lock() - .ok() - .and_then(|f| f.mcp_oauth_tokens.get(server_name).cloned()) - } - - pub fn save(&self, server_name: &str, tokens: StoredOAuthTokens) -> std::io::Result<()> { - let mut guard = self - .inner - .lock() - .map_err(|_| std::io::Error::other("credentials lock poisoned"))?; - guard - .mcp_oauth_tokens - .insert(server_name.to_string(), tokens); - if let Some(parent) = self.path.parent() { - std::fs::create_dir_all(parent)?; - } - let text = serde_json::to_string_pretty(&*guard) - .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?; - std::fs::write(&self.path, text) - } - - pub fn delete(&self, server_name: &str) -> std::io::Result<()> { - let mut guard = self - .inner - .lock() - .map_err(|_| std::io::Error::other("credentials lock poisoned"))?; - guard.mcp_oauth_tokens.remove(server_name); - if let Some(parent) = self.path.parent() { - std::fs::create_dir_all(parent)?; - } - let text = serde_json::to_string_pretty(&*guard) - .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?; - std::fs::write(&self.path, text) - } -} - -/// Placeholder for Codex `perform_oauth_login_return_url` — returns URL for host UI. -pub struct OAuthLoginHandle { - pub authorization_url: String, - pub server_name: String, -} - -pub fn perform_oauth_login(server_name: &str, authorization_url: String) -> OAuthLoginHandle { - OAuthLoginHandle { - authorization_url, - server_name: server_name.to_string(), - } -} diff --git a/crates/pulsing-forge/src/mcp/plugin_config.rs b/crates/pulsing-forge/src/mcp/plugin_config.rs deleted file mode 100644 index b1623abf6..000000000 --- a/crates/pulsing-forge/src/mcp/plugin_config.rs +++ /dev/null @@ -1,248 +0,0 @@ -//! Parse plugin `.mcp.json` files (aligned with codex-mcp `plugin_config.rs`). - -use std::collections::BTreeMap; -use std::path::{Component, Path, PathBuf}; - -use serde::Deserialize; -use serde_json::{Map as JsonMap, Value as JsonValue}; -use tracing::warn; - -use super::config::McpServerConfig; - -#[derive(Clone, Copy, Debug)] -pub enum PluginMcpServerPlacement<'a> { - Declared, - Environment { environment_id: &'a str }, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PluginMcpServerParseError { - pub name: String, - pub message: String, -} - -#[derive(Debug, Default, PartialEq)] -pub struct PluginMcpConfigParseOutcome { - pub servers: BTreeMap, - pub errors: Vec, -} - -#[derive(Debug, Default, Deserialize)] -#[serde(rename_all = "camelCase")] -struct PluginMcpServersFile { - mcp_servers: BTreeMap, -} - -#[derive(Debug, Deserialize)] -#[serde(untagged)] -enum PluginMcpFile { - McpServersObject(PluginMcpServersFile), - ServerMap(BTreeMap), -} - -impl PluginMcpFile { - fn into_mcp_servers(self) -> BTreeMap { - match self { - Self::McpServersObject(file) => file.mcp_servers, - Self::ServerMap(mcp_servers) => mcp_servers, - } - } -} - -pub fn parse_plugin_mcp_config( - plugin_root: &Path, - contents: &str, - placement: PluginMcpServerPlacement<'_>, -) -> Result { - let parsed = serde_json::from_str::(contents)?; - let mut outcome = PluginMcpConfigParseOutcome::default(); - - for (name, config_value) in parsed.into_mcp_servers() { - match normalize_plugin_mcp_server(plugin_root, config_value, placement) { - Ok(config) => { - outcome.servers.insert(name, config); - } - Err(message) => outcome - .errors - .push(PluginMcpServerParseError { name, message }), - } - } - - Ok(outcome) -} - -fn normalize_plugin_mcp_server( - plugin_root: &Path, - value: JsonValue, - placement: PluginMcpServerPlacement<'_>, -) -> Result { - let mut object = normalize_plugin_mcp_server_value(plugin_root, value, placement); - if let PluginMcpServerPlacement::Environment { environment_id } = placement { - object.insert( - "environment_id".to_string(), - JsonValue::String(environment_id.to_string()), - ); - if object.contains_key("command") { - match object.remove("cwd") { - Some(JsonValue::String(cwd)) => object.insert( - "cwd".to_string(), - JsonValue::String( - executor_plugin_cwd(plugin_root, &cwd)? - .to_string_lossy() - .into_owned(), - ), - ), - Some(JsonValue::Null) | None => object.insert( - "cwd".to_string(), - JsonValue::String(plugin_root.to_string_lossy().into_owned()), - ), - Some(value) => object.insert("cwd".to_string(), value), - }; - } - } - - let mut config = serde_json::from_value::(JsonValue::Object(object)) - .map_err(|e| e.to_string())?; - if matches!(placement, PluginMcpServerPlacement::Environment { .. }) { - bind_environment_env_vars(&mut config)?; - } - Ok(config) -} - -fn bind_environment_env_vars(config: &mut McpServerConfig) -> Result<(), String> { - use super::config::{McpServerEnvVar, McpServerTransportConfig}; - - let McpServerTransportConfig::Stdio { env_vars, .. } = &mut config.transport else { - return Ok(()); - }; - let is_local = config.environment_id == super::config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID; - for env_var in env_vars { - match env_var { - McpServerEnvVar::Config { name, source } if source.is_none() && !is_local => { - *source = Some("remote".to_string()); - } - McpServerEnvVar::Config { - name, - source: Some(s), - .. - } if is_local && s == "remote" => { - return Err(format!( - "env_vars entry `{name}` cannot use source `remote` in a local environment" - )); - } - McpServerEnvVar::Config { - name, - source: Some(s), - .. - } if !is_local && s == "local" => { - return Err(format!( - "env_vars entry `{name}` cannot use source `local` in an executor-owned plugin" - )); - } - _ => {} - } - } - Ok(()) -} - -fn normalize_plugin_mcp_server_value( - plugin_root: &Path, - value: JsonValue, - placement: PluginMcpServerPlacement<'_>, -) -> JsonMap { - let mut object = match value { - JsonValue::Object(object) => object, - _ => return JsonMap::new(), - }; - - if let Some(JsonValue::String(transport_type)) = object.remove("type") { - match transport_type.as_str() { - "http" | "streamable_http" | "streamable-http" | "stdio" => {} - other => { - warn!( - plugin = %plugin_root.display(), - transport = other, - "plugin MCP server uses an unknown transport type" - ); - } - } - } - - if let Some(JsonValue::Object(mut oauth)) = object.remove("oauth") { - if oauth.remove("callbackPort").is_some() { - warn!( - plugin = %plugin_root.display(), - "plugin MCP OAuth callbackPort is ignored; Forge uses global MCP OAuth callback settings" - ); - } - if let Some(client_id) = oauth.remove("clientId") { - oauth.entry("client_id".to_string()).or_insert(client_id); - } - if !oauth.is_empty() { - object.insert("oauth".to_string(), JsonValue::Object(oauth)); - } - } - - if matches!(placement, PluginMcpServerPlacement::Declared) - && let Some(JsonValue::String(cwd)) = object.get("cwd") - && !Path::new(cwd).is_absolute() - { - object.insert( - "cwd".to_string(), - JsonValue::String(plugin_root.join(cwd).display().to_string()), - ); - } - - object -} - -fn executor_plugin_cwd(plugin_root: &Path, cwd: &str) -> Result { - let path = Path::new(cwd); - if path.is_absolute() { - return Ok(path.to_path_buf()); - } - for component in path.components() { - if matches!( - component, - Component::ParentDir | Component::RootDir | Component::Prefix(_) - ) { - return Err(format!( - "plugin MCP cwd must stay within plugin root: {cwd}" - )); - } - } - Ok(plugin_root.join(path)) -} - -pub fn parse_plugin_mcp_file( - plugin_root: &Path, - mcp_path: &Path, -) -> Result { - let contents = std::fs::read_to_string(mcp_path).map_err(|e| e.to_string())?; - parse_plugin_mcp_config(plugin_root, &contents, PluginMcpServerPlacement::Declared) - .map_err(|e| e.to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_mcp_servers_wrapper() { - let dir = tempfile::tempdir().unwrap(); - let json = r#"{"mcpServers":{"demo":{"command":"echo","args":["hi"]}}}"#; - let outcome = - parse_plugin_mcp_config(dir.path(), json, PluginMcpServerPlacement::Declared).unwrap(); - assert_eq!(outcome.servers.len(), 1); - assert!(outcome.errors.is_empty()); - } - - #[test] - fn parse_flat_server_map() { - let dir = tempfile::tempdir().unwrap(); - let json = r#"{"github":{"command":"npx","args":["-y","pkg"]}}"#; - let outcome = - parse_plugin_mcp_config(dir.path(), json, PluginMcpServerPlacement::Declared).unwrap(); - assert!(outcome.servers.contains_key("github")); - } -} diff --git a/crates/pulsing-forge/src/mcp/resources.rs b/crates/pulsing-forge/src/mcp/resources.rs deleted file mode 100644 index 74c4748a7..000000000 --- a/crates/pulsing-forge/src/mcp/resources.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! MCP resource URI validation and response size limits. - -use rmcp::model::{ReadResourceResult, ResourceContents}; - -/// Max decoded/encoded payload per `read_mcp_resource` response (aligned with `Read` tool cap). -pub const MAX_MCP_RESOURCE_BYTES: usize = 2 * 1024 * 1024; - -const MAX_MCP_RESOURCE_URI_BYTES: usize = 8 * 1024; - -pub fn validate_mcp_resource_uri(uri: &str) -> Result<(), String> { - let trimmed = uri.trim(); - if trimmed.is_empty() { - return Err("uri must be a non-empty string".into()); - } - if trimmed.len() > MAX_MCP_RESOURCE_URI_BYTES { - return Err(format!( - "uri too long: {} bytes (max {MAX_MCP_RESOURCE_URI_BYTES})", - trimmed.len() - )); - } - let parsed = url::Url::parse(trimmed).map_err(|e| format!("invalid uri: {e}"))?; - if parsed.scheme().is_empty() { - return Err("uri must include a scheme (e.g. file://, https://)".into()); - } - Ok(()) -} - -pub fn resource_content_bytes(content: &ResourceContents) -> usize { - match content { - ResourceContents::TextResourceContents { text, .. } => text.len(), - ResourceContents::BlobResourceContents { blob, .. } => blob.len(), - } -} - -pub fn total_resource_bytes(result: &ReadResourceResult) -> usize { - result.contents.iter().map(resource_content_bytes).sum() -} - -pub fn enforce_resource_size_limit( - result: ReadResourceResult, -) -> Result { - let total = total_resource_bytes(&result); - if total > MAX_MCP_RESOURCE_BYTES { - return Err(format!( - "MCP resource content too large: {total} bytes (max {MAX_MCP_RESOURCE_BYTES})" - )); - } - Ok(result) -} - -#[cfg(test)] -mod tests { - use super::*; - use rmcp::model::ReadResourceResult; - - #[test] - fn validate_uri_rejects_empty_and_relative() { - assert!(validate_mcp_resource_uri("").is_err()); - assert!(validate_mcp_resource_uri(" ").is_err()); - assert!(validate_mcp_resource_uri("relative/path").is_err()); - } - - #[test] - fn validate_uri_accepts_common_schemes() { - assert!(validate_mcp_resource_uri("file:///tmp/x").is_ok()); - assert!(validate_mcp_resource_uri("https://example.com/r").is_ok()); - assert!(validate_mcp_resource_uri("mcp://server/resource/1").is_ok()); - } - - #[test] - fn validate_uri_rejects_too_long() { - let long = format!("file:///{}", "a".repeat(8 * 1024)); - let err = validate_mcp_resource_uri(&long).unwrap_err(); - assert!(err.contains("uri too long")); - } - - #[test] - fn enforce_size_limit_rejects_oversized_payload() { - let big = "x".repeat(MAX_MCP_RESOURCE_BYTES + 1); - let result = ReadResourceResult::new(vec![ResourceContents::text(big, "file:///x")]); - let err = enforce_resource_size_limit(result).unwrap_err(); - assert!(err.contains("too large")); - } - - #[test] - fn enforce_size_limit_sums_multiple_contents() { - let half = MAX_MCP_RESOURCE_BYTES / 2 + 1; - let result = ReadResourceResult::new(vec![ - ResourceContents::text("x".repeat(half), "file:///a"), - ResourceContents::text("y".repeat(half), "file:///b"), - ]); - let err = enforce_resource_size_limit(result).unwrap_err(); - assert!(err.contains("too large")); - } - - #[test] - fn enforce_size_limit_counts_blob_bytes() { - let big = "A".repeat(MAX_MCP_RESOURCE_BYTES + 1); - let result = ReadResourceResult::new(vec![ResourceContents::blob(big, "file:///x")]); - let err = enforce_resource_size_limit(result).unwrap_err(); - assert!(err.contains("too large")); - } -} diff --git a/crates/pulsing-forge/src/mcp/tools.rs b/crates/pulsing-forge/src/mcp/tools.rs deleted file mode 100644 index 2273a24c4..000000000 --- a/crates/pulsing-forge/src/mcp/tools.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! MCP tool metadata, filtering, and model-visible name normalization. - -use std::collections::HashSet; - -use rmcp::model::Tool; -use serde::{Deserialize, Serialize}; -use serde_json::{Map, Value}; -use sha1::{Digest, Sha1}; -use tracing::warn; - -use super::LEGACY_MCP_TOOL_NAME_PREFIX; -use super::config::McpServerConfig; - -const MCP_UI_META_KEY: &str = "ui"; -const MCP_UI_VISIBILITY_META_KEY: &str = "visibility"; -const MCP_UI_MODEL_VISIBILITY: &str = "model"; -const MCP_TOOL_NAME_DELIMITER: &str = "__"; -const MAX_TOOL_NAME_BYTES: usize = 64; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ToolInfo { - pub server_name: String, - #[serde(default)] - pub supports_parallel_tool_calls: bool, - #[serde(default)] - pub server_origin: Option, - #[serde(rename = "tool_name", alias = "callable_name")] - pub callable_name: String, - #[serde(rename = "tool_namespace", alias = "callable_namespace")] - pub callable_namespace: String, - #[serde(default, alias = "connector_description")] - pub namespace_description: Option, - pub tool: Tool, - pub connector_id: Option, - pub connector_name: Option, - #[serde(default)] - pub plugin_display_names: Vec, -} - -impl ToolInfo { - pub fn model_tool_name(&self, prefix_mcp_tool_names: bool) -> String { - if prefix_mcp_tool_names { - format!( - "{}{}{}", - self.callable_namespace, MCP_TOOL_NAME_DELIMITER, self.callable_name - ) - } else { - format!("{}/{}", self.callable_namespace, self.callable_name) - } - } -} - -pub fn tool_is_model_visible(tool: &ToolInfo) -> bool { - let Some(visibility) = tool - .tool - .meta - .as_deref() - .and_then(|meta| meta.get(MCP_UI_META_KEY)) - .and_then(Value::as_object) - .and_then(|ui| ui.get(MCP_UI_VISIBILITY_META_KEY)) - .and_then(Value::as_array) - else { - return true; - }; - visibility - .iter() - .any(|t| t.as_str() == Some(MCP_UI_MODEL_VISIBILITY)) -} - -#[derive(Default, Clone)] -pub struct ToolFilter { - enabled: Option>, - disabled: HashSet, -} - -impl ToolFilter { - pub fn from_config(cfg: &McpServerConfig) -> Self { - Self { - enabled: cfg - .enabled_tools - .as_ref() - .map(|t| t.iter().cloned().collect()), - disabled: cfg - .disabled_tools - .as_ref() - .map(|t| t.iter().cloned().collect()) - .unwrap_or_default(), - } - } - - pub fn allows(&self, tool_name: &str) -> bool { - if let Some(enabled) = &self.enabled - && !enabled.contains(tool_name) - { - return false; - } - !self.disabled.contains(tool_name) - } -} - -pub fn filter_tools(tools: Vec, filter: &ToolFilter) -> Vec { - tools - .into_iter() - .filter(|t| filter.allows(&t.tool.name)) - .collect() -} - -pub fn sanitize_responses_api_tool_name(name: &str) -> String { - let mut out = String::with_capacity(name.len()); - for ch in name.chars() { - if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' { - out.push(ch); - } else { - out.push('_'); - } - } - if out.is_empty() { "tool".into() } else { out } -} - -pub fn normalize_tools_for_model(tools: I, prefix_mcp_tool_names: bool) -> Vec -where - I: IntoIterator, -{ - let mut seen_identity = HashSet::new(); - let mut seen_model_names = HashSet::new(); - let mut out = Vec::new(); - for mut tool in tools { - let identity = format!("{}\0{}", tool.server_name, tool.tool.name); - if !seen_identity.insert(identity) { - warn!( - server = %tool.server_name, - tool = %tool.tool.name, - "skipping duplicated MCP tool from same server" - ); - continue; - } - tool.callable_namespace = if prefix_mcp_tool_names { - format!( - "{}{}", - LEGACY_MCP_TOOL_NAME_PREFIX, - sanitize_responses_api_tool_name(&tool.server_name) - ) - } else { - sanitize_responses_api_tool_name(&tool.server_name) - }; - tool.callable_name = sanitize_responses_api_tool_name(&tool.tool.name); - tool.callable_namespace = truncate_to_bytes(&tool.callable_namespace, MAX_TOOL_NAME_BYTES); - tool.callable_name = truncate_to_bytes(&tool.callable_name, MAX_TOOL_NAME_BYTES); - let model_name = tool.model_tool_name(prefix_mcp_tool_names); - if !seen_model_names.insert(model_name) { - warn!( - server = %tool.server_name, - tool = %tool.tool.name, - model_name = %tool.model_tool_name(prefix_mcp_tool_names), - "skipping MCP tool with colliding model-visible name" - ); - continue; - } - out.push(tool); - } - out -} - -fn truncate_to_bytes(s: &str, max: usize) -> String { - if s.len() <= max { - return s.to_string(); - } - let hash = format!("{:x}", Sha1::digest(s.as_bytes())); - let suffix = &hash[..8.min(hash.len())]; - let keep = max.saturating_sub(suffix.len() + 1); - format!( - "{}_{}", - &s[..s.floor_char_boundary(keep.min(s.len()))], - suffix - ) -} - -pub fn tool_spec_for_model(tool: &ToolInfo, prefix_mcp_tool_names: bool) -> Value { - serde_json::json!({ - "name": tool.model_tool_name(prefix_mcp_tool_names), - "description": tool - .tool - .description - .as_ref() - .map(|d| d.to_string()) - .unwrap_or_default(), - "input_schema": tool_input_schema_json(&tool.tool), - "server_name": tool.server_name, - "tool_name": tool.tool.name, - }) -} - -pub fn tool_input_schema_json(tool: &Tool) -> Value { - let mut schema = if tool.input_schema.as_ref().is_empty() { - Map::from_iter([("type".into(), Value::String("object".into()))]) - } else { - tool.input_schema.as_ref().clone() - }; - // OpenAI models require `properties`; some MCP servers omit or null it (Codex parity). - if schema.get("properties").is_none_or(|v| v.is_null()) { - schema.insert("properties".into(), Value::Object(Map::new())); - } - Value::Object(schema) -} - -#[cfg(test)] -mod tests { - use super::*; - use rmcp::model::Tool; - use std::sync::Arc; - - fn sample_tool(name: &str) -> Tool { - Tool::new_with_raw(name.to_string(), None, Arc::new(serde_json::Map::new())) - } - - #[test] - fn tool_input_schema_inserts_empty_properties() { - let tool = sample_tool("no_props"); - let schema = tool_input_schema_json(&tool); - assert_eq!(schema["type"], "object"); - assert!(schema["properties"].is_object()); - } - - #[test] - fn normalize_skips_colliding_model_names() { - let mk = |server: &str| ToolInfo { - server_name: server.into(), - supports_parallel_tool_calls: false, - server_origin: None, - callable_name: "search".into(), - callable_namespace: server.into(), - namespace_description: None, - tool: sample_tool("search"), - connector_id: None, - connector_name: None, - plugin_display_names: vec![], - }; - // Distinct servers, same sanitized namespace → one model-visible name. - let out = normalize_tools_for_model(vec![mk("my.server"), mk("my_server")], true); - assert_eq!(out.len(), 1); - assert_eq!(out[0].model_tool_name(true), "mcp__my_server__search"); - } - - #[test] - fn tool_spec_for_model_includes_properties() { - let mut tool = sample_tool("search"); - tool.description = Some("Search issues".into()); - let info = ToolInfo { - server_name: "github".into(), - supports_parallel_tool_calls: false, - server_origin: None, - callable_name: "search".into(), - callable_namespace: "github".into(), - namespace_description: None, - tool, - connector_id: None, - connector_name: None, - plugin_display_names: vec![], - }; - let out = normalize_tools_for_model(vec![info], true); - let spec = tool_spec_for_model(&out[0], true); - assert_eq!(spec["name"], "mcp__github__search"); - assert_eq!(spec["description"], "Search issues"); - assert!(spec["input_schema"]["properties"].is_object()); - } - - #[test] - fn normalize_adds_mcp_prefix() { - let info = ToolInfo { - server_name: "github".into(), - supports_parallel_tool_calls: false, - server_origin: None, - callable_name: "search".into(), - callable_namespace: "github".into(), - namespace_description: None, - tool: sample_tool("search"), - connector_id: None, - connector_name: None, - plugin_display_names: vec![], - }; - let out = normalize_tools_for_model(vec![info], true); - assert_eq!(out[0].callable_namespace, "mcp__github"); - assert_eq!(out[0].model_tool_name(true), "mcp__github__search"); - } -} diff --git a/crates/pulsing-forge/src/patch/apply.rs b/crates/pulsing-forge/src/patch/apply.rs deleted file mode 100644 index b9302edcc..000000000 --- a/crates/pulsing-forge/src/patch/apply.rs +++ /dev/null @@ -1,267 +0,0 @@ -use std::fs; -use std::io::Write; -use std::path::{Path, PathBuf}; - -use super::parse_patch; -use super::parser::Hunk; -use super::parser::ParseError; -use super::parser::UpdateFileChunk; -use super::seek_sequence; - -#[derive(Debug, thiserror::Error)] -pub enum ApplyPatchError { - #[error(transparent)] - Parse(#[from] ParseError), - #[error("{0}")] - Io(String), - #[error("{0}")] - Apply(String), -} - -pub fn apply_patch_to_fs(patch: &str, cwd: &Path) -> Result { - apply_patch_to_fs_bounded(patch, cwd, cwd) -} - -pub fn apply_patch_to_fs_bounded( - patch: &str, - base: &Path, - root: &Path, -) -> Result { - let args = parse_patch(patch)?; - apply_hunks(&args.hunks, base, root) -} - -fn apply_hunks(hunks: &[Hunk], base: &Path, root: &Path) -> Result { - if hunks.is_empty() { - return Err(ApplyPatchError::Apply("No files were modified.".into())); - } - let mut added = Vec::new(); - let mut modified = Vec::new(); - let mut deleted = Vec::new(); - - for hunk in hunks { - match hunk { - Hunk::AddFile { path, contents, .. } => { - let path = - super::resolve_patch_path(path, base, root).map_err(ApplyPatchError::Apply)?; - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|e| ApplyPatchError::Io(e.to_string()))?; - } - fs::write(&path, contents).map_err(|e| ApplyPatchError::Io(e.to_string()))?; - added.push(path); - } - Hunk::DeleteFile { path, .. } => { - let path = - super::resolve_patch_path(path, base, root).map_err(ApplyPatchError::Apply)?; - if path.is_dir() { - return Err(ApplyPatchError::Apply(format!( - "Refusing to delete directory {}", - path.display() - ))); - } - fs::remove_file(&path).map_err(|e| ApplyPatchError::Io(e.to_string()))?; - deleted.push(path); - } - Hunk::UpdateFile { - path, - move_path, - chunks, - .. - } => { - let path = - super::resolve_patch_path(path, base, root).map_err(ApplyPatchError::Apply)?; - let new_contents = derive_new_contents(&path, chunks)?; - if let Some(dest) = move_path { - let dest_path = super::resolve_patch_path(dest, base, root) - .map_err(ApplyPatchError::Apply)?; - if let Some(parent) = dest_path.parent() { - fs::create_dir_all(parent) - .map_err(|e| ApplyPatchError::Io(e.to_string()))?; - } - fs::write(&dest_path, &new_contents) - .map_err(|e| ApplyPatchError::Io(e.to_string()))?; - fs::remove_file(&path).map_err(|e| ApplyPatchError::Io(e.to_string()))?; - modified.push(dest_path); - } else { - fs::write(&path, &new_contents) - .map_err(|e| ApplyPatchError::Io(e.to_string()))?; - modified.push(path); - } - } - } - } - - let mut out = Vec::new(); - print_summary(&added, &modified, &deleted, &mut out) - .map_err(|e| ApplyPatchError::Io(e.to_string()))?; - Ok(String::from_utf8_lossy(&out).into_owned()) -} - -fn derive_new_contents(path: &Path, chunks: &[UpdateFileChunk]) -> Result { - let original_contents = fs::read_to_string(path) - .map_err(|e| ApplyPatchError::Io(format!("Failed to read {}: {e}", path.display())))?; - let mut original_lines: Vec = original_contents.split('\n').map(String::from).collect(); - if original_lines.last().is_some_and(String::is_empty) { - original_lines.pop(); - } - let replacements = compute_replacements(&original_lines, path, chunks)?; - let mut new_lines = apply_replacements(original_lines, &replacements); - if !new_lines.last().is_some_and(String::is_empty) { - new_lines.push(String::new()); - } - Ok(new_lines.join("\n")) -} - -fn compute_replacements( - original_lines: &[String], - path: &Path, - chunks: &[UpdateFileChunk], -) -> Result)>, ApplyPatchError> { - let mut replacements = Vec::new(); - let mut line_index = 0usize; - for chunk in chunks { - if let Some(ctx_line) = &chunk.change_context { - if let Some(idx) = seek_sequence::seek_sequence( - original_lines, - std::slice::from_ref(ctx_line), - line_index, - false, - ) { - line_index = idx + 1; - } else { - return Err(ApplyPatchError::Apply(format!( - "Failed to find context '{ctx_line}' in {}", - path.display() - ))); - } - } - if chunk.old_lines.is_empty() { - let insertion_idx = if original_lines.last().is_some_and(String::is_empty) { - original_lines.len() - 1 - } else { - original_lines.len() - }; - replacements.push((insertion_idx, 0, chunk.new_lines.clone())); - continue; - } - let mut pattern: &[String] = &chunk.old_lines; - let mut found = - seek_sequence::seek_sequence(original_lines, pattern, line_index, chunk.is_end_of_file); - let mut new_slice: &[String] = &chunk.new_lines; - if found.is_none() && pattern.last().is_some_and(String::is_empty) { - pattern = &pattern[..pattern.len() - 1]; - if new_slice.last().is_some_and(String::is_empty) { - new_slice = &new_slice[..new_slice.len() - 1]; - } - found = seek_sequence::seek_sequence( - original_lines, - pattern, - line_index, - chunk.is_end_of_file, - ); - } - if let Some(start_idx) = found { - replacements.push((start_idx, pattern.len(), new_slice.to_vec())); - line_index = start_idx + pattern.len(); - } else { - return Err(ApplyPatchError::Apply(format!( - "Failed to find expected lines in {}:\n{}", - path.display(), - chunk.old_lines.join("\n") - ))); - } - } - replacements.sort_by_key(|(index, _, _)| *index); - Ok(replacements) -} - -fn apply_replacements( - mut lines: Vec, - replacements: &[(usize, usize, Vec)], -) -> Vec { - for (start_idx, old_len, new_segment) in replacements.iter().rev() { - for _ in 0..*old_len { - if *start_idx < lines.len() { - lines.remove(*start_idx); - } - } - for (offset, new_line) in new_segment.iter().enumerate() { - lines.insert(start_idx + offset, new_line.clone()); - } - } - lines -} - -fn print_summary( - added: &[PathBuf], - modified: &[PathBuf], - deleted: &[PathBuf], - out: &mut Vec, -) -> std::io::Result<()> { - for p in added { - writeln!(out, "A {}", p.display())?; - } - for p in modified { - writeln!(out, "M {}", p.display())?; - } - for p in deleted { - writeln!(out, "D {}", p.display())?; - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn add_file_patch() { - let dir = tempfile::tempdir().unwrap(); - let patch = concat!( - "*** Begin Patch\n", - "*** Add File: hello.txt\n", - "+hello world\n", - "*** End Patch\n" - ); - let summary = apply_patch_to_fs(patch, dir.path()).unwrap(); - assert!(summary.contains("A ")); - assert_eq!( - fs::read_to_string(dir.path().join("hello.txt")).unwrap(), - "hello world\n" - ); - } - - #[test] - fn rejects_path_escape() { - let dir = tempfile::tempdir().unwrap(); - let patch = concat!( - "*** Begin Patch\n", - "*** Add File: ../escape.txt\n", - "+pwned\n", - "*** End Patch\n" - ); - let err = apply_patch_to_fs(patch, dir.path()).unwrap_err(); - assert!(err.to_string().contains("outside working directory")); - assert!(!dir.path().parent().unwrap().join("escape.txt").exists()); - } - - #[test] - #[cfg(unix)] - fn rejects_symlink_escape() { - let dir = tempfile::tempdir().unwrap(); - let workspace = dir.path().join("workspace"); - std::fs::create_dir(&workspace).unwrap(); - let outside = dir.path().join("outside"); - std::fs::create_dir(&outside).unwrap(); - std::os::unix::fs::symlink(&outside, workspace.join("link")).unwrap(); - let patch = concat!( - "*** Begin Patch\n", - "*** Add File: link/pwned.txt\n", - "+escaped\n", - "*** End Patch\n" - ); - let err = apply_patch_to_fs(patch, &workspace).unwrap_err(); - assert!(err.to_string().contains("outside working directory")); - assert!(!outside.join("pwned.txt").exists()); - } -} diff --git a/crates/pulsing-forge/src/patch/heredoc.rs b/crates/pulsing-forge/src/patch/heredoc.rs deleted file mode 100644 index 6a46aca8a..000000000 --- a/crates/pulsing-forge/src/patch/heredoc.rs +++ /dev/null @@ -1,163 +0,0 @@ -//! Tree-sitter bash heredoc extraction for `apply_patch` shell scripts. -//! Ported from codex-apply-patch `invocation.rs` (Apache-2.0). - -use std::str::Utf8Error; -use std::sync::LazyLock; - -use streaming_iterator::StreamingIterator; -use tree_sitter::{LanguageError, Parser, Query, QueryCursor}; -use tree_sitter_bash::LANGUAGE as BASH; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum HeredocError { - CommandDidNotStartWithApplyPatch, - FailedToLoadBashGrammar(String), - HeredocNotUtf8, - FailedToParsePatchIntoAst, -} - -impl From for HeredocError { - fn from(_: Utf8Error) -> Self { - Self::HeredocNotUtf8 - } -} - -static APPLY_PATCH_QUERY: LazyLock = LazyLock::new(|| { - let language: tree_sitter::Language = BASH.into(); - Query::new( - &language, - r#" - ( - program - . (redirected_statement - body: (command - name: (command_name (word) @apply_name) .) - (#any-of? @apply_name "apply_patch" "applypatch") - redirect: (heredoc_redirect - . (heredoc_start) - . (heredoc_body) @heredoc - . (heredoc_end) - .)) - .) - - ( - program - . (redirected_statement - body: (list - . (command - name: (command_name (word) @cd_name) . - argument: [ - (word) @cd_path - (string (string_content) @cd_path) - (raw_string) @cd_raw_string - ] .) - "&&" - . (command - name: (command_name (word) @apply_name)) - .) - (#eq? @cd_name "cd") - (#any-of? @apply_name "apply_patch" "applypatch") - redirect: (heredoc_redirect - . (heredoc_start) - . (heredoc_body) @heredoc - . (heredoc_end) - .)) - .) - "#, - ) - .expect("valid bash query") -}); - -/// Extract heredoc patch body from a `bash -lc` script. -pub fn extract_apply_patch_from_bash(src: &str) -> Result<(String, Option), HeredocError> { - let lang: tree_sitter::Language = BASH.into(); - let mut parser = Parser::new(); - parser - .set_language(&lang) - .map_err(|e: LanguageError| HeredocError::FailedToLoadBashGrammar(e.to_string()))?; - let tree = parser - .parse(src, None) - .ok_or(HeredocError::FailedToParsePatchIntoAst)?; - - let bytes = src.as_bytes(); - let root = tree.root_node(); - let mut cursor = QueryCursor::new(); - let mut matches = cursor.matches(&APPLY_PATCH_QUERY, root, bytes); - while let Some(m) = matches.next() { - let mut heredoc_text: Option = None; - let mut cd_path: Option = None; - - for capture in m.captures.iter() { - let name = APPLY_PATCH_QUERY.capture_names()[capture.index as usize]; - match name { - "heredoc" => { - let text = capture - .node - .utf8_text(bytes) - .map_err(|_| HeredocError::HeredocNotUtf8)? - .trim_end_matches('\n') - .to_string(); - heredoc_text = Some(text); - } - "cd_path" => { - cd_path = Some( - capture - .node - .utf8_text(bytes) - .map_err(|_| HeredocError::HeredocNotUtf8)? - .to_string(), - ); - } - "cd_raw_string" => { - let raw = capture - .node - .utf8_text(bytes) - .map_err(|_| HeredocError::HeredocNotUtf8)?; - let trimmed = raw - .strip_prefix('\'') - .and_then(|s| s.strip_suffix('\'')) - .unwrap_or(raw); - cd_path = Some(trimmed.to_string()); - } - _ => {} - } - } - - if let Some(heredoc) = heredoc_text { - return Ok((heredoc, cd_path)); - } - } - - Err(HeredocError::CommandDidNotStartWithApplyPatch) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn extracts_apply_patch_heredoc() { - let script = - "apply_patch <<'PATCH'\n*** Begin Patch\n*** Add File: foo\n+hi\n*** End Patch\nPATCH"; - let (body, wd) = extract_apply_patch_from_bash(script).unwrap(); - assert!(wd.is_none()); - assert!(body.contains("*** Add File: foo")); - } - - #[test] - fn extracts_cd_and_apply_patch_heredoc() { - let script = "cd subdir && apply_patch <<'PATCH'\n*** Begin Patch\n*** End Patch\nPATCH"; - let (body, wd) = extract_apply_patch_from_bash(script).unwrap(); - assert_eq!(wd.as_deref(), Some("subdir")); - assert!(body.contains("Begin Patch")); - } - - #[test] - fn rejects_unrelated_shell() { - let script = "echo hello && apply_patch foo"; - assert_eq!( - extract_apply_patch_from_bash(script), - Err(HeredocError::CommandDidNotStartWithApplyPatch) - ); - } -} diff --git a/crates/pulsing-forge/src/patch/invocation.rs b/crates/pulsing-forge/src/patch/invocation.rs deleted file mode 100644 index ea6752c07..000000000 --- a/crates/pulsing-forge/src/patch/invocation.rs +++ /dev/null @@ -1,157 +0,0 @@ -//! Detect `apply_patch` in shell argv and verify hunks against the filesystem. - -use std::path::{Path, PathBuf}; - -use crate::patch::heredoc::{HeredocError, extract_apply_patch_from_bash}; -use crate::patch::{ - ApplyPatchArgs, Hunk, ParseError, apply_patch_to_fs_bounded, normalize_lexically, parse_patch, - resolve_patch_path, -}; - -const APPLY_PATCH_COMMANDS: [&str; 2] = ["apply_patch", "applypatch"]; - -#[derive(Debug, Clone, PartialEq)] -pub enum MaybeApplyPatch { - Body(ApplyPatchArgs), - PatchParseError(ParseError), - ShellParseError(String), - ImplicitInvocation, - NotApplyPatch, -} - -/// If `argv` is an apply_patch invocation, return parsed args; else `NotApplyPatch`. -pub fn maybe_parse_apply_patch(argv: &[String]) -> MaybeApplyPatch { - if let [body] = argv - && parse_patch(body).is_ok() - { - return MaybeApplyPatch::ImplicitInvocation; - } - match argv { - [cmd, body] if APPLY_PATCH_COMMANDS.contains(&cmd.as_str()) => match parse_patch(body) { - Ok(mut source) => { - source.patch = body.clone(); - MaybeApplyPatch::Body(source) - } - Err(e) => MaybeApplyPatch::PatchParseError(e), - }, - [shell, flag, script] if is_shell_flag(shell, flag) => { - if parse_patch(script).is_ok() { - return MaybeApplyPatch::ImplicitInvocation; - } - match extract_apply_patch_from_bash(script) { - Ok((body, workdir)) => match parse_patch(&body) { - Ok(mut source) => { - source.patch = body.clone(); - source.workdir = workdir; - MaybeApplyPatch::Body(source) - } - Err(e) => MaybeApplyPatch::PatchParseError(e), - }, - Err(HeredocError::CommandDidNotStartWithApplyPatch) => { - MaybeApplyPatch::NotApplyPatch - } - Err(e) => MaybeApplyPatch::ShellParseError(format!("{e:?}")), - } - } - _ => MaybeApplyPatch::NotApplyPatch, - } -} - -pub fn apply_parsed_patch(args: &ApplyPatchArgs, cwd: &Path) -> Result { - let effective = resolve_effective_cwd(cwd, args.workdir.as_deref())?; - verify_hunks_readable(&args.hunks, &effective, cwd)?; - apply_patch_to_fs_bounded(&args.patch, &effective, cwd).map_err(|e| e.to_string()) -} - -fn resolve_effective_cwd(cwd: &Path, workdir: Option<&str>) -> Result { - match workdir { - Some(w) => resolve_patch_path(Path::new(w), cwd, cwd), - None => Ok(normalize_lexically(cwd)), - } -} - -fn verify_hunks_readable(hunks: &[Hunk], base: &Path, root: &Path) -> Result<(), String> { - for hunk in hunks { - match hunk { - Hunk::AddFile { path, .. } => { - let path = resolve_patch_path(path, base, root)?; - if path.exists() { - return Err(format!( - "add file blocked: {} already exists", - path.display() - )); - } - } - Hunk::DeleteFile { path } => { - let path = resolve_patch_path(path, base, root)?; - if !path.is_file() { - return Err(format!("file not found: {}", path.display())); - } - } - Hunk::UpdateFile { - path, move_path, .. - } => { - let path = resolve_patch_path(path, base, root)?; - if !path.is_file() { - return Err(format!("file not found: {}", path.display())); - } - if let Some(dest) = move_path { - resolve_patch_path(dest, base, root)?; - } - } - } - } - Ok(()) -} - -fn is_shell_flag(shell: &str, flag: &str) -> bool { - let name = Path::new(shell) - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or(shell) - .to_ascii_lowercase(); - matches!(name.as_str(), "sh" | "bash" | "zsh") && matches!(flag, "-c" | "-lc") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn detects_direct_apply_patch_argv() { - let argv = vec![ - "apply_patch".into(), - "*** Begin Patch\n*** End Patch\n".into(), - ]; - assert!(matches!( - maybe_parse_apply_patch(&argv), - MaybeApplyPatch::Body(_) - )); - } - - #[test] - fn detects_bash_heredoc_via_tree_sitter() { - let script = "apply_patch <<'PATCH'\n*** Begin Patch\n*** End Patch\nPATCH"; - let argv = vec!["bash".into(), "-lc".into(), script.into()]; - assert!(matches!( - maybe_parse_apply_patch(&argv), - MaybeApplyPatch::Body(_) - )); - } - - #[test] - fn rejects_workdir_escape() { - let dir = tempfile::tempdir().unwrap(); - let args = ApplyPatchArgs { - hunks: vec![Hunk::AddFile { - path: PathBuf::from("ok.txt"), - contents: "x\n".into(), - }], - patch: String::new(), - workdir: Some("../escape".into()), - environment_id: None, - }; - let err = apply_parsed_patch(&args, dir.path()).unwrap_err(); - assert!(err.contains("outside working directory")); - } -} diff --git a/crates/pulsing-forge/src/patch/mod.rs b/crates/pulsing-forge/src/patch/mod.rs deleted file mode 100644 index 957dd5fc5..000000000 --- a/crates/pulsing-forge/src/patch/mod.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! Codex `apply_patch` format parser + local filesystem apply. -//! Parser adapted from `codex-apply-patch` (Apache-2.0). - -mod apply; -mod heredoc; -mod invocation; -mod parser; -mod seek_sequence; -mod streaming_parser; - -pub use apply::{apply_patch_to_fs, apply_patch_to_fs_bounded}; -pub use invocation::{MaybeApplyPatch, apply_parsed_patch, maybe_parse_apply_patch}; -pub use parser::Hunk; -pub use parser::ParseError; -pub use parser::UpdateFileChunk; -pub use parser::parse_patch; - -use std::path::{Component, Path, PathBuf}; - -#[derive(Debug, Clone, PartialEq)] -pub struct ApplyPatchArgs { - pub hunks: Vec, - pub patch: String, - pub workdir: Option, - pub environment_id: Option, -} - -/// Join `path` against `base`, normalize `.`/`..`, and reject targets outside `root`. -pub(crate) fn resolve_patch_path(path: &Path, base: &Path, root: &Path) -> Result { - let joined = if path.is_absolute() { - path.to_path_buf() - } else { - base.join(path) - }; - let target = normalize_lexically(&joined); - let boundary = normalize_lexically(root); - if !target.starts_with(&boundary) { - return Err(format!( - "refusing to apply patch outside working directory: {} (cwd: {})", - target.display(), - boundary.display() - )); - } - reject_symlink_escape(&target, &boundary)?; - Ok(target) -} - -/// Follow symlinks on the nearest existing ancestor and reject escapes outside `root`. -fn reject_symlink_escape(target: &Path, root: &Path) -> Result<(), String> { - let root_canon = root.canonicalize().map_err(|e| e.to_string())?; - let mut probe = target.to_path_buf(); - loop { - match probe.canonicalize() { - Ok(canon) => { - if !canon.starts_with(&root_canon) { - return Err(format!( - "refusing to apply patch outside working directory: {} (cwd: {})", - target.display(), - root.display() - )); - } - return Ok(()); - } - Err(_) if probe.pop() => continue, - Err(_) => return Ok(()), - } - } -} - -pub(crate) fn resolve_path_against_base(path: &Path, base: &Path) -> Result { - resolve_patch_path(path, base, base) -} - -pub(crate) fn normalize_lexically(path: &Path) -> PathBuf { - let mut out = PathBuf::new(); - for component in path.components() { - match component { - Component::CurDir => {} - Component::ParentDir => match out.components().next_back() { - Some(Component::Normal(_)) => { - out.pop(); - } - _ => out.push(component), - }, - other => out.push(other), - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - use std::fs; - use tempfile::tempdir; - - #[test] - fn rejects_relative_escape_outside_root() { - let root = PathBuf::from("/tmp/workspace"); - let err = resolve_patch_path(Path::new("../escape.txt"), &root, &root).unwrap_err(); - assert!(err.contains("outside working directory")); - } - - #[test] - fn allows_nested_path_within_root() { - let root = tempdir().unwrap(); - let root_path = root.path().to_path_buf(); - fs::create_dir_all(root_path.join("a")).unwrap(); - let got = resolve_patch_path(Path::new("a/b.txt"), &root_path, &root_path).unwrap(); - assert_eq!(got, root_path.join("a/b.txt")); - } - - #[test] - fn allows_parent_hop_within_root_from_subdir() { - let root = tempdir().unwrap(); - let root_path = root.path().to_path_buf(); - let base = root_path.join("subdir"); - fs::create_dir_all(&base).unwrap(); - let got = resolve_patch_path(Path::new("../sibling.txt"), &base, &root_path).unwrap(); - assert_eq!(got, root_path.join("sibling.txt")); - } -} diff --git a/crates/pulsing-forge/src/patch/parser.rs b/crates/pulsing-forge/src/patch/parser.rs deleted file mode 100644 index 4cdadb9de..000000000 --- a/crates/pulsing-forge/src/patch/parser.rs +++ /dev/null @@ -1,253 +0,0 @@ -//! This module is responsible for parsing & validating a patch into a list of "hunks". -//! (It does not attempt to actually check that the patch can be applied to the filesystem.) -//! -//! The official Lark grammar for the apply-patch format is: -//! -//! start: begin_patch environment_id? hunk+ end_patch -//! begin_patch: "*** Begin Patch" LF -//! environment_id: "*** Environment ID: " filename LF -//! end_patch: "*** End Patch" LF? -//! -//! hunk: add_hunk | delete_hunk | update_hunk -//! add_hunk: "*** Add File: " filename LF add_line+ -//! delete_hunk: "*** Delete File: " filename LF -//! update_hunk: "*** Update File: " filename LF change_move? change? -//! filename: /(.+)/ -//! add_line: "+" /(.+)/ LF -> line -//! -//! change_move: "*** Move to: " filename LF -//! change: (change_context | change_line)+ eof_line? -//! change_context: ("@@" | "@@ " /(.+)/) LF -//! change_line: ("+" | "-" | " ") /(.+)/ LF -//! eof_line: "*** End of File" LF -//! -//! The parser below is a little more lenient than the explicit spec and allows for -//! leading/trailing whitespace around patch markers. -use super::ApplyPatchArgs; -use super::resolve_path_against_base; -use super::streaming_parser::StreamingPatchParser; -use std::path::Path; -use std::path::PathBuf; - -use thiserror::Error; - -pub(crate) const BEGIN_PATCH_MARKER: &str = "*** Begin Patch"; -pub(crate) const END_PATCH_MARKER: &str = "*** End Patch"; -pub(crate) const ADD_FILE_MARKER: &str = "*** Add File: "; -pub(crate) const DELETE_FILE_MARKER: &str = "*** Delete File: "; -pub(crate) const UPDATE_FILE_MARKER: &str = "*** Update File: "; -pub(crate) const MOVE_TO_MARKER: &str = "*** Move to: "; -pub(crate) const EOF_MARKER: &str = "*** End of File"; -pub(crate) const CHANGE_CONTEXT_MARKER: &str = "@@ "; -pub(crate) const EMPTY_CHANGE_CONTEXT_MARKER: &str = "@@"; - -/// Currently, the only OpenAI model that knowingly requires lenient parsing is -/// gpt-4.1. While we could try to require everyone to pass in a strictness -/// param when invoking apply_patch, it is a pain to thread it through all of -/// the call sites, so we resign ourselves allowing lenient parsing for all -/// models. See [`ParseMode::Lenient`] for details on the exceptions we make for -/// gpt-4.1. -const PARSE_IN_STRICT_MODE: bool = false; - -#[derive(Debug, PartialEq, Error, Clone)] -pub enum ParseError { - #[error("invalid patch: {0}")] - InvalidPatchError(String), - #[error("invalid hunk at line {line_number}, {message}")] - InvalidHunkError { message: String, line_number: usize }, -} -use ParseError::*; - -#[derive(Debug, PartialEq, Clone)] -#[allow(clippy::enum_variant_names)] -pub enum Hunk { - AddFile { - path: PathBuf, - contents: String, - }, - DeleteFile { - path: PathBuf, - }, - UpdateFile { - path: PathBuf, - move_path: Option, - - /// Chunks should be in order, i.e. the `change_context` of one chunk - /// should occur later in the file than the previous chunk. - chunks: Vec, - }, -} - -impl Hunk { - pub fn resolve_path(&self, cwd: &Path) -> Result { - let path = match self { - Hunk::UpdateFile { path, .. } => path, - Hunk::AddFile { .. } | Hunk::DeleteFile { .. } => self.path(), - }; - resolve_path_against_base(path, cwd) - } - - /// Returns the path affected by this hunk, using the move destination for rename hunks. - pub fn path(&self) -> &Path { - match self { - Hunk::AddFile { path, .. } => path, - Hunk::DeleteFile { path } => path, - Hunk::UpdateFile { - move_path: Some(path), - .. - } => path, - Hunk::UpdateFile { - path, - move_path: None, - .. - } => path, - } - } -} - -#[derive(Debug, PartialEq, Clone)] -pub struct UpdateFileChunk { - /// A single line of context used to narrow down the position of the chunk - /// (this is usually a class, method, or function definition.) - pub change_context: Option, - - /// A contiguous block of lines that should be replaced with `new_lines`. - /// `old_lines` must occur strictly after `change_context`. - pub old_lines: Vec, - pub new_lines: Vec, - - /// If set to true, `old_lines` must occur at the end of the source file. - /// (Tolerance around trailing newlines should be encouraged.) - pub is_end_of_file: bool, -} - -pub fn parse_patch(patch: &str) -> Result { - let mode = if PARSE_IN_STRICT_MODE { - ParseMode::Strict - } else { - ParseMode::Lenient - }; - parse_patch_text(patch, mode) -} - -enum ParseMode { - /// Parse the patch text argument as is. - Strict, - - /// GPT-4.1 is known to formulate the `command` array for the `local_shell` - /// tool call for `apply_patch` call using something like the following: - /// - /// ```json - /// [ - /// "apply_patch", - /// "<<'EOF'\n*** Begin Patch\n*** Update File: README.md\n@@...\n*** End Patch\nEOF\n", - /// ] - /// ``` - /// - /// This is a problem because `local_shell` is a bit of a misnomer: the - /// `command` is not invoked by passing the arguments to a shell like Bash, - /// but are invoked using something akin to `execvpe(3)`. - /// - /// This is significant in this case because where a shell would interpret - /// `<<'EOF'...` as a heredoc and pass the contents via stdin (which is - /// fine, as `apply_patch` is specified to read from stdin if no argument is - /// passed), `execvpe(3)` interprets the heredoc as a literal string. To get - /// the `local_shell` tool to run a command the way shell would, the - /// `command` array must be something like: - /// - /// ```json - /// [ - /// "bash", - /// "-lc", - /// "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: README.md\n@@...\n*** End Patch\nEOF\n", - /// ] - /// ``` - /// - /// In lenient mode, we check if the argument to `apply_patch` starts with - /// `<<'EOF'` and ends with `EOF\n`. If so, we strip off these markers, - /// trim() the result, and treat what is left as the patch text. - Lenient, -} - -fn parse_patch_text(patch: &str, mode: ParseMode) -> Result { - let lines: Vec<&str> = patch.trim().lines().collect(); - let patch_lines = match mode { - ParseMode::Strict => check_patch_boundaries_strict(&lines)?, - ParseMode::Lenient => check_patch_boundaries_lenient(&lines)?, - }; - - let patch = patch_lines.join("\n"); - let mut parser = StreamingPatchParser::default(); - parser.push_delta(&patch)?; - let hunks = parser.finish()?; - let environment_id = parser.environment_id().map(str::to_owned); - Ok(ApplyPatchArgs { - hunks, - patch, - workdir: None, - environment_id, - }) -} - -/// Checks the start and end lines of the patch text for `apply_patch`, -/// returning an error if they do not match the expected markers. -fn check_patch_boundaries_strict<'a>(lines: &'a [&'a str]) -> Result<&'a [&'a str], ParseError> { - let (first_line, last_line) = match lines { - [] => (None, None), - [first] => (Some(first), Some(first)), - [first, .., last] => (Some(first), Some(last)), - }; - check_start_and_end_lines_strict(first_line, last_line)?; - Ok(lines) -} - -/// If we are in lenient mode, we check if the first line starts with `<( - original_lines: &'a [&'a str], -) -> Result<&'a [&'a str], ParseError> { - let original_parse_error = match check_patch_boundaries_strict(original_lines) { - Ok(lines) => return Ok(lines), - Err(e) => e, - }; - - match original_lines { - [first, .., last] => { - if (first == &"<= 4 - { - let inner_lines = &original_lines[1..original_lines.len() - 1]; - check_patch_boundaries_strict(inner_lines) - } else { - Err(original_parse_error) - } - } - _ => Err(original_parse_error), - } -} - -fn check_start_and_end_lines_strict( - first_line: Option<&&str>, - last_line: Option<&&str>, -) -> Result<(), ParseError> { - let first_line = first_line.map(|line| line.trim()); - let last_line = last_line.map(|line| line.trim()); - - match (first_line, last_line) { - (Some(first), Some(last)) if first == BEGIN_PATCH_MARKER && last == END_PATCH_MARKER => { - Ok(()) - } - (Some(first), _) if first != BEGIN_PATCH_MARKER => Err(InvalidPatchError(String::from( - "The first line of the patch must be '*** Begin Patch'", - ))), - _ => Err(InvalidPatchError(String::from( - "The last line of the patch must be '*** End Patch'", - ))), - } -} diff --git a/crates/pulsing-forge/src/patch/seek_sequence.rs b/crates/pulsing-forge/src/patch/seek_sequence.rs deleted file mode 100644 index c98e8fb4d..000000000 --- a/crates/pulsing-forge/src/patch/seek_sequence.rs +++ /dev/null @@ -1,110 +0,0 @@ -/// Attempt to find the sequence of `pattern` lines within `lines` beginning at or after `start`. -/// Returns the starting index of the match or `None` if not found. Matches are attempted with -/// decreasing strictness: exact match, then ignoring trailing whitespace, then ignoring leading -/// and trailing whitespace. When `eof` is true, we first try starting at the end-of-file (so that -/// patterns intended to match file endings are applied at the end), and fall back to searching -/// from `start` if needed. -/// -/// Special cases handled defensively: -/// • Empty `pattern` → returns `Some(start)` (no-op match) -/// • `pattern.len() > lines.len()` → returns `None` (cannot match, avoids -/// out‑of‑bounds panic that occurred pre‑2025‑04‑12) -pub(crate) fn seek_sequence( - lines: &[String], - pattern: &[String], - start: usize, - eof: bool, -) -> Option { - if pattern.is_empty() { - return Some(start); - } - - // When the pattern is longer than the available input there is no possible - // match. Early‑return to avoid the out‑of‑bounds slice that would occur in - // the search loops below (previously caused a panic when - // `pattern.len() > lines.len()`). - if pattern.len() > lines.len() { - return None; - } - let search_start = if eof && lines.len() >= pattern.len() { - lines.len() - pattern.len() - } else { - start - }; - // Exact match first. - for i in search_start..=lines.len().saturating_sub(pattern.len()) { - if lines[i..i + pattern.len()] == *pattern { - return Some(i); - } - } - // Then rstrip match. - for i in search_start..=lines.len().saturating_sub(pattern.len()) { - let mut ok = true; - for (p_idx, pat) in pattern.iter().enumerate() { - if lines[i + p_idx].trim_end() != pat.trim_end() { - ok = false; - break; - } - } - if ok { - return Some(i); - } - } - // Finally, trim both sides to allow more lenience. - for i in search_start..=lines.len().saturating_sub(pattern.len()) { - let mut ok = true; - for (p_idx, pat) in pattern.iter().enumerate() { - if lines[i + p_idx].trim() != pat.trim() { - ok = false; - break; - } - } - if ok { - return Some(i); - } - } - - // ------------------------------------------------------------------ - // Final, most permissive pass – attempt to match after *normalising* - // common Unicode punctuation to their ASCII equivalents so that diffs - // authored with plain ASCII characters can still be applied to source - // files that contain typographic dashes / quotes, etc. This mirrors the - // fuzzy behaviour of `git apply` which ignores minor byte-level - // differences when locating context lines. - // ------------------------------------------------------------------ - - fn normalise(s: &str) -> String { - s.trim() - .chars() - .map(|c| match c { - // Various dash / hyphen code-points → ASCII '-' - '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}' - | '\u{2212}' => '-', - // Fancy single quotes → '\'' - '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' => '\'', - // Fancy double quotes → '"' - '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' => '"', - // Non-breaking space and other odd spaces → normal space - '\u{00A0}' | '\u{2002}' | '\u{2003}' | '\u{2004}' | '\u{2005}' | '\u{2006}' - | '\u{2007}' | '\u{2008}' | '\u{2009}' | '\u{200A}' | '\u{202F}' | '\u{205F}' - | '\u{3000}' => ' ', - other => other, - }) - .collect::() - } - - for i in search_start..=lines.len().saturating_sub(pattern.len()) { - let mut ok = true; - for (p_idx, pat) in pattern.iter().enumerate() { - if normalise(&lines[i + p_idx]) != normalise(pat) { - ok = false; - break; - } - } - if ok { - return Some(i); - } - } - - None -} diff --git a/crates/pulsing-forge/src/patch/streaming_parser.rs b/crates/pulsing-forge/src/patch/streaming_parser.rs deleted file mode 100644 index 449fc52a9..000000000 --- a/crates/pulsing-forge/src/patch/streaming_parser.rs +++ /dev/null @@ -1,409 +0,0 @@ -use std::path::PathBuf; - -use super::parser::ADD_FILE_MARKER; -use super::parser::BEGIN_PATCH_MARKER; -use super::parser::CHANGE_CONTEXT_MARKER; -use super::parser::DELETE_FILE_MARKER; -use super::parser::EMPTY_CHANGE_CONTEXT_MARKER; -use super::parser::END_PATCH_MARKER; -use super::parser::EOF_MARKER; -use super::parser::Hunk; -use super::parser::MOVE_TO_MARKER; -use super::parser::ParseError; -use super::parser::UPDATE_FILE_MARKER; -use super::parser::UpdateFileChunk; - -use Hunk::*; -use ParseError::*; - -const ENVIRONMENT_ID_MARKER: &str = "*** Environment ID:"; - -#[derive(Debug, Default, Clone)] -pub struct StreamingPatchParser { - line_buffer: String, - state: StreamingParserState, - line_number: usize, -} - -#[derive(Debug, Default, Clone)] -struct StreamingParserState { - mode: StreamingParserMode, - hunks: Vec, - environment_id: Option, -} - -#[derive(Debug, Default, Clone, Copy)] -enum StreamingParserMode { - #[default] - NotStarted, - StartedPatch, - AddFile, - DeleteFile, - UpdateFile { - hunk_line_number: usize, - }, - EndedPatch, -} - -impl StreamingPatchParser { - pub fn environment_id(&self) -> Option<&str> { - self.state.environment_id.as_deref() - } - - fn ensure_update_hunk_is_not_empty(&self, line: &str) -> Result<(), ParseError> { - if let Some(UpdateFile { path, chunks, .. }) = self.state.hunks.last() { - if chunks.is_empty() - && let StreamingParserMode::UpdateFile { hunk_line_number } = self.state.mode - { - return Err(InvalidHunkError { - message: format!("Update file hunk for path '{}' is empty", path.display()), - line_number: hunk_line_number, - }); - } - if chunks - .last() - .is_some_and(|chunk| chunk.old_lines.is_empty() && chunk.new_lines.is_empty()) - { - if line == END_PATCH_MARKER { - return Err(InvalidHunkError { - message: "Update hunk does not contain any lines".to_string(), - line_number: self.line_number, - }); - } - return Err(InvalidHunkError { - message: format!( - "Unexpected line found in update hunk: '{line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)" - ), - line_number: self.line_number, - }); - } - } - Ok(()) - } - - fn handle_hunk_headers_and_end_patch(&mut self, trimmed: &str) -> Result { - if matches!(self.state.mode, StreamingParserMode::StartedPatch) - && let Some(environment_id) = trimmed.strip_prefix(ENVIRONMENT_ID_MARKER) - { - if self.state.environment_id.is_some() { - return Err(InvalidPatchError( - "apply_patch environment_id cannot be specified more than once".to_string(), - )); - } - let environment_id = environment_id.trim(); - if environment_id.is_empty() { - return Err(InvalidPatchError( - "apply_patch environment_id cannot be empty".to_string(), - )); - } - self.state.environment_id = Some(environment_id.to_string()); - return Ok(true); - } - if trimmed == END_PATCH_MARKER { - self.ensure_update_hunk_is_not_empty(trimmed)?; - self.state.mode = StreamingParserMode::EndedPatch; - return Ok(true); - } - if let Some(path) = trimmed.strip_prefix(ADD_FILE_MARKER) { - self.ensure_update_hunk_is_not_empty(trimmed)?; - self.state.hunks.push(AddFile { - path: PathBuf::from(path), - contents: String::new(), - }); - self.state.mode = StreamingParserMode::AddFile; - return Ok(true); - } - if let Some(path) = trimmed.strip_prefix(DELETE_FILE_MARKER) { - self.ensure_update_hunk_is_not_empty(trimmed)?; - self.state.hunks.push(DeleteFile { - path: PathBuf::from(path), - }); - self.state.mode = StreamingParserMode::DeleteFile; - return Ok(true); - } - if let Some(path) = trimmed.strip_prefix(UPDATE_FILE_MARKER) { - self.ensure_update_hunk_is_not_empty(trimmed)?; - self.state.hunks.push(UpdateFile { - path: PathBuf::from(path), - move_path: None, - chunks: Vec::new(), - }); - self.state.mode = StreamingParserMode::UpdateFile { - hunk_line_number: self.line_number, - }; - return Ok(true); - } - Ok(false) - } - - pub fn push_delta(&mut self, delta: &str) -> Result, ParseError> { - for ch in delta.chars() { - if ch == '\n' { - let mut line = std::mem::take(&mut self.line_buffer); - line.truncate(line.strip_suffix('\r').map_or(line.len(), str::len)); - self.line_number += 1; - self.process_line(&line)?; - } else { - self.line_buffer.push(ch); - } - } - - Ok(self.state.hunks.clone()) - } - - pub fn finish(&mut self) -> Result, ParseError> { - if !self.line_buffer.is_empty() { - let line = std::mem::take(&mut self.line_buffer); - self.line_number += 1; - if line.trim() == END_PATCH_MARKER { - self.ensure_update_hunk_is_not_empty(line.trim())?; - self.state.mode = StreamingParserMode::EndedPatch; - } else { - self.process_line(&line)?; - } - } - - if !matches!(self.state.mode, StreamingParserMode::EndedPatch) { - return Err(InvalidPatchError( - "The last line of the patch must be '*** End Patch'".to_string(), - )); - } - - Ok(self.state.hunks.clone()) - } - - fn process_line(&mut self, line: &str) -> Result<(), ParseError> { - let trimmed = line.trim(); - match self.state.mode { - StreamingParserMode::NotStarted => { - if trimmed == BEGIN_PATCH_MARKER { - self.state.mode = StreamingParserMode::StartedPatch; - return Ok(()); - } - Err(InvalidPatchError( - "The first line of the patch must be '*** Begin Patch'".to_string(), - )) - } - StreamingParserMode::StartedPatch => { - if self.handle_hunk_headers_and_end_patch(trimmed)? { - return Ok(()); - } - Err(InvalidHunkError { - message: format!( - "'{trimmed}' is not a valid hunk header. Valid hunk headers: '*** Add File: {{path}}', '*** Delete File: {{path}}', '*** Update File: {{path}}'" - ), - line_number: self.line_number, - }) - } - StreamingParserMode::AddFile => { - if self.handle_hunk_headers_and_end_patch(trimmed)? { - return Ok(()); - } - if let Some(line_to_add) = line.strip_prefix('+') - && let Some(AddFile { contents, .. }) = self.state.hunks.last_mut() - { - contents.push_str(line_to_add); - contents.push('\n'); - return Ok(()); - } - Err(InvalidHunkError { - message: format!( - "'{trimmed}' is not a valid hunk header. Valid hunk headers: '*** Add File: {{path}}', '*** Delete File: {{path}}', '*** Update File: {{path}}'" - ), - line_number: self.line_number, - }) - } - StreamingParserMode::DeleteFile => { - if self.handle_hunk_headers_and_end_patch(trimmed)? { - return Ok(()); - } - Err(InvalidHunkError { - message: format!( - "'{trimmed}' is not a valid hunk header. Valid hunk headers: '*** Add File: {{path}}', '*** Delete File: {{path}}', '*** Update File: {{path}}'" - ), - line_number: self.line_number, - }) - } - StreamingParserMode::UpdateFile { hunk_line_number } => { - let update_line = line.trim_end(); - if self.handle_hunk_headers_and_end_patch(update_line)? { - return Ok(()); - } - - if let Some(UpdateFile { - move_path, chunks, .. - }) = self.state.hunks.last_mut() - { - if chunks.last().is_some_and(|chunk| chunk.is_end_of_file) { - if update_line.is_empty() { - return Ok(()); - } - if update_line != EMPTY_CHANGE_CONTEXT_MARKER - && !update_line.starts_with(CHANGE_CONTEXT_MARKER) - { - return Err(InvalidHunkError { - message: format!( - "Expected update hunk to start with a @@ context marker, got: '{line}'" - ), - line_number: self.line_number, - }); - } - } - - if chunks.is_empty() - && move_path.is_none() - && let Some(move_to_path) = update_line.strip_prefix(MOVE_TO_MARKER) - { - *move_path = Some(PathBuf::from(move_to_path)); - self.state.mode = StreamingParserMode::UpdateFile { hunk_line_number }; - return Ok(()); - } - - if (update_line == EMPTY_CHANGE_CONTEXT_MARKER - || update_line.starts_with(CHANGE_CONTEXT_MARKER)) - && chunks.last().is_some_and(|chunk| { - chunk.old_lines.is_empty() && chunk.new_lines.is_empty() - }) - { - return Err(InvalidHunkError { - message: format!( - "Unexpected line found in update hunk: '{line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)" - ), - line_number: self.line_number, - }); - } - - if update_line == EMPTY_CHANGE_CONTEXT_MARKER { - chunks.push(UpdateFileChunk { - change_context: None, - old_lines: Vec::new(), - new_lines: Vec::new(), - is_end_of_file: false, - }); - self.state.mode = StreamingParserMode::UpdateFile { hunk_line_number }; - return Ok(()); - } - - if let Some(change_context) = update_line.strip_prefix(CHANGE_CONTEXT_MARKER) { - chunks.push(UpdateFileChunk { - change_context: Some(change_context.to_string()), - old_lines: Vec::new(), - new_lines: Vec::new(), - is_end_of_file: false, - }); - self.state.mode = StreamingParserMode::UpdateFile { hunk_line_number }; - return Ok(()); - } - - if update_line == EOF_MARKER { - if chunks.last().is_some_and(|chunk| { - chunk.old_lines.is_empty() && chunk.new_lines.is_empty() - }) { - return Err(InvalidHunkError { - message: "Update hunk does not contain any lines".to_string(), - line_number: self.line_number, - }); - } - if let Some(chunk) = chunks.last_mut() { - chunk.is_end_of_file = true; - } - self.state.mode = StreamingParserMode::UpdateFile { hunk_line_number }; - return Ok(()); - } - - if line.is_empty() { - if chunks.is_empty() { - chunks.push(UpdateFileChunk { - change_context: None, - old_lines: Vec::new(), - new_lines: Vec::new(), - is_end_of_file: false, - }); - } - if let Some(chunk) = chunks.last_mut() { - chunk.old_lines.push(String::new()); - chunk.new_lines.push(String::new()); - } - self.state.mode = StreamingParserMode::UpdateFile { hunk_line_number }; - return Ok(()); - } - - if let Some(line_to_add) = line.strip_prefix(' ') { - if chunks.is_empty() { - chunks.push(UpdateFileChunk { - change_context: None, - old_lines: Vec::new(), - new_lines: Vec::new(), - is_end_of_file: false, - }); - } - if let Some(chunk) = chunks.last_mut() { - chunk.old_lines.push(line_to_add.to_string()); - chunk.new_lines.push(line_to_add.to_string()); - } - self.state.mode = StreamingParserMode::UpdateFile { hunk_line_number }; - return Ok(()); - } - - if let Some(line_to_add) = line.strip_prefix('+') { - if chunks.is_empty() { - chunks.push(UpdateFileChunk { - change_context: None, - old_lines: Vec::new(), - new_lines: Vec::new(), - is_end_of_file: false, - }); - } - if let Some(chunk) = chunks.last_mut() { - chunk.new_lines.push(line_to_add.to_string()); - } - self.state.mode = StreamingParserMode::UpdateFile { hunk_line_number }; - return Ok(()); - } - - if let Some(line_to_remove) = line.strip_prefix('-') { - if chunks.is_empty() { - chunks.push(UpdateFileChunk { - change_context: None, - old_lines: Vec::new(), - new_lines: Vec::new(), - is_end_of_file: false, - }); - } - if let Some(chunk) = chunks.last_mut() { - chunk.old_lines.push(line_to_remove.to_string()); - } - self.state.mode = StreamingParserMode::UpdateFile { hunk_line_number }; - return Ok(()); - } - - if chunks.last().is_some_and(|chunk| { - !chunk.old_lines.is_empty() || !chunk.new_lines.is_empty() - }) { - return Err(InvalidHunkError { - message: format!( - "Expected update hunk to start with a @@ context marker, got: '{line}'" - ), - line_number: self.line_number, - }); - } - } - Err(InvalidHunkError { - message: format!( - "Unexpected line found in update hunk: '{line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)" - ), - line_number: self.line_number, - }) - } - StreamingParserMode::EndedPatch => { - if trimmed.is_empty() { - Ok(()) - } else { - Err(InvalidPatchError( - "The last line of the patch must be '*** End Patch'".to_string(), - )) - } - } - } - } -} diff --git a/crates/pulsing-forge/src/process_group.rs b/crates/pulsing-forge/src/process_group.rs deleted file mode 100644 index a8f6bb6e1..000000000 --- a/crates/pulsing-forge/src/process_group.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Small cross-platform helpers for containing shell process trees. - -#[cfg(unix)] -pub fn configure(command: &mut tokio::process::Command) { - use std::os::unix::process::CommandExt; - command.as_std_mut().process_group(0); -} - -#[cfg(not(unix))] -pub fn configure(_command: &mut tokio::process::Command) {} - -#[cfg(unix)] -pub fn kill(process_id: u32) { - // A negative pid targets the process group created with process_group(0). - unsafe { - libc::kill(-(process_id as i32), libc::SIGKILL); - } -} - -#[cfg(not(unix))] -pub fn kill(_process_id: u32) {} - -pub struct ProcessGroupGuard { - process_id: Option, -} - -impl ProcessGroupGuard { - pub fn new(process_id: Option) -> Self { - Self { process_id } - } - - pub fn disarm(&mut self) { - self.process_id = None; - } - - pub fn kill_now(&self) { - if let Some(process_id) = self.process_id { - kill(process_id); - } - } -} - -impl Drop for ProcessGroupGuard { - fn drop(&mut self) { - if let Some(process_id) = self.process_id { - kill(process_id); - } - } -} diff --git a/crates/pulsing-forge/src/protocol/command.rs b/crates/pulsing-forge/src/protocol/command.rs deleted file mode 100644 index cb374b22c..000000000 --- a/crates/pulsing-forge/src/protocol/command.rs +++ /dev/null @@ -1,105 +0,0 @@ -use std::path::PathBuf; - -use serde::{Deserialize, Serialize}; - -use super::{CommandId, ProtocolVersion, SessionId, TurnId}; -use crate::agent::AgentConfig; -use crate::approval::ApprovalPolicy; - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SessionSpec { - pub cwd: PathBuf, - pub provider: String, - pub model: String, - pub max_tokens: u32, - pub max_turns: usize, - pub sandbox: String, - #[serde(default)] - pub approval_policy: ApprovalPolicy, - pub tool_names: Vec, - pub system_prompt: Option, -} - -impl From for SessionSpec { - fn from(value: AgentConfig) -> Self { - Self { - cwd: value.cwd, - provider: value.provider, - model: value.model, - max_tokens: value.max_tokens, - max_turns: value.max_turns, - sandbox: value.sandbox, - approval_policy: value.approval_policy, - tool_names: value.tool_names, - system_prompt: value.system_prompt, - } - } -} - -impl From for AgentConfig { - fn from(value: SessionSpec) -> Self { - Self { - cwd: value.cwd, - provider: value.provider, - model: value.model, - max_tokens: value.max_tokens, - max_turns: value.max_turns, - sandbox: value.sandbox, - approval_policy: value.approval_policy, - tool_names: value.tool_names, - system_prompt: value.system_prompt, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CommandEnvelope { - pub protocol: String, - pub version: ProtocolVersion, - pub command_id: CommandId, - pub session_id: SessionId, - pub expected_seq: Option, - pub payload: T, -} - -impl CommandEnvelope { - pub fn new(command_id: CommandId, session_id: SessionId, payload: T) -> Self { - Self { - protocol: "forge.session".into(), - version: ProtocolVersion::V1, - command_id, - session_id, - expected_seq: None, - payload, - } - } - - pub fn expecting(mut self, seq: u64) -> Self { - self.expected_seq = Some(seq); - self - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CreateSession { - pub spec: SessionSpec, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct StartTurn { - pub turn_id: TurnId, - pub input: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CancelTurn { - pub turn_id: TurnId, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CommandReceipt { - pub command_id: CommandId, - pub session_id: SessionId, - pub turn_id: Option, - pub accepted_seq: u64, -} diff --git a/crates/pulsing-forge/src/protocol/error.rs b/crates/pulsing-forge/src/protocol/error.rs deleted file mode 100644 index 8e5948d37..000000000 --- a/crates/pulsing-forge/src/protocol/error.rs +++ /dev/null @@ -1,36 +0,0 @@ -use thiserror::Error; - -use super::{SessionId, TurnId}; - -#[derive(Debug, Clone, Error, PartialEq, Eq)] -pub enum ForgeProtocolError { - #[error("session not found: {0}")] - SessionNotFound(SessionId), - #[error("session already exists: {0}")] - SessionAlreadyExists(SessionId), - #[error("session is closed: {0}")] - SessionClosed(SessionId), - #[error("session already has an active turn: {0}")] - SessionBusy(SessionId), - #[error("turn is not active: {0}")] - TurnNotActive(TurnId), - #[error("event sequence conflict: expected {expected}, actual {actual}")] - SequenceConflict { expected: u64, actual: u64 }, - #[error("invalid state transition: {0}")] - InvalidTransition(String), - #[error("event subscription lagged by {0} events")] - SubscriptionLagged(u64), - #[error("event subscription closed")] - SubscriptionClosed, - #[error("invalid protocol: expected {expected}, got {actual}")] - InvalidProtocol { - expected: &'static str, - actual: String, - }, - #[error("unsupported {protocol} protocol major version {major}")] - UnsupportedVersion { protocol: String, major: u16 }, - #[error("agent task failed: {0}")] - Agent(String), - #[error("internal Forge error: {0}")] - Internal(String), -} diff --git a/crates/pulsing-forge/src/protocol/event.rs b/crates/pulsing-forge/src/protocol/event.rs deleted file mode 100644 index aed619ec9..000000000 --- a/crates/pulsing-forge/src/protocol/event.rs +++ /dev/null @@ -1,112 +0,0 @@ -use chrono::{DateTime, Utc}; -use serde::{Deserialize, Serialize}; - -use super::{CommandId, EventId, SessionId, TurnId}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub struct ProtocolVersion { - pub major: u16, - pub minor: u16, -} - -impl ProtocolVersion { - pub const V1: Self = Self { major: 1, minor: 0 }; -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", content = "payload", rename_all = "snake_case")] -pub enum ForgeEventKind { - SessionCreated, - SessionClosed, - TurnStarted { - input: String, - }, - TurnOutputDelta { - delta: String, - }, - TurnCancelRequested, - TurnCleanupStalled { - resources: Vec, - }, - TurnCancelled, - TurnCompleted { - text: String, - }, - TurnFailed { - message: String, - }, - ToolStarted { - name: String, - }, - ToolCompleted { - name: String, - ok: bool, - summary: String, - }, - ToolCancelled { - name: String, - }, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct ForgeEvent { - pub protocol: String, - pub version: ProtocolVersion, - pub event_id: EventId, - pub session_id: SessionId, - pub seq: u64, - pub occurred_at: DateTime, - pub turn_id: Option, - pub causation_id: Option, - #[serde(flatten)] - pub kind: ForgeEventKind, -} - -impl ForgeEvent { - pub fn new( - session_id: SessionId, - seq: u64, - turn_id: Option, - causation_id: Option, - kind: ForgeEventKind, - ) -> Self { - Self { - protocol: "forge.event".into(), - version: ProtocolVersion::V1, - event_id: EventId::new(), - session_id, - seq, - occurred_at: Utc::now(), - turn_id, - causation_id, - kind, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn event_kind_is_flattened_into_the_versioned_envelope() { - let event = ForgeEvent::new( - SessionId::from_string("session-1"), - 7, - Some(TurnId::from_string("turn-1")), - None, - ForgeEventKind::TurnOutputDelta { - delta: "hello".into(), - }, - ); - - let value = serde_json::to_value(&event).expect("serialize event"); - assert_eq!(value["protocol"], "forge.event"); - assert_eq!(value["version"]["major"], 1); - assert_eq!(value["kind"], "turn_output_delta"); - assert_eq!(value["payload"]["delta"], "hello"); - - let decoded: ForgeEvent = serde_json::from_value(value).expect("deserialize event"); - assert_eq!(decoded, event); - } -} diff --git a/crates/pulsing-forge/src/protocol/ids.rs b/crates/pulsing-forge/src/protocol/ids.rs deleted file mode 100644 index 2586a247a..000000000 --- a/crates/pulsing-forge/src/protocol/ids.rs +++ /dev/null @@ -1,58 +0,0 @@ -use std::fmt; - -use serde::{Deserialize, Serialize}; -use uuid::Uuid; - -macro_rules! opaque_id { - ($name:ident, $prefix:literal) => { - #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] - #[serde(transparent)] - pub struct $name(String); - - impl $name { - pub fn new() -> Self { - Self(format!("{}_{}", $prefix, Uuid::new_v4().simple())) - } - - pub fn from_string(value: impl Into) -> Self { - Self(value.into()) - } - - pub fn as_str(&self) -> &str { - &self.0 - } - } - - impl Default for $name { - fn default() -> Self { - Self::new() - } - } - - impl fmt::Display for $name { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0.fmt(f) - } - } - }; -} - -opaque_id!(SessionId, "ses"); -opaque_id!(TurnId, "turn"); -opaque_id!(EventId, "evt"); -opaque_id!(CommandId, "cmd"); -opaque_id!(CandidateId, "cand"); - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ids_are_opaque_and_round_trip() { - let id = SessionId::new(); - let encoded = serde_json::to_string(&id).unwrap(); - let decoded: SessionId = serde_json::from_str(&encoded).unwrap(); - assert_eq!(decoded, id); - assert!(id.as_str().starts_with("ses_")); - } -} diff --git a/crates/pulsing-forge/src/protocol/mod.rs b/crates/pulsing-forge/src/protocol/mod.rs deleted file mode 100644 index 408a48ec4..000000000 --- a/crates/pulsing-forge/src/protocol/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! Versioned Forge command and event protocol. - -mod command; -mod error; -mod event; -mod ids; - -pub use command::{ - CancelTurn, CommandEnvelope, CommandReceipt, CreateSession, SessionSpec, StartTurn, -}; -pub use error::ForgeProtocolError; -pub use event::{ForgeEvent, ForgeEventKind, ProtocolVersion}; -pub use ids::{CandidateId, CommandId, EventId, SessionId, TurnId}; diff --git a/crates/pulsing-forge/src/pty_session.rs b/crates/pulsing-forge/src/pty_session.rs deleted file mode 100644 index 12550a548..000000000 --- a/crates/pulsing-forge/src/pty_session.rs +++ /dev/null @@ -1,268 +0,0 @@ -//! PTY-backed exec session (portable-pty). - -use std::io::{Read, Write}; -use std::path::Path; -use std::sync::atomic::{AtomicI32, Ordering}; -use std::sync::{Arc, Mutex, mpsc}; -use std::thread::{self, JoinHandle}; - -use portable_pty::{ChildKiller, CommandBuilder, PtySize, native_pty_system}; - -use crate::error::ToolError; -use crate::exec_output::{ - ExecOutputDelta, ExecStream, OutputBuffer, RUNNING_EXIT_SENTINEL, Utf8ChunkDecoder, -}; -use crate::process_group; -use crate::sandbox::BashExecPlan; - -enum PtyCommand { - Write(Vec), - Kill, -} - -/// Handle to a background PTY session thread. -pub struct PtyExecHandle { - cmd_tx: mpsc::Sender, - killer: Arc>>, - process_id: Option, - pub exit_code: Arc, - _thread: JoinHandle<()>, -} - -impl Drop for PtyExecHandle { - fn drop(&mut self) { - if self.poll_exit_code().is_none() { - let _ = self.kill(); - } - } -} - -impl PtyExecHandle { - pub fn write_stdin(&self, data: &[u8]) -> Result<(), ToolError> { - self.cmd_tx - .send(PtyCommand::Write(data.to_vec())) - .map_err(|e| ToolError::respond(format!("pty stdin channel closed: {e}"))) - } - - pub fn kill(&self) -> Result<(), ToolError> { - if let Some(process_id) = self.process_id { - process_group::kill(process_id); - } - self.killer - .lock() - .map_err(|_| ToolError::respond("pty killer lock poisoned"))? - .kill() - .map_err(|e| ToolError::respond(format!("pty kill failed: {e}")))?; - // Keep the command for implementations where killing does not - // immediately wake the PTY reader loop. - let _ = self.cmd_tx.send(PtyCommand::Kill); - Ok(()) - } - - pub fn poll_exit_code(&self) -> Option { - let code = self.exit_code.load(Ordering::SeqCst); - if code == RUNNING_EXIT_SENTINEL { - None - } else { - Some(code) - } - } -} - -pub fn spawn_pty_exec( - plan: &BashExecPlan, - workdir: &Path, - buffer: Arc>, - session_id: i32, - on_delta: Option>, -) -> Result { - let cmd_tx_out; - let (cmd_tx, cmd_rx) = mpsc::channel(); - let (killer_tx, killer_rx) = mpsc::sync_channel(1); - cmd_tx_out = cmd_tx; - let exit_code = Arc::new(AtomicI32::new(RUNNING_EXIT_SENTINEL)); - let exit_out = exit_code.clone(); - let exit_guard = exit_code.clone(); - let plan = plan.clone(); - let wd = workdir.to_path_buf(); - - let thread = thread::spawn(move || { - if let Err(e) = run_pty_thread( - &plan, &wd, cmd_rx, killer_tx, buffer, session_id, on_delta, exit_out, - ) { - tracing::warn!("pty session ended with error: {e}"); - } - // Setup can fail before the wait loop ever runs (e.g. openpty/spawn - // errors above); without this the session would sit in the table - // forever reporting "still running" since nothing else advances - // `exit_code` on that path. - if exit_guard.load(Ordering::SeqCst) == RUNNING_EXIT_SENTINEL { - exit_guard.store(-1, Ordering::SeqCst); - } - }); - let (killer, process_id) = killer_rx - .recv() - .map_err(|_| ToolError::respond("pty process failed before exposing its kill handle"))?; - - Ok(PtyExecHandle { - cmd_tx: cmd_tx_out, - killer: Arc::new(Mutex::new(killer)), - process_id, - exit_code, - _thread: thread, - }) -} - -fn run_pty_thread( - plan: &BashExecPlan, - workdir: &Path, - cmd_rx: mpsc::Receiver, - killer_tx: mpsc::SyncSender<(Box, Option)>, - buffer: Arc>, - session_id: i32, - on_delta: Option>, - exit_code: Arc, -) -> Result<(), ToolError> { - // Surface setup failures (openpty/spawn/reader/writer) in the session's - // own output buffer, not just tracing logs — otherwise callers only see - // an empty transcript with no clue why the command never produced output. - let report_err = |msg: String| -> ToolError { - if let Ok(mut b) = buffer.try_lock() { - b.push(&format!("{msg}\n")); - } - ToolError::respond(msg) - }; - - let pty_system = native_pty_system(); - let pair = pty_system - .openpty(PtySize { - rows: 24, - cols: 120, - pixel_width: 0, - pixel_height: 0, - }) - .map_err(|e| report_err(format!("openpty failed: {e}")))?; - - let mut cmd_builder = CommandBuilder::new(&plan.argv[0]); - for arg in &plan.argv[1..] { - cmd_builder.arg(arg); - } - cmd_builder.cwd(workdir); - if let Some(env) = &plan.env { - cmd_builder.env_clear(); - for (k, v) in env { - cmd_builder.env(k, v); - } - } - - let mut child = pair - .slave - .spawn_command(cmd_builder) - .map_err(|e| report_err(format!("pty spawn failed: {e}")))?; - killer_tx - .send((child.clone_killer(), child.process_id())) - .map_err(|_| report_err("pty owner dropped during startup".into()))?; - - let mut reader = pair - .master - .try_clone_reader() - .map_err(|e| report_err(format!("pty reader failed: {e}")))?; - let mut writer = pair - .master - .take_writer() - .map_err(|e| report_err(format!("pty writer failed: {e}")))?; - - let mut decoder = Utf8ChunkDecoder::default(); - let mut buf = [0u8; 4096]; - loop { - loop { - match cmd_rx.try_recv() { - Ok(PtyCommand::Write(data)) => { - if let Err(e) = writer.write_all(&data) { - if let Ok(mut b) = buffer.try_lock() { - b.push(&format!("write stdin failed: {e}\n")); - } - } else { - let _ = writer.flush(); - } - } - Ok(PtyCommand::Kill) => { - let _ = child.kill(); - } - Err(mpsc::TryRecvError::Empty) => break, - Err(mpsc::TryRecvError::Disconnected) => { - let _ = child.kill(); - break; - } - } - } - - match child.try_wait() { - Ok(Some(status)) => { - exit_code.store(status.exit_code() as i32, Ordering::SeqCst); - break; - } - Ok(None) => {} - Err(e) => { - exit_code.store(-1, Ordering::SeqCst); - return Err(ToolError::respond(format!("pty wait failed: {e}"))); - } - } - - match reader.read(&mut buf) { - Ok(0) => { - thread::sleep(std::time::Duration::from_millis(10)); - } - Ok(n) => { - emit_chunk(&mut decoder, &buf[..n], &buffer, session_id, &on_delta); - } - Err(_) => thread::sleep(std::time::Duration::from_millis(10)), - } - } - - // Drain remaining output. - while let Ok(n) = reader.read(&mut buf) { - if n == 0 { - break; - } - emit_chunk(&mut decoder, &buf[..n], &buffer, session_id, &on_delta); - } - let tail = decoder.finish(); - if !tail.is_empty() { - if let Ok(mut b) = buffer.try_lock() { - b.push(&tail); - } - if let Some(hook) = &on_delta { - hook(ExecOutputDelta { - session_id, - stream: ExecStream::Pty, - chunk: tail, - }); - } - } - - Ok(()) -} - -fn emit_chunk( - decoder: &mut Utf8ChunkDecoder, - bytes: &[u8], - buffer: &Arc>, - session_id: i32, - on_delta: &Option>, -) { - let chunk = decoder.decode(bytes); - if chunk.is_empty() { - return; - } - if let Ok(mut b) = buffer.try_lock() { - b.push(&chunk); - } - if let Some(hook) = on_delta { - hook(ExecOutputDelta { - session_id, - stream: ExecStream::Pty, - chunk, - }); - } -} diff --git a/crates/pulsing-forge/src/registry.rs b/crates/pulsing-forge/src/registry.rs deleted file mode 100644 index b618bfa02..000000000 --- a/crates/pulsing-forge/src/registry.rs +++ /dev/null @@ -1,305 +0,0 @@ -//! Forge's canonical tool registry. -//! -//! A registered executor is the single source of truth for both model-visible -//! metadata and runtime dispatch. Agent clients select tools by name, but never -//! maintain a second copy of their schemas. - -use std::collections::HashMap; -use std::fmt; - -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; -use thiserror::Error; - -use crate::executor::ToolExecutor; - -/// A callable tool name that preserves an optional namespace. -#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] -pub struct ToolName { - pub namespace: Option, - pub name: String, -} - -impl ToolName { - pub fn plain(name: impl Into) -> Self { - Self { - namespace: None, - name: name.into(), - } - } - - pub fn namespaced(namespace: impl Into, name: impl Into) -> Self { - Self { - namespace: Some(namespace.into()), - name: name.into(), - } - } - - /// Name sent over the current flat model tool protocol. - pub fn model_name(&self) -> String { - match &self.namespace { - Some(namespace) => format!("{namespace}{}", self.name), - None => self.name.clone(), - } - } -} - -impl fmt::Display for ToolName { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.model_name()) - } -} - -impl From<&str> for ToolName { - fn from(value: &str) -> Self { - Self::plain(value) - } -} - -impl From for ToolName { - fn from(value: String) -> Self { - Self::plain(value) - } -} - -/// Provider-neutral metadata owned by the executable tool. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ToolSpec { - pub name: ToolName, - pub description: String, - pub input_schema: Value, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub output_schema: Option, -} - -impl ToolSpec { - pub fn function( - name: impl Into, - description: impl Into, - input_schema: Value, - ) -> Self { - Self { - name: name.into(), - description: description.into(), - input_schema: normalize_object_schema(input_schema), - output_schema: None, - } - } - - /// Current Forge LLM clients consume Anthropic-style function definitions; - /// OpenAI conversion happens in `llm::message`. - pub fn model_definition(&self) -> Value { - json!({ - "name": self.name.model_name(), - "description": self.description, - "input_schema": self.input_schema, - }) - } -} - -fn normalize_object_schema(mut schema: Value) -> Value { - if let Some(obj) = schema.as_object_mut() { - obj.entry("type").or_insert_with(|| json!("object")); - obj.entry("properties") - .or_insert_with(|| Value::Object(Default::default())); - } - schema -} - -#[derive(Debug, Error, PartialEq, Eq)] -pub enum ToolRegistryError { - #[error("tool name must not be empty")] - EmptyName, - #[error("tool executor name {executor:?} does not match spec name {spec:?}")] - NameMismatch { executor: String, spec: String }, - #[error("duplicate tool registration: {0}")] - Duplicate(String), - #[error("unknown tool selected for this Forge runtime: {0}")] - Unknown(String), - #[error("tool is not directly model-visible: {0}")] - NotDirect(String), -} - -pub struct ToolRegistry { - tools: HashMap>, -} - -impl ToolRegistry { - pub fn from_executors( - executors: impl IntoIterator>, - ) -> Result { - let mut registry = Self { - tools: HashMap::new(), - }; - for executor in executors { - registry.register(executor)?; - } - Ok(registry) - } - - pub fn register(&mut self, executor: Box) -> Result<(), ToolRegistryError> { - let executor_name = executor.tool_name().trim().to_string(); - if executor_name.is_empty() { - return Err(ToolRegistryError::EmptyName); - } - let spec_name = executor.spec().name.model_name(); - if executor_name != spec_name { - return Err(ToolRegistryError::NameMismatch { - executor: executor_name, - spec: spec_name, - }); - } - if self.tools.contains_key(&executor_name) { - return Err(ToolRegistryError::Duplicate(executor_name)); - } - self.tools.insert(executor_name, executor); - Ok(()) - } - - pub fn get(&self, name: &str) -> Option<&dyn ToolExecutor> { - self.tools.get(name).map(Box::as_ref) - } - - pub fn names(&self) -> Vec { - let mut names: Vec<_> = self.tools.keys().cloned().collect(); - names.sort(); - names - } - - pub fn definitions_for(&self, names: &[String]) -> Result, ToolRegistryError> { - names - .iter() - .map(|name| { - let tool = self - .tools - .get(name) - .ok_or_else(|| ToolRegistryError::Unknown(name.clone()))?; - if !tool.exposure().is_direct() { - return Err(ToolRegistryError::NotDirect(name.clone())); - } - Ok(tool.spec().model_definition()) - }) - .collect() - } - - pub fn direct_definitions(&self) -> Vec { - let mut tools: Vec<_> = self - .tools - .values() - .filter(|tool| tool.exposure().is_direct()) - .map(|tool| tool.spec().model_definition()) - .collect(); - tools.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); - tools - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::context::ToolCallContext; - use crate::error::ToolError; - use crate::executor::{ToolExecutorFuture, ToolExposure}; - use crate::result::ToolResult; - - struct TestTool { - runtime_name: &'static str, - spec_name: &'static str, - exposure: ToolExposure, - } - - impl ToolExecutor for TestTool { - fn tool_name(&self) -> &str { - self.runtime_name - } - - fn spec(&self) -> ToolSpec { - ToolSpec::function(self.spec_name, "test", json!({"type": "object"})) - } - - fn exposure(&self) -> ToolExposure { - self.exposure - } - - fn handle<'a>( - &'a self, - _ctx: &'a ToolCallContext, - _arguments: Value, - ) -> ToolExecutorFuture<'a> { - Box::pin(async { Ok::<_, ToolError>(ToolResult::ok("ok")) }) - } - } - - #[test] - fn rejects_name_mismatch_and_duplicates() { - let mismatch = ToolRegistry::from_executors([Box::new(TestTool { - runtime_name: "runtime", - spec_name: "schema", - exposure: ToolExposure::Direct, - }) as Box]) - .err() - .unwrap(); - assert!(matches!(mismatch, ToolRegistryError::NameMismatch { .. })); - - let duplicate = ToolRegistry::from_executors([ - Box::new(TestTool { - runtime_name: "same", - spec_name: "same", - exposure: ToolExposure::Direct, - }) as Box, - Box::new(TestTool { - runtime_name: "same", - spec_name: "same", - exposure: ToolExposure::Direct, - }) as Box, - ]) - .err() - .unwrap(); - assert_eq!(duplicate, ToolRegistryError::Duplicate("same".into())); - } - - #[test] - fn definitions_are_derived_from_registered_executors() { - let registry = ToolRegistry::from_executors([ - Box::new(TestTool { - runtime_name: "visible", - spec_name: "visible", - exposure: ToolExposure::Direct, - }) as Box, - Box::new(TestTool { - runtime_name: "deferred", - spec_name: "deferred", - exposure: ToolExposure::Deferred, - }) as Box, - ]) - .unwrap(); - - assert_eq!(registry.direct_definitions().len(), 1); - assert_eq!(registry.direct_definitions()[0]["name"], "visible"); - assert_eq!( - registry.definitions_for(&["deferred".into()]).unwrap_err(), - ToolRegistryError::NotDirect("deferred".into()) - ); - } - - #[test] - fn every_builtin_executor_has_one_canonical_definition() { - let registry = ToolRegistry::from_executors(crate::handlers::builtin_handlers()).unwrap(); - let names = registry.names(); - let definitions = registry.direct_definitions(); - - assert_eq!(names.len(), 22); - assert_eq!(definitions.len(), names.len()); - for definition in definitions { - let name = definition["name"].as_str().unwrap(); - assert!(names.iter().any(|candidate| candidate == name)); - assert!( - definition["description"] - .as_str() - .is_some_and(|value| !value.is_empty()) - ); - assert_eq!(definition["input_schema"]["type"], "object"); - assert!(definition["input_schema"]["properties"].is_object()); - } - } -} diff --git a/crates/pulsing-forge/src/result.rs b/crates/pulsing-forge/src/result.rs deleted file mode 100644 index 08064890c..000000000 --- a/crates/pulsing-forge/src/result.rs +++ /dev/null @@ -1,33 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ToolResult { - pub content: String, - #[serde(default)] - pub is_error: bool, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub structured: Option, -} - -impl ToolResult { - pub fn ok(content: impl Into) -> Self { - Self { - content: content.into(), - is_error: false, - structured: None, - } - } - - pub fn err(content: impl Into) -> Self { - Self { - content: content.into(), - is_error: true, - structured: None, - } - } - - pub fn with_structured(mut self, value: serde_json::Value) -> Self { - self.structured = Some(value); - self - } -} diff --git a/crates/pulsing-forge/src/runtime.rs b/crates/pulsing-forge/src/runtime.rs deleted file mode 100644 index afcef0994..000000000 --- a/crates/pulsing-forge/src/runtime.rs +++ /dev/null @@ -1,418 +0,0 @@ -use std::path::Path; -use std::sync::Arc; - -use crate::approval::{ApprovalCache, new_exec_policy}; -use crate::context::{LocalToolSession, NullToolSession, ToolCallContext, ToolSession}; -use crate::discovery::{ToolCatalog, new_tool_catalog}; -use crate::handlers::builtin_handlers; -use crate::handlers::try_call_mcp_dynamic_tool; -use crate::registry::{ToolRegistry, ToolRegistryError}; -use crate::result::ToolResult; -use crate::turn::TurnExecutionContext; -use crate::unified_exec::UnifiedExecManager; - -pub struct ToolRuntimeConfig { - pub cwd: std::path::PathBuf, - pub sandbox_policy: String, - pub dangerously_disable_sandbox: bool, - pub session: Arc, - pub exec: Arc, - pub exec_policy: Arc>, - pub approval_cache: Arc, - pub tool_catalog: Arc>, - pub mcp_runtime: Option, -} - -impl Default for ToolRuntimeConfig { - fn default() -> Self { - let catalog = new_tool_catalog(); - { - let mut c = catalog.lock().unwrap(); - c.load_codex_plugins(&[]); - } - Self { - cwd: std::env::current_dir().unwrap_or_else(|_| ".".into()), - sandbox_policy: "off".into(), - dangerously_disable_sandbox: false, - session: Arc::new(NullToolSession), - exec: Arc::new(UnifiedExecManager::new()), - exec_policy: new_exec_policy(), - approval_cache: Arc::new(ApprovalCache::default()), - tool_catalog: catalog, - mcp_runtime: None, - } - } -} - -pub struct ToolRuntime { - registry: ToolRegistry, - context: ToolCallContext, -} - -impl ToolRuntime { - pub fn new(config: ToolRuntimeConfig) -> Self { - let registry = ToolRegistry::from_executors(builtin_handlers()) - .expect("built-in Forge tools must form a valid registry"); - let context = ToolCallContext::new( - config.cwd, - &config.sandbox_policy, - config.session, - config.exec, - config.exec_policy, - config.approval_cache, - config.tool_catalog, - ) - .with_dangerous_sandbox(config.dangerously_disable_sandbox); - let context = if let Some(mcp) = config.mcp_runtime { - context.with_mcp_runtime(mcp) - } else { - context - }; - Self { registry, context } - } - - pub fn with_local_session(cwd: impl AsRef, sandbox_policy: &str) -> Self { - Self::new(ToolRuntimeConfig { - cwd: cwd.as_ref().to_path_buf(), - sandbox_policy: sandbox_policy.to_string(), - session: Arc::new(LocalToolSession::default()), - ..Default::default() - }) - } - - pub fn context(&self) -> &ToolCallContext { - &self.context - } - - pub fn tool_names(&self) -> Vec { - self.registry.names() - } - - pub fn tool_definitions( - &self, - names: &[String], - ) -> Result, ToolRegistryError> { - self.registry.definitions_for(names) - } - - pub fn registry(&self) -> &ToolRegistry { - &self.registry - } - - pub async fn call_tool(&self, name: &str, arguments: serde_json::Value) -> ToolResult { - self.call_tool_with_context(&self.context, name, arguments) - .await - } - - pub async fn call_tool_in_turn( - &self, - turn: Arc, - name: &str, - arguments: serde_json::Value, - ) -> ToolResult { - let context = self.context.clone().with_turn(turn); - self.call_tool_with_context(&context, name, arguments).await - } - - async fn call_tool_with_context( - &self, - context: &ToolCallContext, - name: &str, - arguments: serde_json::Value, - ) -> ToolResult { - if let Some(h) = self.registry.get(name) { - return match h.handle(context, arguments).await { - Ok(r) => r, - Err(e) => ToolResult::err(e.to_string()), - }; - } - if let Some(result) = try_call_mcp_dynamic_tool(context, name, arguments).await { - return match result { - Ok(r) => r, - Err(e) => ToolResult::err(e.to_string()), - }; - } - ToolResult::err(format!("Unknown tool: {name}")) - } -} - -impl Default for ToolRuntime { - fn default() -> Self { - Self::with_local_session(".", "off") - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::context::{PlanItem, StepStatus}; - - #[tokio::test] - async fn mcp_dynamic_tool_routes_before_unknown() { - use rmcp::model::Tool; - use std::sync::Arc; - - let tool = Tool::new_with_raw( - "echo".to_string(), - Some("Echo".into()), - Arc::new(serde_json::Map::new()), - ); - let info = crate::mcp::ToolInfo { - server_name: "demo".into(), - supports_parallel_tool_calls: false, - server_origin: None, - callable_name: "echo".into(), - callable_namespace: "demo".into(), - namespace_description: None, - tool, - connector_id: None, - connector_name: None, - plugin_display_names: vec![], - }; - let catalog = crate::discovery::new_tool_catalog(); - let catalog_snap = - crate::mcp::build_default_catalog(vec![], std::collections::HashMap::new()); - let manager = crate::mcp::McpConnectionManager::from_tools(vec![info], true); - let mcp = crate::mcp::McpRuntime { - catalog: catalog_snap, - manager, - }; - let slot = crate::mcp::new_shared_mcp_runtime(); - *slot.write().await = Some(mcp); - let rt = ToolRuntime::new(ToolRuntimeConfig { - mcp_runtime: Some(slot), - tool_catalog: catalog, - ..Default::default() - }); - let out = rt.call_tool("mcp__demo__echo", serde_json::json!({})).await; - assert!( - !out.content.starts_with("Unknown tool:"), - "expected MCP dispatch, got: {}", - out.content - ); - assert!(out.is_error); - assert!( - out.content.contains("MCP server not connected") || out.content.contains("MCP tool") - ); - } - - #[tokio::test] - async fn read_roundtrip() { - let dir = tempfile::tempdir().unwrap(); - let fp = dir.path().join("a.txt"); - std::fs::write(&fp, "hello").unwrap(); - let rt = ToolRuntime::with_local_session(dir.path(), "off"); - let out = rt - .call_tool("Read", serde_json::json!({"file_path": "a.txt"})) - .await; - assert!(!out.is_error); - assert_eq!(out.content, "hello"); - } - - #[tokio::test] - async fn update_plan_uses_session() { - let session = Arc::new(LocalToolSession::default()); - let rt = ToolRuntime::new(ToolRuntimeConfig { - session: session.clone(), - ..Default::default() - }); - let out = rt - .call_tool( - "update_plan", - serde_json::json!({ - "plan": [{"step": "one", "status": "pending"}] - }), - ) - .await; - assert!(!out.is_error); - assert_eq!( - session.plan_snapshot(), - vec![PlanItem { - step: "one".into(), - status: StepStatus::Pending, - }] - ); - } - - #[tokio::test] - async fn shell_command_codex_args() { - let session = Arc::new( - LocalToolSession::default() - .with_approval_policy(crate::approval::ApprovalPolicy::Always), - ); - let rt = ToolRuntime::new(ToolRuntimeConfig { - session, - ..Default::default() - }); - let out = rt - .call_tool( - "shell_command", - serde_json::json!({"cmd": "echo hi", "workdir": "."}), - ) - .await; - assert!(!out.is_error); - assert!(out.content.contains("hi")); - } - - #[tokio::test] - async fn bash_alias_matches_shell_command() { - let session = Arc::new( - LocalToolSession::default() - .with_approval_policy(crate::approval::ApprovalPolicy::Always), - ); - let rt = ToolRuntime::new(ToolRuntimeConfig { - session, - ..Default::default() - }); - let out = rt - .call_tool("Bash", serde_json::json!({"command": "echo alias-ok"})) - .await; - assert!(!out.is_error, "{}", out.content); - assert!(out.content.contains("alias-ok")); - } - - #[tokio::test] - async fn shell_command_login_does_not_bypass_restricted_sandbox() { - let session = Arc::new( - LocalToolSession::default() - .with_approval_policy(crate::approval::ApprovalPolicy::Always), - ); - let rt = ToolRuntime::new(ToolRuntimeConfig { - session, - sandbox_policy: "restricted".into(), - ..Default::default() - }); - let out = rt - .call_tool( - "shell_command", - serde_json::json!({ - "cmd": "echo hi", - "login": true, - }), - ) - .await; - assert!(!out.is_error, "{}", out.content); - assert!( - out.content.contains("restricted env"), - "login shell must stay inside restricted wrapper, got: {}", - out.content - ); - } - - #[tokio::test] - async fn shell_command_require_escalated_denied_when_approval_never() { - let session = Arc::new( - LocalToolSession::default() - .with_approval_policy(crate::approval::ApprovalPolicy::Never), - ); - let rt = ToolRuntime::new(ToolRuntimeConfig { - session, - sandbox_policy: "restricted".into(), - ..Default::default() - }); - let out = rt - .call_tool( - "shell_command", - serde_json::json!({ - "cmd": "echo hi", - "sandbox_permissions": "require_escalated", - }), - ) - .await; - assert!( - out.is_error, - "require_escalated must be denied when approval_policy=never" - ); - } - - #[tokio::test] - async fn tool_search_finds_deferred_tool() { - let catalog = crate::discovery::new_tool_catalog(); - { - let mut c = catalog.lock().unwrap(); - c.register_deferred(crate::discovery::DeferredToolEntry::from_function( - "github_mcp", - "GitHub MCP integration", - serde_json::json!({"type": "object"}), - )); - } - let rt = ToolRuntime::new(ToolRuntimeConfig { - tool_catalog: catalog, - ..Default::default() - }); - let out = rt - .call_tool("tool_search", serde_json::json!({"query": "github mcp"})) - .await; - assert!(!out.is_error); - assert!(out.content.contains("github_mcp")); - } - - #[tokio::test] - async fn tool_search_rejects_empty_query() { - let rt = ToolRuntime::new(ToolRuntimeConfig::default()); - for args in [ - serde_json::json!({"query": ""}), - serde_json::json!({"query": " "}), - serde_json::json!({}), - ] { - let out = rt.call_tool("tool_search", args).await; - assert!(out.is_error); - } - } - - #[tokio::test] - async fn tool_search_limit_zero_or_negative_falls_back_to_default() { - let catalog = crate::discovery::new_tool_catalog(); - { - let mut c = catalog.lock().unwrap(); - for name in ["github_mcp", "github_issues", "github_actions"] { - c.register_deferred(crate::discovery::DeferredToolEntry::from_function( - name, - "GitHub integration", - serde_json::json!({"type": "object"}), - )); - } - } - let rt = ToolRuntime::new(ToolRuntimeConfig { - tool_catalog: catalog, - ..Default::default() - }); - // limit=0 and limit=-5 are not usable positive counts, so both should - // behave like the omitted-limit (default) case rather than returning - // zero or panicking. - for args in [ - serde_json::json!({"query": "github", "limit": 0}), - serde_json::json!({"query": "github", "limit": -5}), - ] { - let out = rt.call_tool("tool_search", args).await; - assert!(!out.is_error); - let payload: serde_json::Value = serde_json::from_str(&out.content).unwrap(); - assert_eq!(payload["tools"].as_array().unwrap().len(), 3); - } - } - - #[tokio::test] - async fn tool_search_huge_limit_is_clamped_not_rejected() { - let catalog = crate::discovery::new_tool_catalog(); - { - let mut c = catalog.lock().unwrap(); - c.register_deferred(crate::discovery::DeferredToolEntry::from_function( - "github_mcp", - "GitHub MCP integration", - serde_json::json!({"type": "object"}), - )); - } - let rt = ToolRuntime::new(ToolRuntimeConfig { - tool_catalog: catalog, - ..Default::default() - }); - let out = rt - .call_tool( - "tool_search", - serde_json::json!({"query": "github", "limit": 999_999_999_u64}), - ) - .await; - assert!(!out.is_error); - assert!(out.content.contains("github_mcp")); - } -} diff --git a/crates/pulsing-forge/src/sandbox.rs b/crates/pulsing-forge/src/sandbox.rs deleted file mode 100644 index bba5e1365..000000000 --- a/crates/pulsing-forge/src/sandbox.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! Bash sandbox helpers (MVP). Logic aligned with Craft/Codex `build_bash_exec`. - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SandboxPolicy { - Off, - Restricted, - Bwrap, -} - -pub fn normalize_policy(raw: &str) -> SandboxPolicy { - match raw.trim().to_lowercase().as_str() { - "restricted" => SandboxPolicy::Restricted, - "bwrap" => SandboxPolicy::Bwrap, - _ => SandboxPolicy::Off, - } -} - -#[derive(Clone, Debug)] -pub struct BashExecPlan { - pub argv: Vec, - pub env: Option>, - pub label: String, -} - -/// Builds the argv/env for running `command` under the given sandbox policy. -/// -/// `login` requests login-shell semantics (`bash -l`, sourcing profile files) -/// instead of a plain `-c` invocation. It must never itself disable the -/// sandbox wrapper — callers that need an unsandboxed login shell must go -/// through `dangerously_disable_sandbox` explicitly, which is gated by -/// approval upstream. -pub fn build_bash_exec( - command: &str, - cwd: Option<&Path>, - policy: SandboxPolicy, - dangerously_disable_sandbox: bool, - login: bool, -) -> BashExecPlan { - let wd = cwd - .map(|p| p.canonicalize().unwrap_or_else(|_| p.to_path_buf())) - .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))); - - let pol = if dangerously_disable_sandbox { - SandboxPolicy::Off - } else { - policy - }; - - if pol == SandboxPolicy::Off { - let argv = if login { - vec!["bash".into(), "-lc".into(), command.to_string()] - } else { - vec!["/bin/sh".into(), "-c".into(), command.to_string()] - }; - return BashExecPlan { - argv, - env: None, - label: "subprocess shell (sandbox=off)".into(), - }; - } - - if pol == SandboxPolicy::Bwrap && which_bwrap() { - let mut argv = vec![ - "bwrap".to_string(), - "--die-with-parent".into(), - "--unshare-pid".into(), - "--tmpfs".into(), - "/tmp".into(), - "--proc".into(), - "/proc".into(), - "--dev".into(), - "/dev".into(), - "--ro-bind".into(), - "/usr".into(), - "/usr".into(), - "--ro-bind".into(), - "/bin".into(), - "/bin".into(), - "--ro-bind".into(), - "/lib".into(), - "/lib".into(), - ]; - if Path::new("/lib64").is_dir() { - argv.extend(["--ro-bind".into(), "/lib64".into(), "/lib64".into()]); - } - let wd_str = wd.to_string_lossy().to_string(); - let shell_flag = if login { "-lc" } else { "-c" }; - argv.extend([ - "--bind".into(), - wd_str.clone(), - "/work".into(), - "--chdir".into(), - "/work".into(), - "bash".into(), - shell_flag.into(), - command.to_string(), - ]); - return BashExecPlan { - argv, - env: None, - label: "bubblewrap (minimal profile; Linux)".into(), - }; - } - - let mut env = HashMap::new(); - env.insert( - "HOME".into(), - std::env::var("HOME").unwrap_or_else(|_| "/tmp".into()), - ); - env.insert("PATH".into(), "/usr/bin:/bin:/usr/local/bin".into()); - env.insert( - "LANG".into(), - std::env::var("LANG").unwrap_or_else(|_| "C.UTF-8".into()), - ); - env.insert( - "USER".into(), - std::env::var("USER").unwrap_or_else(|_| "user".into()), - ); - let mut argv = vec!["env".into(), "-i".into()]; - for (k, v) in &env { - argv.push(format!("{k}={v}")); - } - let label = if login { - argv.extend(["bash".into(), "-lc".into(), command.to_string()]); - "restricted env (env -i + bash -l)" - } else { - argv.extend([ - "bash".into(), - "--norc".into(), - "--noprofile".into(), - "-c".into(), - command.to_string(), - ]); - "restricted env (env -i + bash --norc)" - }; - BashExecPlan { - argv, - env: Some(env), - label: label.into(), - } -} - -fn which_bwrap() -> bool { - std::process::Command::new("which") - .arg("bwrap") - .output() - .map(|o| o.status.success()) - .unwrap_or(false) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Regression: `login=true` must still route through the restricted-env - /// wrapper (`env -i` + no-inherit env) instead of falling back to a - /// bare, unsandboxed `bash -lc` that inherits the full host environment. - #[test] - fn login_restricted_policy_still_clears_env() { - let plan = build_bash_exec("echo hi", None, SandboxPolicy::Restricted, false, true); - assert_eq!(plan.argv[0], "env"); - assert_eq!(plan.argv[1], "-i"); - assert!( - plan.env.is_some(), - "restricted plan must carry a scrubbed env map" - ); - assert!(plan.argv.iter().any(|a| a == "-lc")); - } - - #[test] - fn login_off_policy_uses_login_shell_directly() { - let plan = build_bash_exec("echo hi", None, SandboxPolicy::Off, false, true); - assert_eq!(plan.argv, vec!["bash", "-lc", "echo hi"]); - } - - #[test] - fn non_login_off_policy_uses_plain_sh() { - let plan = build_bash_exec("echo hi", None, SandboxPolicy::Off, false, false); - assert_eq!(plan.argv, vec!["/bin/sh", "-c", "echo hi"]); - } - - /// `dangerously_disable_sandbox` must win over any requested policy - /// regardless of `login`, and is the only switch allowed to disable - /// the sandbox wrapper. - #[test] - fn dangerously_disable_sandbox_overrides_policy_for_login_and_non_login() { - for login in [true, false] { - let plan = build_bash_exec("echo hi", None, SandboxPolicy::Restricted, true, login); - assert!(plan.label.contains("sandbox=off")); - assert!(plan.env.is_none()); - } - } - - #[test] - fn login_bwrap_policy_keeps_bwrap_wrapper_when_available() { - if !which_bwrap() { - return; - } - let plan = build_bash_exec("echo hi", None, SandboxPolicy::Bwrap, false, true); - assert_eq!(plan.argv[0], "bwrap"); - assert!(plan.argv.iter().any(|a| a == "-lc")); - } -} diff --git a/crates/pulsing-forge/src/session/client.rs b/crates/pulsing-forge/src/session/client.rs deleted file mode 100644 index 9cc7f8277..000000000 --- a/crates/pulsing-forge/src/session/client.rs +++ /dev/null @@ -1,132 +0,0 @@ -use crate::agent::AgentConfig; -use crate::protocol::{ - CancelTurn, CommandEnvelope, CommandId, CommandReceipt, CreateSession, ForgeEventKind, - ForgeProtocolError, SessionId, SessionSpec, StartTurn, TurnId, -}; - -use super::{EventSubscription, ForgeService, SessionSnapshot}; - -#[derive(Clone, Default)] -pub struct LocalForgeClient { - service: ForgeService, -} - -impl LocalForgeClient { - pub fn new(service: ForgeService) -> Self { - Self { service } - } - - pub fn service(&self) -> &ForgeService { - &self.service - } - - pub async fn create_session( - &self, - config: AgentConfig, - ) -> Result { - let session_id = SessionId::new(); - self.create_session_with(CommandId::new(), session_id.clone(), config) - .await?; - Ok(session_id) - } - - pub async fn create_session_with( - &self, - command_id: CommandId, - session_id: SessionId, - config: AgentConfig, - ) -> Result { - self.service - .create_session(CommandEnvelope::new( - command_id, - session_id, - CreateSession { - spec: SessionSpec::from(config), - }, - )) - .await - } - - pub async fn start_turn( - &self, - session_id: SessionId, - input: impl Into, - ) -> Result { - self.start_turn_with(CommandId::new(), session_id, TurnId::new(), input.into()) - .await - } - - pub async fn start_turn_with( - &self, - command_id: CommandId, - session_id: SessionId, - turn_id: TurnId, - input: String, - ) -> Result { - self.service - .start_turn(CommandEnvelope::new( - command_id, - session_id, - StartTurn { turn_id, input }, - )) - .await - } - - pub async fn cancel_turn( - &self, - session_id: SessionId, - turn_id: TurnId, - ) -> Result { - self.service - .cancel_turn(CommandEnvelope::new( - CommandId::new(), - session_id, - CancelTurn { turn_id }, - )) - .await - } - - pub async fn snapshot( - &self, - session_id: &SessionId, - ) -> Result { - self.service.snapshot(session_id).await - } - - pub async fn subscribe( - &self, - session_id: &SessionId, - after_seq: u64, - ) -> Result { - self.service.subscribe(session_id, after_seq).await - } - - pub async fn run_turn( - &self, - session_id: SessionId, - input: impl Into, - ) -> Result { - let receipt = self.start_turn(session_id.clone(), input).await?; - let turn_id = receipt - .turn_id - .clone() - .ok_or_else(|| ForgeProtocolError::Internal("start_turn returned no turn_id".into()))?; - let mut events = self.subscribe(&session_id, receipt.accepted_seq).await?; - loop { - let event = events.recv().await?; - if event.turn_id.as_ref() != Some(&turn_id) { - continue; - } - match event.kind { - ForgeEventKind::TurnCompleted { text } => return Ok(text), - ForgeEventKind::TurnFailed { message } => { - return Err(ForgeProtocolError::Agent(message)); - } - ForgeEventKind::TurnCancelled => { - return Err(ForgeProtocolError::Agent("turn cancelled".into())); - } - _ => {} - } - } - } -} diff --git a/crates/pulsing-forge/src/session/mod.rs b/crates/pulsing-forge/src/session/mod.rs deleted file mode 100644 index 21ad04ab4..000000000 --- a/crates/pulsing-forge/src/session/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Persistent Forge sessions, event reduction, and local client. - -mod client; -mod reducer; -mod service; -mod store; - -pub use client::LocalForgeClient; -pub use reducer::{SessionSnapshot, SessionStatus, TurnSnapshot, TurnStatus}; -pub use service::{EventSubscription, ForgeService}; -pub use store::{EventStore, InMemoryEventStore}; diff --git a/crates/pulsing-forge/src/session/reducer.rs b/crates/pulsing-forge/src/session/reducer.rs deleted file mode 100644 index b9b3de2d4..000000000 --- a/crates/pulsing-forge/src/session/reducer.rs +++ /dev/null @@ -1,326 +0,0 @@ -use std::collections::HashMap; - -use serde::{Deserialize, Serialize}; - -use crate::protocol::{ - ForgeEvent, ForgeEventKind, ForgeProtocolError, SessionId, SessionSpec, TurnId, -}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum SessionStatus { - Active, - Closed, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum TurnStatus { - Running, - Cancelling, - Unknown, - Completed, - Failed, - Cancelled, -} - -impl TurnStatus { - pub fn is_terminal(self) -> bool { - matches!(self, Self::Completed | Self::Failed | Self::Cancelled) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct TurnSnapshot { - pub id: TurnId, - pub input: String, - pub status: TurnStatus, - pub output: Option, - pub error: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SessionSnapshot { - pub id: SessionId, - pub spec: SessionSpec, - pub status: SessionStatus, - pub last_seq: u64, - pub active_turn: Option, - pub turns: HashMap, -} - -impl SessionSnapshot { - pub(crate) fn uninitialized(id: SessionId, spec: SessionSpec) -> Self { - Self { - id, - spec, - status: SessionStatus::Active, - last_seq: 0, - active_turn: None, - turns: HashMap::new(), - } - } - - pub(crate) fn ensure_can_start(&self) -> Result<(), ForgeProtocolError> { - if self.status == SessionStatus::Closed { - return Err(ForgeProtocolError::SessionClosed(self.id.clone())); - } - if self.active_turn.is_some() { - return Err(ForgeProtocolError::SessionBusy(self.id.clone())); - } - Ok(()) - } - - pub(crate) fn apply(&mut self, event: &ForgeEvent) -> Result<(), ForgeProtocolError> { - if event.session_id != self.id { - return Err(ForgeProtocolError::InvalidTransition(format!( - "event belongs to {}, reducer belongs to {}", - event.session_id, self.id - ))); - } - let expected = self.last_seq + 1; - if event.seq != expected { - return Err(ForgeProtocolError::SequenceConflict { - expected, - actual: event.seq, - }); - } - - match &event.kind { - ForgeEventKind::SessionCreated => { - if self.last_seq != 0 { - return Err(ForgeProtocolError::InvalidTransition( - "session.created must be the first event".into(), - )); - } - } - ForgeEventKind::SessionClosed => { - if self.active_turn.is_some() { - return Err(ForgeProtocolError::InvalidTransition( - "cannot close a session with an active turn".into(), - )); - } - self.status = SessionStatus::Closed; - } - ForgeEventKind::TurnStarted { input } => { - self.ensure_can_start()?; - let turn_id = event.turn_id.clone().ok_or_else(|| { - ForgeProtocolError::InvalidTransition("turn.started missing turn_id".into()) - })?; - self.turns.insert( - turn_id.clone(), - TurnSnapshot { - id: turn_id.clone(), - input: input.clone(), - status: TurnStatus::Running, - output: None, - error: None, - }, - ); - self.active_turn = Some(turn_id); - } - ForgeEventKind::TurnCancelRequested => { - let turn = self.active_turn_mut(event)?; - if turn.status != TurnStatus::Running { - return Err(ForgeProtocolError::InvalidTransition(format!( - "cannot cancel turn in {:?}", - turn.status - ))); - } - turn.status = TurnStatus::Cancelling; - } - ForgeEventKind::TurnCancelled => { - let turn = self.active_turn_mut(event)?; - if !matches!( - turn.status, - TurnStatus::Running | TurnStatus::Cancelling | TurnStatus::Unknown - ) { - return Err(ForgeProtocolError::InvalidTransition(format!( - "cannot complete cancellation from {:?}", - turn.status - ))); - } - turn.status = TurnStatus::Cancelled; - self.active_turn = None; - } - ForgeEventKind::TurnCleanupStalled { resources } => { - let turn = self.active_turn_mut(event)?; - turn.status = TurnStatus::Unknown; - turn.error = Some(format!( - "waiting for turn resources to stop: {}", - resources.join(", ") - )); - } - ForgeEventKind::TurnCompleted { text } => { - let turn = self.active_turn_mut(event)?; - turn.status = TurnStatus::Completed; - turn.output = Some(text.clone()); - self.active_turn = None; - } - ForgeEventKind::TurnFailed { message } => { - let turn = self.active_turn_mut(event)?; - turn.status = TurnStatus::Failed; - turn.error = Some(message.clone()); - self.active_turn = None; - } - ForgeEventKind::TurnOutputDelta { .. } - | ForgeEventKind::ToolStarted { .. } - | ForgeEventKind::ToolCompleted { .. } - | ForgeEventKind::ToolCancelled { .. } => { - let turn = self.active_turn_ref(event)?; - if turn.status.is_terminal() { - return Err(ForgeProtocolError::InvalidTransition( - "activity after terminal turn".into(), - )); - } - } - } - - self.last_seq = event.seq; - Ok(()) - } - - fn event_turn_id<'a>( - &'a self, - event: &'a ForgeEvent, - ) -> Result<&'a TurnId, ForgeProtocolError> { - event.turn_id.as_ref().ok_or_else(|| { - ForgeProtocolError::InvalidTransition("turn event missing turn_id".into()) - }) - } - - fn active_turn_ref(&self, event: &ForgeEvent) -> Result<&TurnSnapshot, ForgeProtocolError> { - let turn_id = self.event_turn_id(event)?; - if self.active_turn.as_ref() != Some(turn_id) { - return Err(ForgeProtocolError::TurnNotActive(turn_id.clone())); - } - self.turns - .get(turn_id) - .ok_or_else(|| ForgeProtocolError::TurnNotActive(turn_id.clone())) - } - - fn active_turn_mut( - &mut self, - event: &ForgeEvent, - ) -> Result<&mut TurnSnapshot, ForgeProtocolError> { - let turn_id = event.turn_id.clone().ok_or_else(|| { - ForgeProtocolError::InvalidTransition("turn event missing turn_id".into()) - })?; - if self.active_turn.as_ref() != Some(&turn_id) { - return Err(ForgeProtocolError::TurnNotActive(turn_id)); - } - self.turns - .get_mut(&turn_id) - .ok_or(ForgeProtocolError::TurnNotActive(turn_id)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::agent::AgentConfig; - use crate::protocol::{CommandId, ForgeEventKind}; - - fn state() -> SessionSnapshot { - let id = SessionId::new(); - let mut state = SessionSnapshot::uninitialized(id.clone(), AgentConfig::default().into()); - state - .apply(&ForgeEvent::new( - id, - 1, - None, - Some(CommandId::new()), - ForgeEventKind::SessionCreated, - )) - .unwrap(); - state - } - - fn event(state: &SessionSnapshot, turn: Option, kind: ForgeEventKind) -> ForgeEvent { - ForgeEvent::new( - state.id.clone(), - state.last_seq + 1, - turn, - Some(CommandId::new()), - kind, - ) - } - - #[test] - fn enforces_single_active_turn() { - let mut state = state(); - let turn = TurnId::new(); - state - .apply(&event( - &state, - Some(turn.clone()), - ForgeEventKind::TurnStarted { - input: "one".into(), - }, - )) - .unwrap(); - let second = event( - &state, - Some(TurnId::new()), - ForgeEventKind::TurnStarted { - input: "two".into(), - }, - ); - assert!(matches!( - state.apply(&second), - Err(ForgeProtocolError::SessionBusy(_)) - )); - } - - #[test] - fn cancellation_is_not_terminal_until_cancelled_event() { - let mut state = state(); - let turn = TurnId::new(); - state - .apply(&event( - &state, - Some(turn.clone()), - ForgeEventKind::TurnStarted { - input: "one".into(), - }, - )) - .unwrap(); - state - .apply(&event( - &state, - Some(turn.clone()), - ForgeEventKind::TurnCancelRequested, - )) - .unwrap(); - assert_eq!(state.active_turn, Some(turn.clone())); - assert_eq!(state.turns[&turn].status, TurnStatus::Cancelling); - - state - .apply(&event( - &state, - Some(turn.clone()), - ForgeEventKind::TurnCancelled, - )) - .unwrap(); - assert_eq!(state.active_turn, None); - assert_eq!(state.turns[&turn].status, TurnStatus::Cancelled); - } - - #[test] - fn rejects_event_sequence_gaps() { - let mut state = state(); - let event = ForgeEvent::new( - state.id.clone(), - state.last_seq + 2, - Some(TurnId::new()), - None, - ForgeEventKind::TurnStarted { - input: "gap".into(), - }, - ); - assert!(matches!( - state.apply(&event), - Err(ForgeProtocolError::SequenceConflict { .. }) - )); - } -} diff --git a/crates/pulsing-forge/src/session/service.rs b/crates/pulsing-forge/src/session/service.rs deleted file mode 100644 index 979a2e669..000000000 --- a/crates/pulsing-forge/src/session/service.rs +++ /dev/null @@ -1,542 +0,0 @@ -use std::collections::{HashMap, VecDeque}; -use std::sync::Arc; - -use crate::agent::{AgentCancelled, AgentEvent, ForgeAgent}; -use crate::protocol::{ - CancelTurn, CommandEnvelope, CommandId, CommandReceipt, CreateSession, ForgeEvent, - ForgeEventKind, ForgeProtocolError, SessionId, StartTurn, TurnId, -}; -use crate::turn::TurnExecutionContext; -use tokio::sync::{Mutex, RwLock, broadcast}; - -use super::reducer::SessionSnapshot; -use super::store::{EventStore, InMemoryEventStore}; - -const EVENT_CHANNEL_CAPACITY: usize = 256; -const TURN_RESOURCE_CLEANUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); - -#[derive(Clone)] -pub struct ForgeService { - inner: Arc, -} - -struct ServiceInner { - store: Arc, - sessions: RwLock>>, -} - -struct SessionRuntime { - agent: Mutex, - control: Mutex, - events: broadcast::Sender, -} - -struct ControlState { - snapshot: SessionSnapshot, - receipts: HashMap, - active_execution: Option<(TurnId, Arc)>, -} - -pub struct EventSubscription { - replay: VecDeque, - live: broadcast::Receiver, - last_seq: u64, -} - -impl EventSubscription { - pub async fn recv(&mut self) -> Result { - if let Some(event) = self.replay.pop_front() { - self.last_seq = self.last_seq.max(event.seq); - return Ok(event); - } - loop { - match self.live.recv().await { - Ok(event) if event.seq <= self.last_seq => continue, - Ok(event) => { - self.last_seq = event.seq; - return Ok(event); - } - Err(broadcast::error::RecvError::Lagged(count)) => { - return Err(ForgeProtocolError::SubscriptionLagged(count)); - } - Err(broadcast::error::RecvError::Closed) => { - return Err(ForgeProtocolError::SubscriptionClosed); - } - } - } - } -} - -impl Default for ForgeService { - fn default() -> Self { - Self::new() - } -} - -impl ForgeService { - pub fn new() -> Self { - Self::with_store(Arc::new(InMemoryEventStore::new())) - } - - pub fn with_store(store: Arc) -> Self { - Self { - inner: Arc::new(ServiceInner { - store, - sessions: RwLock::new(HashMap::new()), - }), - } - } - - pub async fn create_session( - &self, - command: CommandEnvelope, - ) -> Result { - validate_command(&command)?; - if let Some(existing) = self - .inner - .sessions - .read() - .await - .get(&command.session_id) - .cloned() - { - let control = existing.control.lock().await; - return control - .receipts - .get(&command.command_id) - .cloned() - .ok_or_else(|| { - ForgeProtocolError::SessionAlreadyExists(command.session_id.clone()) - }); - } - - let agent = ForgeAgent::try_new(command.payload.spec.clone().into()) - .map_err(|err| ForgeProtocolError::Agent(err.to_string()))?; - let (event_tx, _) = broadcast::channel(EVENT_CHANNEL_CAPACITY); - let mut snapshot = - SessionSnapshot::uninitialized(command.session_id.clone(), command.payload.spec); - let event = ForgeEvent::new( - command.session_id.clone(), - 1, - None, - Some(command.command_id.clone()), - ForgeEventKind::SessionCreated, - ); - self.inner.store.append(event.clone())?; - snapshot.apply(&event)?; - let receipt = CommandReceipt { - command_id: command.command_id.clone(), - session_id: command.session_id.clone(), - turn_id: None, - accepted_seq: event.seq, - }; - let runtime = Arc::new(SessionRuntime { - agent: Mutex::new(agent), - control: Mutex::new(ControlState { - snapshot, - receipts: HashMap::from([(command.command_id, receipt.clone())]), - active_execution: None, - }), - events: event_tx, - }); - - let mut sessions = self.inner.sessions.write().await; - if sessions.contains_key(&command.session_id) { - return Err(ForgeProtocolError::SessionAlreadyExists(command.session_id)); - } - sessions.insert(receipt.session_id.clone(), runtime); - Ok(receipt) - } - - pub async fn start_turn( - &self, - command: CommandEnvelope, - ) -> Result { - validate_command(&command)?; - let runtime = self.session(&command.session_id).await?; - let execution = Arc::new(TurnExecutionContext::new( - command.session_id.clone(), - command.payload.turn_id.clone(), - )); - let event; - let receipt; - { - let mut control = runtime.control.lock().await; - if let Some(existing) = control.receipts.get(&command.command_id) { - return Ok(existing.clone()); - } - check_expected_seq(command.expected_seq, control.snapshot.last_seq)?; - control.snapshot.ensure_can_start()?; - - event = ForgeEvent::new( - command.session_id.clone(), - control.snapshot.last_seq + 1, - Some(command.payload.turn_id.clone()), - Some(command.command_id.clone()), - ForgeEventKind::TurnStarted { - input: command.payload.input.clone(), - }, - ); - self.inner.store.append(event.clone())?; - control.snapshot.apply(&event)?; - control.active_execution = Some((command.payload.turn_id.clone(), execution.clone())); - receipt = CommandReceipt { - command_id: command.command_id.clone(), - session_id: command.session_id.clone(), - turn_id: Some(command.payload.turn_id.clone()), - accepted_seq: event.seq, - }; - control - .receipts - .insert(command.command_id.clone(), receipt.clone()); - } - let _ = runtime.events.send(event); - - let service = self.clone(); - let session_id = command.session_id; - let turn_id = command.payload.turn_id; - let input = command.payload.input; - tokio::spawn(async move { - service - .run_turn_task(runtime, session_id, turn_id, input, execution) - .await; - }); - Ok(receipt) - } - - pub async fn cancel_turn( - &self, - command: CommandEnvelope, - ) -> Result { - validate_command(&command)?; - let runtime = self.session(&command.session_id).await?; - let event; - let receipt; - let execution; - { - let mut control = runtime.control.lock().await; - if let Some(existing) = control.receipts.get(&command.command_id) { - return Ok(existing.clone()); - } - check_expected_seq(command.expected_seq, control.snapshot.last_seq)?; - let Some((active_turn, active_execution)) = control.active_execution.as_ref() else { - return Err(ForgeProtocolError::TurnNotActive(command.payload.turn_id)); - }; - if active_turn != &command.payload.turn_id { - return Err(ForgeProtocolError::TurnNotActive(command.payload.turn_id)); - } - execution = active_execution.clone(); - event = ForgeEvent::new( - command.session_id.clone(), - control.snapshot.last_seq + 1, - Some(command.payload.turn_id.clone()), - Some(command.command_id.clone()), - ForgeEventKind::TurnCancelRequested, - ); - self.inner.store.append(event.clone())?; - control.snapshot.apply(&event)?; - receipt = CommandReceipt { - command_id: command.command_id.clone(), - session_id: command.session_id.clone(), - turn_id: Some(command.payload.turn_id.clone()), - accepted_seq: event.seq, - }; - control.receipts.insert(command.command_id, receipt.clone()); - } - let _ = runtime.events.send(event); - execution.cancel(); - Ok(receipt) - } - - pub async fn snapshot( - &self, - session_id: &SessionId, - ) -> Result { - let runtime = self.session(session_id).await?; - let snapshot = runtime.control.lock().await.snapshot.clone(); - Ok(snapshot) - } - - pub async fn subscribe( - &self, - session_id: &SessionId, - after_seq: u64, - ) -> Result { - let runtime = self.session(session_id).await?; - // Subscribe before loading history so events emitted during the load are - // either present in replay or in the live channel. Consumers deduplicate. - let live = runtime.events.subscribe(); - let replay = self.inner.store.load(session_id, after_seq)?.into(); - Ok(EventSubscription { - replay, - live, - last_seq: after_seq, - }) - } - - async fn session( - &self, - session_id: &SessionId, - ) -> Result, ForgeProtocolError> { - self.inner - .sessions - .read() - .await - .get(session_id) - .cloned() - .ok_or_else(|| ForgeProtocolError::SessionNotFound(session_id.clone())) - } - - async fn run_turn_task( - &self, - runtime: Arc, - session_id: SessionId, - turn_id: TurnId, - input: String, - execution: Arc, - ) { - let observer_service = self.clone(); - let observer_runtime = runtime.clone(); - let observer_turn = turn_id.clone(); - let observer = Arc::new(move |agent_event: AgentEvent| { - let service = observer_service.clone(); - let runtime = observer_runtime.clone(); - let turn = observer_turn.clone(); - Box::pin(async move { - let kind = match agent_event { - AgentEvent::TextDelta(delta) => Some(ForgeEventKind::TurnOutputDelta { delta }), - AgentEvent::ToolStart { name } => Some(ForgeEventKind::ToolStarted { name }), - AgentEvent::ToolEnd { name, ok, summary } => { - Some(ForgeEventKind::ToolCompleted { name, ok, summary }) - } - AgentEvent::ToolCancelled { name } => { - Some(ForgeEventKind::ToolCancelled { name }) - } - AgentEvent::Error(_) | AgentEvent::Done { .. } | AgentEvent::Cancelled => None, - }; - if let Some(kind) = kind { - let _ = service.record_event(&runtime, Some(turn), None, kind).await; - } - }) as std::pin::Pin + Send>> - }); - - let result = { - let mut agent = runtime.agent.lock().await; - agent.set_event_handler(Some(observer)); - let result = agent.run_in_turn(&input, execution.clone()).await; - agent.set_event_handler(None); - result - }; - - if !execution - .cleanup_and_wait(TURN_RESOURCE_CLEANUP_TIMEOUT) - .await - { - let _ = self - .record_event( - &runtime, - Some(turn_id.clone()), - None, - ForgeEventKind::TurnCleanupStalled { - resources: execution.resources().active_kinds(), - }, - ) - .await; - execution.resources().wait_for_idle_unbounded().await; - } - - let kind = match result { - _ if execution.is_cancelled() => ForgeEventKind::TurnCancelled, - Ok(text) => ForgeEventKind::TurnCompleted { text }, - Err(err) if err.downcast_ref::().is_some() => { - ForgeEventKind::TurnCancelled - } - Err(err) => ForgeEventKind::TurnFailed { - message: err.to_string(), - }, - }; - let _ = self - .record_terminal_event(&runtime, &session_id, turn_id, kind) - .await; - } - - async fn record_event( - &self, - runtime: &SessionRuntime, - turn_id: Option, - causation_id: Option, - kind: ForgeEventKind, - ) -> Result { - let event; - { - let mut control = runtime.control.lock().await; - event = ForgeEvent::new( - control.snapshot.id.clone(), - control.snapshot.last_seq + 1, - turn_id, - causation_id, - kind, - ); - self.inner.store.append(event.clone())?; - control.snapshot.apply(&event)?; - } - let _ = runtime.events.send(event.clone()); - Ok(event) - } - - async fn record_terminal_event( - &self, - runtime: &SessionRuntime, - session_id: &SessionId, - turn_id: TurnId, - kind: ForgeEventKind, - ) -> Result { - let event; - { - let mut control = runtime.control.lock().await; - event = ForgeEvent::new( - session_id.clone(), - control.snapshot.last_seq + 1, - Some(turn_id.clone()), - None, - kind, - ); - self.inner.store.append(event.clone())?; - control.snapshot.apply(&event)?; - if control - .active_execution - .as_ref() - .is_some_and(|(active, _)| active == &turn_id) - { - control.active_execution = None; - } - } - let _ = runtime.events.send(event.clone()); - Ok(event) - } -} - -fn check_expected_seq(expected: Option, actual: u64) -> Result<(), ForgeProtocolError> { - if let Some(expected) = expected - && expected != actual - { - return Err(ForgeProtocolError::SequenceConflict { expected, actual }); - } - Ok(()) -} - -fn validate_command(command: &CommandEnvelope) -> Result<(), ForgeProtocolError> { - if command.protocol != "forge.session" { - return Err(ForgeProtocolError::InvalidProtocol { - expected: "forge.session", - actual: command.protocol.clone(), - }); - } - if command.version.major != 1 { - return Err(ForgeProtocolError::UnsupportedVersion { - protocol: command.protocol.clone(), - major: command.version.major, - }); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::agent::AgentConfig; - use crate::protocol::{CreateSession, SessionSpec}; - - async fn create(service: &ForgeService) -> (SessionId, CommandReceipt) { - let session_id = SessionId::new(); - let command = CommandEnvelope::new( - CommandId::new(), - session_id.clone(), - CreateSession { - spec: SessionSpec::from(AgentConfig { - provider: "demo".into(), - model: "demo".into(), - ..AgentConfig::default() - }), - }, - ); - let receipt = service.create_session(command).await.unwrap(); - (session_id, receipt) - } - - #[tokio::test] - async fn duplicate_start_command_is_idempotent() { - let service = ForgeService::new(); - let (session, _) = create(&service).await; - let command_id = CommandId::new(); - let command = CommandEnvelope::new( - command_id, - session.clone(), - StartTurn { - turn_id: TurnId::new(), - input: "hello".into(), - }, - ); - let first = service.start_turn(command.clone()).await.unwrap(); - let second = service.start_turn(command).await.unwrap(); - assert_eq!(first, second); - } - - #[tokio::test] - async fn rejects_unsupported_command_major_version() { - let service = ForgeService::new(); - let session_id = SessionId::new(); - let mut command = CommandEnvelope::new( - CommandId::new(), - session_id, - CreateSession { - spec: AgentConfig::default().into(), - }, - ); - command.version.major = 2; - assert!(matches!( - service.create_session(command).await, - Err(ForgeProtocolError::UnsupportedVersion { major: 2, .. }) - )); - } - - #[tokio::test] - async fn subscription_replays_from_cursor() { - let service = ForgeService::new(); - let (session, created) = create(&service).await; - let events = service.inner.store.load(&session, 0).unwrap(); - assert_eq!(events.len(), 1); - assert_eq!(events[0].seq, created.accepted_seq); - - let mut subscription = service.subscribe(&session, 0).await.unwrap(); - let replay = subscription.recv().await.unwrap(); - assert!(matches!(replay.kind, ForgeEventKind::SessionCreated)); - } - - #[tokio::test] - async fn local_client_runs_multiple_turns_in_one_session() { - let client = super::super::LocalForgeClient::default(); - let session = client - .create_session(AgentConfig { - provider: "demo".into(), - model: "demo".into(), - ..AgentConfig::default() - }) - .await - .unwrap(); - let first = client - .run_turn(session.clone(), "remember alpha") - .await - .unwrap(); - let second = client - .run_turn(session.clone(), "remember beta") - .await - .unwrap(); - assert!(first.contains("alpha")); - assert!(second.contains("beta")); - - let snapshot = client.snapshot(&session).await.unwrap(); - assert_eq!(snapshot.turns.len(), 2); - assert!(snapshot.active_turn.is_none()); - } -} diff --git a/crates/pulsing-forge/src/session/store.rs b/crates/pulsing-forge/src/session/store.rs deleted file mode 100644 index 3e9c50d8b..000000000 --- a/crates/pulsing-forge/src/session/store.rs +++ /dev/null @@ -1,96 +0,0 @@ -use std::collections::HashMap; -use std::sync::Mutex; - -use crate::protocol::{ForgeEvent, ForgeProtocolError, SessionId}; - -pub trait EventStore: Send + Sync { - fn append(&self, event: ForgeEvent) -> Result<(), ForgeProtocolError>; - fn load( - &self, - session_id: &SessionId, - after_seq: u64, - ) -> Result, ForgeProtocolError>; -} - -#[derive(Default)] -pub struct InMemoryEventStore { - events: Mutex>>, -} - -impl InMemoryEventStore { - pub fn new() -> Self { - Self::default() - } -} - -impl EventStore for InMemoryEventStore { - fn append(&self, event: ForgeEvent) -> Result<(), ForgeProtocolError> { - let mut all = self - .events - .lock() - .map_err(|_| ForgeProtocolError::Internal("event store lock poisoned".into()))?; - let events = all.entry(event.session_id.clone()).or_default(); - let expected = events.last().map_or(1, |last| last.seq + 1); - if event.seq != expected { - return Err(ForgeProtocolError::SequenceConflict { - expected, - actual: event.seq, - }); - } - events.push(event); - Ok(()) - } - - fn load( - &self, - session_id: &SessionId, - after_seq: u64, - ) -> Result, ForgeProtocolError> { - let all = self - .events - .lock() - .map_err(|_| ForgeProtocolError::Internal("event store lock poisoned".into()))?; - Ok(all - .get(session_id) - .into_iter() - .flatten() - .filter(|event| event.seq > after_seq) - .cloned() - .collect()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::protocol::{ForgeEventKind, SessionId}; - - #[test] - fn append_requires_contiguous_sequence() { - let store = InMemoryEventStore::new(); - let session = SessionId::new(); - store - .append(ForgeEvent::new( - session.clone(), - 1, - None, - None, - ForgeEventKind::SessionCreated, - )) - .unwrap(); - let result = store.append(ForgeEvent::new( - session, - 3, - None, - None, - ForgeEventKind::SessionClosed, - )); - assert!(matches!( - result, - Err(ForgeProtocolError::SequenceConflict { - expected: 2, - actual: 3 - }) - )); - } -} diff --git a/crates/pulsing-forge/src/session_input.rs b/crates/pulsing-forge/src/session_input.rs deleted file mode 100644 index 6e252b1ec..000000000 --- a/crates/pulsing-forge/src/session_input.rs +++ /dev/null @@ -1,271 +0,0 @@ -//! Codex-compatible `request_user_input` argument validation. - -use serde::{Deserialize, Serialize}; - -use crate::error::ToolError; - -pub const MIN_AUTO_RESOLUTION_MS: u64 = 60_000; -pub const MAX_AUTO_RESOLUTION_MS: u64 = 240_000; - -#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] -pub struct RequestUserInputQuestionOption { - pub label: String, - pub description: String, -} - -#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] -pub struct RequestUserInputQuestion { - pub id: String, - pub header: String, - pub question: String, - #[serde(rename = "isOther", default)] - pub is_other: bool, - #[serde(rename = "isSecret", default)] - pub is_secret: bool, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub options: Option>, -} - -#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] -pub struct RequestUserInputArgs { - pub questions: Vec, - #[serde( - rename = "autoResolutionMs", - default, - skip_serializing_if = "Option::is_none" - )] - pub auto_resolution_ms: Option, -} - -pub fn validate_request_user_input( - value: &serde_json::Value, -) -> Result { - match value.get("questions") { - None => { - return Err(ToolError::respond( - "request_user_input requires at least one question", - )); - } - Some(serde_json::Value::Array(items)) if items.is_empty() => { - return Err(ToolError::respond( - "request_user_input requires at least one question", - )); - } - Some(serde_json::Value::Array(items)) => { - for item in items { - if !item.is_object() { - return Err(ToolError::respond("each question must be an object")); - } - } - } - Some(_) => { - return Err(ToolError::respond("field 'questions' must be a list")); - } - } - - let auto_resolution_ms = parse_auto_resolution_ms(value)?; - - let mut cleaned = value.clone(); - if let Some(obj) = cleaned.as_object_mut() { - obj.remove("autoResolutionMs"); - obj.remove("auto_resolution_ms"); - } - - let mut args: RequestUserInputArgs = serde_json::from_value(cleaned) - .map_err(|e| ToolError::respond(format!("invalid request_user_input arguments: {e}")))?; - args.auto_resolution_ms = auto_resolution_ms; - normalize_request_user_input_strings(&mut args); - let mut seen = std::collections::HashSet::new(); - for q in &args.questions { - if q.id.is_empty() { - return Err(ToolError::respond("each question requires a non-empty id")); - } - if q.question.is_empty() { - return Err(ToolError::respond(format!( - "question {:?} requires non-empty question text", - q.id - ))); - } - if !seen.insert(q.id.clone()) { - return Err(ToolError::respond(format!( - "duplicate question id {:?}", - q.id - ))); - } - if let Some(opts) = &q.options { - if opts.is_empty() { - return Err(ToolError::respond(format!( - "question {:?} has empty options array", - q.id - ))); - } - for opt in opts { - if opt.label.is_empty() { - return Err(ToolError::respond(format!( - "question {:?} has option with empty label", - q.id - ))); - } - } - } - } - Ok(args) -} - -fn normalize_request_user_input_strings(args: &mut RequestUserInputArgs) { - for q in &mut args.questions { - q.id = q.id.trim().to_string(); - q.question = q.question.trim().to_string(); - if let Some(opts) = &mut q.options { - for opt in opts { - opt.label = opt.label.trim().to_string(); - } - } - } -} - -fn parse_auto_resolution_ms(value: &serde_json::Value) -> Result, ToolError> { - let raw = value - .get("autoResolutionMs") - .or_else(|| value.get("auto_resolution_ms")); - let Some(raw) = raw else { - return Ok(None); - }; - let ms = match raw { - serde_json::Value::Number(n) => n - .as_u64() - .or_else(|| n.as_i64().and_then(|i| u64::try_from(i).ok())), - _ => None, - }; - ms.map(normalize_auto_resolution_ms) - .ok_or_else(|| { - ToolError::respond(format!("autoResolutionMs must be an integer, got {raw:?}")) - }) - .map(Some) -} - -pub fn normalize_auto_resolution_ms(ms: u64) -> u64 { - ms.clamp(MIN_AUTO_RESOLUTION_MS, MAX_AUTO_RESOLUTION_MS) -} - -pub fn normalize_request_user_input(mut args: RequestUserInputArgs) -> RequestUserInputArgs { - if let Some(ms) = args.auto_resolution_ms { - args.auto_resolution_ms = Some(normalize_auto_resolution_ms(ms)); - } - args -} - -pub fn args_to_value(args: &RequestUserInputArgs) -> serde_json::Value { - serde_json::to_value(args).expect("RequestUserInputArgs serializes") -} - -pub fn default_auto_answers(args: &RequestUserInputArgs) -> serde_json::Value { - let mut answers = serde_json::Map::new(); - for q in &args.questions { - let default_answer = q - .options - .as_ref() - .and_then(|o| o.first()) - .map(|o| o.label.clone()) - .unwrap_or_default(); - answers.insert( - q.id.clone(), - serde_json::json!({ "answers": [default_answer] }), - ); - } - serde_json::json!({ "answers": answers }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn rejects_empty_questions() { - let raw = serde_json::json!({ "questions": [] }); - assert!(validate_request_user_input(&raw).is_err()); - } - - #[test] - fn accepts_valid_payload() { - let raw = serde_json::json!({ - "questions": [{ - "id": "q1", - "header": "Pick", - "question": "Which?", - "options": [{"label": "A", "description": "first"}] - }], - "autoResolutionMs": 5000 - }); - let args = validate_request_user_input(&raw).unwrap(); - assert_eq!(args.questions.len(), 1); - assert_eq!(args.auto_resolution_ms, Some(MIN_AUTO_RESOLUTION_MS)); - } - - #[test] - fn clamps_auto_resolution_to_max() { - let raw = serde_json::json!({ - "questions": [{"id": "q1", "header": "H", "question": "Q?"}], - "autoResolutionMs": 999_999_999 - }); - let args = validate_request_user_input(&raw).unwrap(); - assert_eq!(args.auto_resolution_ms, Some(MAX_AUTO_RESOLUTION_MS)); - } - - #[test] - fn rejects_non_list_questions() { - let raw = serde_json::json!({ "questions": "not-a-list" }); - let err = validate_request_user_input(&raw).unwrap_err(); - assert_eq!(err.to_string(), "field 'questions' must be a list"); - } - - #[test] - fn rejects_malformed_auto_resolution_ms() { - let raw = serde_json::json!({ - "questions": [{"id": "q1", "header": "H", "question": "Q?"}], - "autoResolutionMs": "soon" - }); - let err = validate_request_user_input(&raw).unwrap_err(); - assert!( - err.to_string() - .contains("autoResolutionMs must be an integer") - ); - } - - #[test] - fn accepts_auto_resolution_ms_snake_case_alias() { - let raw = serde_json::json!({ - "questions": [{"id": "q1", "header": "H", "question": "Q?"}], - "auto_resolution_ms": 90_000 - }); - let args = validate_request_user_input(&raw).unwrap(); - assert_eq!(args.auto_resolution_ms, Some(90_000)); - } - - #[test] - fn default_auto_answers_matches_codex_response_shape() { - let args = validate_request_user_input(&serde_json::json!({ - "questions": [{ - "id": " q1 ", - "header": "Pick", - "question": " Which? ", - "options": [{"label": " A ", "description": "first"}] - }] - })) - .unwrap(); - assert_eq!(args.questions[0].id, "q1"); - let out = default_auto_answers(&args); - assert_eq!(out["answers"]["q1"]["answers"], serde_json::json!(["A"])); - } - - #[test] - fn args_to_value_emits_clamped_timeout() { - let args = validate_request_user_input(&serde_json::json!({ - "questions": [{"id": "q1", "header": "H", "question": "Q?"}], - "autoResolutionMs": 1 - })) - .unwrap(); - let payload = args_to_value(&args); - assert_eq!(payload["autoResolutionMs"], MIN_AUTO_RESOLUTION_MS); - } -} diff --git a/crates/pulsing-forge/src/turn.rs b/crates/pulsing-forge/src/turn.rs deleted file mode 100644 index cb3bf61d4..000000000 --- a/crates/pulsing-forge/src/turn.rs +++ /dev/null @@ -1,228 +0,0 @@ -//! Turn-scoped cancellation and resource ownership. - -use std::collections::HashMap; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, Weak}; -use std::time::{Duration, Instant}; - -use tokio::sync::Notify; -use tokio_util::sync::CancellationToken; - -use crate::protocol::{SessionId, TurnId}; - -type CancelResource = Arc; - -struct ResourceEntry { - kind: String, - cancel: CancelResource, -} - -/// Registry of external resources owned by one Forge turn. -/// -/// A resource stays registered until its guard is dropped. Cancellation first -/// invokes every registered resource's non-blocking canceller; terminal turn -/// events may then wait until all guards have been released. -pub struct TurnResourceRegistry { - next_id: AtomicU64, - entries: Mutex>, - idle: Notify, -} - -impl Default for TurnResourceRegistry { - fn default() -> Self { - Self { - next_id: AtomicU64::new(1), - entries: Mutex::new(HashMap::new()), - idle: Notify::new(), - } - } -} - -impl TurnResourceRegistry { - pub fn register( - self: &Arc, - kind: impl Into, - cancel: impl Fn() + Send + Sync + 'static, - ) -> TurnResourceGuard { - let id = self.next_id.fetch_add(1, Ordering::Relaxed); - self.entries.lock().expect("turn resources").insert( - id, - ResourceEntry { - kind: kind.into(), - cancel: Arc::new(cancel), - }, - ); - TurnResourceGuard { - registry: Arc::downgrade(self), - id, - } - } - - pub fn register_passive(self: &Arc, kind: impl Into) -> TurnResourceGuard { - self.register(kind, || {}) - } - - pub fn cancel_all(&self) { - let cancellers = self - .entries - .lock() - .expect("turn resources") - .values() - .map(|entry| entry.cancel.clone()) - .collect::>(); - for cancel in cancellers { - cancel(); - } - } - - pub fn active_count(&self) -> usize { - self.entries.lock().expect("turn resources").len() - } - - pub fn active_kinds(&self) -> Vec { - self.entries - .lock() - .expect("turn resources") - .values() - .map(|entry| entry.kind.clone()) - .collect() - } - - pub async fn wait_for_idle(&self, timeout: Duration) -> bool { - let deadline = Instant::now() + timeout; - loop { - let notified = self.idle.notified(); - if self.active_count() == 0 { - return true; - } - let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { - return false; - }; - if tokio::time::timeout(remaining, notified).await.is_err() { - return self.active_count() == 0; - } - } - } - - pub async fn wait_for_idle_unbounded(&self) { - loop { - let notified = self.idle.notified(); - if self.active_count() == 0 { - return; - } - notified.await; - } - } - - fn release(&self, id: u64) { - if self - .entries - .lock() - .expect("turn resources") - .remove(&id) - .is_some() - { - self.idle.notify_waiters(); - } - } -} - -/// RAII ownership token for one external turn resource. -pub struct TurnResourceGuard { - registry: Weak, - id: u64, -} - -impl Drop for TurnResourceGuard { - fn drop(&mut self) { - if let Some(registry) = self.registry.upgrade() { - registry.release(self.id); - } - } -} - -/// Execution identity, cancellation signal, and resource registry for one turn. -pub struct TurnExecutionContext { - pub session_id: SessionId, - pub turn_id: TurnId, - cancellation: CancellationToken, - resources: Arc, -} - -impl TurnExecutionContext { - pub fn new(session_id: SessionId, turn_id: TurnId) -> Self { - Self::with_cancellation(session_id, turn_id, CancellationToken::new()) - } - - pub fn with_cancellation( - session_id: SessionId, - turn_id: TurnId, - cancellation: CancellationToken, - ) -> Self { - Self { - session_id, - turn_id, - cancellation, - resources: Arc::new(TurnResourceRegistry::default()), - } - } - - pub fn cancellation(&self) -> CancellationToken { - self.cancellation.clone() - } - - pub fn is_cancelled(&self) -> bool { - self.cancellation.is_cancelled() - } - - pub fn resources(&self) -> &Arc { - &self.resources - } - - pub fn cancel(&self) { - self.cancellation.cancel(); - self.resources.cancel_all(); - } - - pub async fn cancel_and_wait(&self, timeout: Duration) -> bool { - self.cancel(); - self.resources.wait_for_idle(timeout).await - } - - pub async fn cleanup_and_wait(&self, timeout: Duration) -> bool { - self.resources.cancel_all(); - self.resources.wait_for_idle(timeout).await - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::AtomicBool; - - #[tokio::test] - async fn cancellation_invokes_resources_and_waits_for_release() { - let turn = TurnExecutionContext::new(SessionId::new(), TurnId::new()); - let cancelled = Arc::new(AtomicBool::new(false)); - let flag = cancelled.clone(); - let guard = turn - .resources() - .register("test", move || flag.store(true, Ordering::SeqCst)); - - turn.cancel(); - assert!(cancelled.load(Ordering::SeqCst)); - assert_eq!(turn.resources().active_kinds(), vec!["test"]); - assert!( - !turn - .resources() - .wait_for_idle(Duration::from_millis(10)) - .await - ); - drop(guard); - assert!( - turn.resources() - .wait_for_idle(Duration::from_millis(10)) - .await - ); - } -} diff --git a/crates/pulsing-forge/src/unified_exec.rs b/crates/pulsing-forge/src/unified_exec.rs deleted file mode 100644 index af45c722a..000000000 --- a/crates/pulsing-forge/src/unified_exec.rs +++ /dev/null @@ -1,1027 +0,0 @@ -//! UnifiedExec session store — `exec_command` + `write_stdin`. - -use std::collections::HashMap; -use std::path::Path; -use std::sync::Arc; -use std::sync::atomic::{AtomicI32, Ordering}; -use std::time::Instant; - -use serde_json::Value; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command}; -use tokio::sync::Mutex; -use tokio::task::JoinHandle; - -use crate::approval::{ - args_dangerously_disable_sandbox, effective_sandbox_policy, ensure_shell_allowed, -}; -use crate::context::ToolCallContext; -use crate::error::ToolError; -use crate::exec_output::{ - DEFAULT_MAX_OUTPUT_TOKENS, ExecCommandOutput, ExecOutputDelta, ExecStream, MAX_STDIN_BYTES, - OutputBuffer, SHELL_MAX_BYTES, Utf8ChunkDecoder, clamp_yield_ms, -}; -use crate::handlers::shell_exec::resolve_shell_workdir; -use crate::process_group; -use crate::pty_session::PtyExecHandle; -use crate::result::ToolResult; -use crate::sandbox::{SandboxPolicy, build_bash_exec}; -use crate::turn::TurnResourceGuard; - -pub struct UnifiedExecManager { - next_id: AtomicI32, - sessions: Mutex>, -} - -enum SessionHandle { - Pipe { - child: Child, - stdin: Option, - process_id: Option, - }, - Pty(PtyExecHandle), -} - -struct ExecSession { - handle: SessionHandle, - buffer: Arc>, - _reader: Option>, - started: Instant, - tty: bool, - owner_turn: Option, - _turn_resource: Option, -} - -impl Drop for ExecSession { - fn drop(&mut self) { - match &mut self.handle { - SessionHandle::Pipe { - child, process_id, .. - } => { - if let Some(process_id) = process_id { - process_group::kill(*process_id); - } - if matches!(child.try_wait(), Ok(None)) { - let _ = child.start_kill(); - } - } - SessionHandle::Pty(pty) => { - let _ = pty.kill(); - } - } - } -} - -#[derive(Debug, Clone)] -pub struct ExecSessionSummary { - pub id: i32, - pub elapsed_secs: f64, - pub tty: bool, -} - -impl Default for UnifiedExecManager { - fn default() -> Self { - Self::new() - } -} - -impl Drop for UnifiedExecManager { - fn drop(&mut self) { - // Best-effort cleanup: hosts that forget to call `stop_all()` before - // dropping the manager (e.g. a panicking caller, or a Python binding - // that never invokes `close()`) would otherwise leak child processes - // and PTY reader threads for every still-running exec_command session. - let Ok(mut sessions) = self.sessions.try_lock() else { - return; - }; - for (_, session) in sessions.drain() { - drop(session); - } - } -} - -impl UnifiedExecManager { - pub fn new() -> Self { - Self { - next_id: AtomicI32::new(1), - sessions: Mutex::new(HashMap::new()), - } - } - - pub async fn exec_command( - self: &Arc, - ctx: &ToolCallContext, - args: &Value, - ) -> Result { - let cmd = args - .get("cmd") - .or_else(|| args.get("command")) - .and_then(|v| v.as_str()) - .ok_or_else(|| ToolError::respond("missing cmd/command"))?; - let login = args.get("login").and_then(|v| v.as_bool()).unwrap_or(false); - let yield_ms = clamp_yield_ms(args.get("yield_time_ms").and_then(|v| v.as_u64())); - let max_tokens = args - .get("max_output_tokens") - .and_then(|v| v.as_u64()) - .map(|v| v as usize) - .unwrap_or(DEFAULT_MAX_OUTPUT_TOKENS); - - ensure_shell_allowed(ctx, args, cmd)?; - let policy = effective_sandbox_policy(ctx, args); - let dangerous = args_dangerously_disable_sandbox(ctx, args); - let workdir = resolve_shell_workdir(ctx, args)?; - let tty = args.get("tty").and_then(|v| v.as_bool()).unwrap_or(true); - - let session_id = self.next_id.fetch_add(1, Ordering::SeqCst); - let turn_resource = ctx.turn.as_ref().map(|turn| { - let weak_manager = Arc::downgrade(self); - turn.resources() - .register(format!("exec:{session_id}"), move || { - let Some(manager) = weak_manager.upgrade() else { - return; - }; - let Ok(runtime) = tokio::runtime::Handle::try_current() else { - return; - }; - runtime.spawn(async move { - manager.stop_session_and_wait(session_id).await; - }); - }) - }); - let buffer = Arc::new(Mutex::new(OutputBuffer::new(SHELL_MAX_BYTES))); - let on_delta = stream_hook(ctx, session_id); - - let (handle, reader) = if tty { - let pty = spawn_pty_exec( - cmd, - &workdir, - login, - policy, - dangerous, - buffer.clone(), - session_id, - on_delta, - )?; - (SessionHandle::Pty(pty), None) - } else { - let (child, stdin, reader) = spawn_pipe_session( - cmd, - &workdir, - login, - policy, - dangerous, - buffer.clone(), - session_id, - on_delta, - ) - .await?; - let process_id = child.id(); - ( - SessionHandle::Pipe { - child, - stdin, - process_id, - }, - Some(reader), - ) - }; - - self.sessions.lock().await.insert( - session_id, - ExecSession { - handle, - buffer: buffer.clone(), - _reader: reader, - started: Instant::now(), - tty, - owner_turn: ctx.turn.as_ref().map(|turn| turn.turn_id.clone()), - _turn_resource: turn_resource, - }, - ); - - if let Some(turn) = &ctx.turn { - let cancellation = turn.cancellation(); - tokio::select! { - _ = cancellation.cancelled() => { - self.stop_session_and_wait(session_id).await; - return Ok(ToolResult::err("exec session cancelled")); - } - _ = tokio::time::sleep(std::time::Duration::from_millis(yield_ms)) => {} - } - } else { - tokio::time::sleep(std::time::Duration::from_millis(yield_ms)).await; - } - self.poll_session(session_id, max_tokens, ctx).await - } - - pub async fn write_stdin( - &self, - ctx: &ToolCallContext, - args: &Value, - ) -> Result { - let session_id = parse_session_id(args.get("session_id"))?; - let chars = args - .get("chars") - .or_else(|| args.get("input")) - .and_then(|v| v.as_str()) - .ok_or_else(|| ToolError::respond("missing chars"))?; - let byte_len = chars.len(); - if byte_len > MAX_STDIN_BYTES { - return Ok(ToolResult::err(format!( - "stdin input too large: {byte_len} bytes (max {MAX_STDIN_BYTES})" - ))); - } - let yield_ms = clamp_yield_ms(args.get("yield_time_ms").and_then(|v| v.as_u64())); - let max_tokens = args - .get("max_output_tokens") - .and_then(|v| v.as_u64()) - .map(|v| v as usize) - .unwrap_or(DEFAULT_MAX_OUTPUT_TOKENS); - - { - let mut sessions = self.sessions.lock().await; - let session = sessions - .get_mut(&session_id) - .ok_or_else(|| ToolError::respond(format!("unknown session_id {session_id}")))?; - if let Some(owner) = &session.owner_turn - && ctx.turn.as_ref().map(|turn| &turn.turn_id) != Some(owner) - { - return Ok(ToolResult::err(format!( - "session {session_id} belongs to another turn" - ))); - } - - if chars != "\x03" && session_has_exited(&mut session.handle) { - return Ok(ToolResult::err(format!( - "session {session_id} has already exited" - ))); - } - - if chars == "\x03" { - match &mut session.handle { - SessionHandle::Pipe { - child, process_id, .. - } => { - if let Some(process_id) = process_id { - process_group::kill(*process_id); - } - let _ = child.start_kill(); - } - SessionHandle::Pty(pty) => pty.kill()?, - } - } else if !session.tty { - return Ok(ToolResult::err( - "stdin writes require tty=true exec_command sessions", - )); - } else { - match &mut session.handle { - SessionHandle::Pipe { stdin, .. } => { - if let Some(stdin) = stdin.as_mut() { - stdin.write_all(chars.as_bytes()).await.map_err(|e| { - ToolError::respond(format!("write stdin failed: {e}")) - })?; - stdin.flush().await.map_err(|e| { - ToolError::respond(format!("flush stdin failed: {e}")) - })?; - } else { - return Ok(ToolResult::err("session stdin is closed")); - } - } - SessionHandle::Pty(pty) => pty.write_stdin(chars.as_bytes())?, - } - } - } - - tokio::time::sleep(std::time::Duration::from_millis(yield_ms)).await; - self.poll_session(session_id, max_tokens, ctx).await - } - - /// Active unified-exec sessions (for REPL `/ps`). - pub async fn list_sessions(&self) -> Vec { - let sessions = self.sessions.lock().await; - sessions - .iter() - .map(|(id, s)| ExecSessionSummary { - id: *id, - elapsed_secs: s.started.elapsed().as_secs_f64(), - tty: s.tty, - }) - .collect() - } - - /// Kill all background exec sessions (REPL `/stop` or `/clean`). - pub async fn stop_all(&self) -> usize { - let mut sessions = self.sessions.lock().await; - let removed = sessions - .drain() - .map(|(_, session)| session) - .collect::>(); - let count = removed.len(); - drop(sessions); - for session in removed { - session.terminate().await; - } - count - } - - async fn stop_session_and_wait(&self, session_id: i32) { - let session = self.sessions.lock().await.remove(&session_id); - if let Some(session) = session { - session.terminate().await; - } - } - - async fn poll_session( - &self, - session_id: i32, - max_tokens: usize, - ctx: &ToolCallContext, - ) -> Result { - let mut sessions = self.sessions.lock().await; - let session = sessions - .get_mut(&session_id) - .ok_or_else(|| ToolError::respond(format!("unknown session_id {session_id}")))?; - - let exit_code = match &mut session.handle { - SessionHandle::Pipe { child, .. } => match child.try_wait() { - Ok(Some(status)) => Some(status.code().unwrap_or(-1)), - Ok(None) => None, - Err(e) => return Ok(ToolResult::err(format!("wait failed: {e}"))), - }, - SessionHandle::Pty(pty) => pty.poll_exit_code(), - }; - - let wall = session.started.elapsed().as_secs_f64(); - let mut buf = session.buffer.lock().await; - buf.truncate_to_tokens(max_tokens); - let output = buf.snapshot(); - drop(buf); - - let structured = ExecCommandOutput::new( - output.clone(), - wall, - exit_code, - if exit_code.is_none() { - Some(session_id) - } else { - None - }, - ); - - if exit_code.is_some() { - sessions.remove(&session_id); - } - - let json = serde_json::to_string_pretty(&structured) - .map_err(|e| ToolError::respond(e.to_string()))?; - let is_error = exit_code.is_some_and(|c| c != 0); - let result = ToolResult { - content: json.clone(), - is_error, - structured: Some(serde_json::to_value(structured).unwrap_or(Value::Null)), - }; - - // Final snapshot delta for hosts that only listen to stream events. - let _ = ctx.session.on_exec_output_delta(ExecOutputDelta { - session_id, - stream: ExecStream::Pty, - chunk: output, - }); - - Ok(result) - } -} - -impl ExecSession { - async fn terminate(mut self) { - match &mut self.handle { - SessionHandle::Pipe { - child, process_id, .. - } => { - if let Some(process_id) = process_id.take() { - process_group::kill(process_id); - } - if matches!(child.try_wait(), Ok(None)) { - let _ = child.start_kill(); - } - let _ = tokio::time::timeout(std::time::Duration::from_secs(2), child.wait()).await; - } - SessionHandle::Pty(pty) => { - let _ = pty.kill(); - let deadline = Instant::now() + std::time::Duration::from_secs(2); - while pty.poll_exit_code().is_none() && Instant::now() < deadline { - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - } - } - if let Some(reader) = self._reader.take() { - let _ = tokio::time::timeout(std::time::Duration::from_secs(1), reader).await; - } - } -} - -fn stream_hook( - ctx: &ToolCallContext, - _session_id: i32, -) -> Option> { - let session = ctx.session.clone(); - Some(Arc::new(move |delta| { - let _ = session.on_exec_output_delta(delta); - })) -} - -fn spawn_pty_exec( - command: &str, - workdir: &Path, - login: bool, - policy: SandboxPolicy, - dangerous: bool, - buffer: Arc>, - session_id: i32, - on_delta: Option>, -) -> Result { - let plan = build_bash_exec(command, Some(workdir), policy, dangerous, login); - crate::pty_session::spawn_pty_exec(&plan, workdir, buffer, session_id, on_delta) -} - -fn parse_session_id(value: Option<&Value>) -> Result { - let Some(v) = value else { - return Err(ToolError::respond("missing session_id")); - }; - let id = if let Some(n) = v.as_i64() { - n - } else if let Some(s) = v.as_str() { - s.parse::() - .map_err(|_| ToolError::respond(format!("invalid session_id {s:?}")))? - } else { - return Err(ToolError::respond(format!("invalid session_id {v}"))); - }; - i32::try_from(id).map_err(|_| ToolError::respond(format!("invalid session_id {id}"))) -} - -fn session_has_exited(handle: &mut SessionHandle) -> bool { - match handle { - SessionHandle::Pipe { child, .. } => matches!(child.try_wait(), Ok(Some(_))), - SessionHandle::Pty(pty) => pty.poll_exit_code().is_some(), - } -} - -async fn spawn_pipe_session( - command: &str, - workdir: &Path, - login: bool, - policy: SandboxPolicy, - dangerous: bool, - buffer: Arc>, - session_id: i32, - on_delta: Option>, -) -> Result<(Child, Option, JoinHandle<()>), ToolError> { - let plan = build_bash_exec(command, Some(workdir), policy, dangerous, login); - let mut cmd = Command::new(&plan.argv[0]); - cmd.args(&plan.argv[1..]); - process_group::configure(&mut cmd); - cmd.kill_on_drop(true); - cmd.current_dir(workdir) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()); - if let Some(env) = &plan.env { - cmd.env_clear(); - for (k, v) in env { - cmd.env(k, v); - } - } - let mut child = cmd - .spawn() - .map_err(|e| ToolError::respond(format!("spawn failed: {e}")))?; - let stdin = child.stdin.take(); - let reader = spawn_stream_reader( - child.stdout.take(), - child.stderr.take(), - buffer, - session_id, - on_delta, - ); - Ok((child, stdin, reader)) -} - -fn spawn_stream_reader( - stdout: Option, - stderr: Option, - buffer: Arc>, - session_id: i32, - on_delta: Option>, -) -> JoinHandle<()> { - tokio::spawn(async move { - let mut out = stdout; - let mut err = stderr; - // Separate decoders per stream: stdout/stderr interleave independently, - // so a shared decoder could pair leftover bytes from one stream with - // bytes from the other and corrupt both. - let mut out_decoder = Utf8ChunkDecoder::default(); - let mut err_decoder = Utf8ChunkDecoder::default(); - let mut buf = [0u8; 4096]; - loop { - let mut progressed = false; - if let Some(s) = out.as_mut() { - match s.read(&mut buf).await { - Ok(0) => out = None, - Ok(n) => { - push_chunk( - &mut out_decoder, - &buffer, - session_id, - ExecStream::Stdout, - &buf[..n], - &on_delta, - ) - .await; - progressed = true; - } - Err(_) => out = None, - } - } - if let Some(e) = err.as_mut() { - match e.read(&mut buf).await { - Ok(0) => err = None, - Ok(n) => { - push_chunk( - &mut err_decoder, - &buffer, - session_id, - ExecStream::Stderr, - &buf[..n], - &on_delta, - ) - .await; - progressed = true; - } - Err(_) => err = None, - } - } - if out.is_none() && err.is_none() { - break; - } - if !progressed { - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - } - flush_decoder( - &mut out_decoder, - &buffer, - session_id, - ExecStream::Stdout, - &on_delta, - ) - .await; - flush_decoder( - &mut err_decoder, - &buffer, - session_id, - ExecStream::Stderr, - &on_delta, - ) - .await; - }) -} - -async fn push_chunk( - decoder: &mut Utf8ChunkDecoder, - buffer: &Arc>, - session_id: i32, - stream: ExecStream, - bytes: &[u8], - on_delta: &Option>, -) { - let chunk = decoder.decode(bytes); - if chunk.is_empty() { - return; - } - buffer.lock().await.push(&chunk); - if let Some(hook) = on_delta { - hook(ExecOutputDelta { - session_id, - stream, - chunk, - }); - } -} - -async fn flush_decoder( - decoder: &mut Utf8ChunkDecoder, - buffer: &Arc>, - session_id: i32, - stream: ExecStream, - on_delta: &Option>, -) { - let tail = decoder.finish(); - if tail.is_empty() { - return; - } - buffer.lock().await.push(&tail); - if let Some(hook) = on_delta { - hook(ExecOutputDelta { - session_id, - stream, - chunk: tail, - }); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::approval::{ApprovalCache, ApprovalPolicy, new_exec_policy}; - use crate::context::{LocalToolSession, ToolCallContext, ToolSession}; - use std::sync::Arc; - - use crate::discovery::new_tool_catalog; - - fn test_ctx(session: Arc, exec: Arc) -> ToolCallContext { - ToolCallContext::new( - ".", - "off", - session, - exec, - new_exec_policy(), - Arc::new(ApprovalCache::default()), - new_tool_catalog(), - ) - } - - #[tokio::test] - async fn exec_command_tty_uses_pty() { - let mgr = UnifiedExecManager::new(); - let exec = Arc::new(mgr); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = test_ctx(session, exec.clone()); - let out = exec - .exec_command( - &ctx, - &serde_json::json!({ - "cmd": "echo pty_ok", - "yield_time_ms": 500, - "tty": true - }), - ) - .await - .unwrap(); - assert!(!out.is_error); - let structured = out.structured.unwrap(); - let output = structured - .get("output") - .and_then(|v| v.as_str()) - .unwrap_or(""); - assert!(output.contains("pty_ok") || structured.get("session_id").is_some()); - } - - async fn assert_turn_cancel_stops_process_tree(tty: bool) { - let dir = tempfile::tempdir().unwrap(); - let marker = dir.path().join("should-not-exist"); - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let turn = Arc::new(crate::turn::TurnExecutionContext::new( - crate::SessionId::new(), - crate::TurnId::new(), - )); - let ctx = ToolCallContext::new( - dir.path(), - "off", - session, - exec.clone(), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - new_tool_catalog(), - ) - .with_turn(turn.clone()); - let args = serde_json::json!({ - "cmd": "(sleep 0.3; touch should-not-exist) & wait", - "yield_time_ms": 5_000, - "tty": tty - }); - - let cancel = async { - tokio::time::sleep(std::time::Duration::from_millis(50)).await; - turn.cancel(); - }; - let (result, ()) = tokio::join!(exec.exec_command(&ctx, &args), cancel); - assert!(result.unwrap().is_error); - assert!( - turn.resources() - .wait_for_idle(std::time::Duration::from_secs(3)) - .await - ); - assert!(exec.list_sessions().await.is_empty()); - tokio::time::sleep(std::time::Duration::from_millis(400)).await; - assert!(!marker.exists(), "cancelled process tree produced a file"); - } - - #[tokio::test] - async fn cancellation_stops_pipe_session_process_tree() { - assert_turn_cancel_stops_process_tree(false).await; - } - - #[tokio::test] - async fn cancellation_stops_pty_session_process_tree() { - assert_turn_cancel_stops_process_tree(true).await; - } - - #[tokio::test] - async fn write_stdin_unknown_session_returns_clear_error_not_panic() { - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = test_ctx(session, exec.clone()); - // Runtime dispatch converts this Err into `ToolResult::err(..)` for the model; - // exercise the same conversion here to assert no panic and a clear message. - let err = exec - .write_stdin(&ctx, &serde_json::json!({"session_id": 999, "chars": "hi"})) - .await - .unwrap_err(); - assert!(err.to_string().contains("999")); - } - - #[tokio::test] - async fn write_stdin_rejects_invalid_session_id_type() { - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = test_ctx(session, exec.clone()); - let err = exec - .write_stdin( - &ctx, - &serde_json::json!({"session_id": "not-a-number", "chars": "hi"}), - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("invalid session_id")); - } - - #[tokio::test] - async fn write_stdin_rejects_oversized_input() { - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = test_ctx(session, exec.clone()); - let huge = "a".repeat(MAX_STDIN_BYTES + 1); - let out = exec - .write_stdin(&ctx, &serde_json::json!({"session_id": 1, "chars": huge})) - .await - .unwrap(); - assert!(out.is_error); - assert!(out.content.contains("too large")); - } - - #[tokio::test] - async fn write_stdin_rejects_utf8_oversized_by_bytes_not_chars() { - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = test_ctx(session, exec.clone()); - let huge = "\u{00e9}".repeat(MAX_STDIN_BYTES / 2 + 1); - assert!(huge.len() > MAX_STDIN_BYTES); - let out = exec - .write_stdin(&ctx, &serde_json::json!({"session_id": 1, "chars": huge})) - .await - .unwrap(); - assert!(out.is_error); - assert!(out.content.contains("too large")); - } - - #[tokio::test] - async fn write_stdin_accepts_empty_input_for_live_session() { - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = test_ctx(session, exec.clone()); - let started = exec - .exec_command( - &ctx, - &serde_json::json!({"cmd": "cat", "yield_time_ms": 300, "tty": true}), - ) - .await - .unwrap(); - let session_id = started - .structured - .as_ref() - .and_then(|v| v.get("session_id")) - .and_then(|v| v.as_i64()) - .expect("running session should report session_id"); - - let out = exec - .write_stdin( - &ctx, - &serde_json::json!({"session_id": session_id, "chars": "", "yield_time_ms": 300}), - ) - .await - .unwrap(); - assert!(!out.is_error); - - let _ = exec - .write_stdin( - &ctx, - &serde_json::json!({"session_id": session_id, "chars": "\x03"}), - ) - .await; - } - - #[tokio::test] - async fn write_stdin_concurrent_writes_do_not_panic() { - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = test_ctx(session, exec.clone()); - let started = exec - .exec_command( - &ctx, - &serde_json::json!({"cmd": "cat", "yield_time_ms": 300, "tty": true}), - ) - .await - .unwrap(); - let session_id = started - .structured - .as_ref() - .and_then(|v| v.get("session_id")) - .and_then(|v| v.as_i64()) - .expect("running session should report session_id"); - - let mut handles = Vec::new(); - for i in 0..8 { - let exec = exec.clone(); - let ctx = test_ctx( - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)), - exec.clone(), - ); - handles.push(tokio::spawn(async move { - exec.write_stdin( - &ctx, - &serde_json::json!({"session_id": session_id, "chars": format!("{i}\n")}), - ) - .await - })); - } - for h in handles { - let _ = h.await.unwrap(); - } - - let _ = exec - .write_stdin( - &ctx, - &serde_json::json!({"session_id": session_id, "chars": "\x03"}), - ) - .await; - } - - #[tokio::test] - async fn streaming_hook_receives_deltas() { - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let exec = Arc::new(UnifiedExecManager::new()); - let ctx = test_ctx(session.clone(), exec.clone()); - let _ = exec - .exec_command( - &ctx, - &serde_json::json!({ - "cmd": "echo stream_test", - "yield_time_ms": 500, - "tty": true - }), - ) - .await - .unwrap(); - assert!(!session.exec_deltas().is_empty()); - } - - #[tokio::test] - async fn drop_manager_kills_running_pty_session() { - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = test_ctx(session, exec.clone()); - let out = exec - .exec_command( - &ctx, - &serde_json::json!({ - "cmd": "sleep 30", - "yield_time_ms": 100, - "tty": true - }), - ) - .await - .unwrap(); - assert!( - out.structured - .as_ref() - .and_then(|v| v.get("session_id")) - .is_some() - ); - assert!(!exec.list_sessions().await.is_empty()); - - drop(exec); - tokio::time::sleep(std::time::Duration::from_millis(200)).await; - } - - #[tokio::test] - async fn exec_command_tty_applies_restricted_sandbox() { - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = ToolCallContext::new( - ".", - "restricted", - session, - exec.clone(), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - new_tool_catalog(), - ); - let out = exec - .exec_command( - &ctx, - &serde_json::json!({ - "cmd": "echo $PATH", - "yield_time_ms": 500, - "tty": true - }), - ) - .await - .unwrap(); - let structured = out.structured.unwrap(); - let output = structured - .get("output") - .and_then(|v| v.as_str()) - .unwrap_or(""); - assert!( - output.contains("/usr/bin:/bin:/usr/local/bin"), - "pty path must route through restricted env wrapper, got: {output:?}" - ); - } - - #[tokio::test] - async fn exec_command_pipe_mode_applies_restricted_sandbox() { - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = ToolCallContext::new( - ".", - "restricted", - session, - exec.clone(), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - new_tool_catalog(), - ); - let out = exec - .exec_command( - &ctx, - &serde_json::json!({ - "cmd": "echo $PATH", - "yield_time_ms": 500, - "tty": false - }), - ) - .await - .unwrap(); - let structured = out.structured.unwrap(); - let output = structured - .get("output") - .and_then(|v| v.as_str()) - .unwrap_or(""); - assert!( - output.contains("/usr/bin:/bin:/usr/local/bin"), - "pipe path must route through restricted env wrapper, got: {output:?}" - ); - } - - #[tokio::test] - async fn exec_command_rejects_workdir_escape() { - let dir = tempfile::tempdir().unwrap(); - let exec = Arc::new(UnifiedExecManager::new()); - let session = - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)); - let ctx = ToolCallContext::new( - dir.path(), - "off", - session, - exec.clone(), - new_exec_policy(), - Arc::new(ApprovalCache::default()), - new_tool_catalog(), - ); - let err = exec - .exec_command( - &ctx, - &serde_json::json!({ - "cmd": "echo hi", - "workdir": "../escape", - "yield_time_ms": 300, - "tty": false - }), - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("outside working directory")); - } -} diff --git a/crates/pulsing-forge/tests/apply_patch_scenarios.rs b/crates/pulsing-forge/tests/apply_patch_scenarios.rs deleted file mode 100644 index c22130d94..000000000 --- a/crates/pulsing-forge/tests/apply_patch_scenarios.rs +++ /dev/null @@ -1,137 +0,0 @@ -//! End-to-end apply_patch scenarios (portable fixture layout from codex-apply-patch). -//! -//! Each scenario under `vendor/codex-rs/apply-patch/tests/fixtures/scenarios/` has: -//! `input/`, `patch.txt`, `expected/` — see that directory's README. - -use pulsing_forge::patch::apply_patch_to_fs; -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; - -/// Scenarios not yet matching codex-apply-patch reference (tracked gaps). -const KNOWN_GAP_SCENARIOS: &[&str] = &[ - "011_add_overwrites_existing_file", - "015_failure_after_partial_success_leaves_changes", -]; - -#[derive(Debug, Clone, PartialEq, Eq)] -enum Entry { - File(Vec), - Dir, -} - -#[test] -fn codex_apply_patch_scenarios() { - let scenarios_dir = scenarios_root(); - if !scenarios_dir.is_dir() { - eprintln!( - "skip codex_apply_patch_scenarios: missing {}", - scenarios_dir.display() - ); - return; - } - let mut passed = 0usize; - let mut unexpected_failures: Vec = Vec::new(); - for entry in fs::read_dir(&scenarios_dir).expect("read scenarios dir") { - let entry = entry.expect("scenario entry"); - let path = entry.path(); - if !path.is_dir() { - continue; - } - let name = path - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or("") - .to_string(); - let ok = run_apply_patch_scenario(&path).is_ok(); - if ok { - passed += 1; - } else if !KNOWN_GAP_SCENARIOS.contains(&name.as_str()) { - unexpected_failures.push(name); - } - } - assert!( - passed >= 10, - "expected many passing scenarios, got {passed}" - ); - assert!( - unexpected_failures.is_empty(), - "unexpected apply_patch scenario failures: {unexpected_failures:?}" - ); -} - -fn scenarios_root() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../vendor/codex-rs/apply-patch/tests/fixtures/scenarios") -} - -fn run_apply_patch_scenario(dir: &Path) -> Result<(), Box> { - let tmp = tempfile::tempdir()?; - let input_dir = dir.join("input"); - if input_dir.is_dir() { - copy_dir_recursive(&input_dir, tmp.path())?; - } - let patch = fs::read_to_string(dir.join("patch.txt"))?; - let _ = apply_patch_to_fs(&patch, tmp.path()); - let expected_dir = dir.join("expected"); - let expected = snapshot_dir(&expected_dir)?; - let actual = snapshot_dir(tmp.path())?; - if actual != expected { - return Err(format!( - "filesystem mismatch for {}", - dir.file_name().unwrap_or_default().to_string_lossy() - ) - .into()); - } - Ok(()) -} - -fn snapshot_dir(root: &Path) -> Result, Box> { - let mut entries = BTreeMap::new(); - if root.is_dir() { - snapshot_dir_recursive(root, root, &mut entries)?; - } - Ok(entries) -} - -fn snapshot_dir_recursive( - base: &Path, - dir: &Path, - entries: &mut BTreeMap, -) -> Result<(), Box> { - for entry in fs::read_dir(dir)? { - let entry = entry?; - let path = entry.path(); - if path.file_name().is_some_and(|n| n == ".gitattributes") { - continue; - } - let rel = path.strip_prefix(base)?.to_path_buf(); - let metadata = fs::metadata(&path)?; - if metadata.is_dir() { - entries.insert(rel.clone(), Entry::Dir); - snapshot_dir_recursive(base, &path, entries)?; - } else if metadata.is_file() { - entries.insert(rel, Entry::File(fs::read(&path)?)); - } - } - Ok(()) -} - -fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), Box> { - for entry in fs::read_dir(src)? { - let entry = entry?; - let path = entry.path(); - let dest_path = dst.join(entry.file_name()); - let metadata = fs::metadata(&path)?; - if metadata.is_dir() { - fs::create_dir_all(&dest_path)?; - copy_dir_recursive(&path, &dest_path)?; - } else if metadata.is_file() { - if let Some(parent) = dest_path.parent() { - fs::create_dir_all(parent)?; - } - fs::copy(&path, &dest_path)?; - } - } - Ok(()) -} diff --git a/crates/pulsing-gui/Cargo.toml b/crates/pulsing-gui/Cargo.toml deleted file mode 100644 index 5857438d7..000000000 --- a/crates/pulsing-gui/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "pulsing-gui" -version.workspace = true -edition = "2021" -authors.workspace = true -license.workspace = true -description = "Pulsing desktop chat GUI (egui)" -repository.workspace = true - -[dependencies] -anyhow = { workspace = true } -eframe = { version = "0.31", default-features = false, features = [ - "default_fonts", - "glow", - "x11", -] } -egui = "0.31" -pulsing-forge = { path = "../pulsing-forge" } -pulsing-workspace = { path = "../pulsing-workspace" } -tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } - -[lints.clippy] -too_many_arguments = "allow" diff --git a/crates/pulsing-gui/src/app/chat.rs b/crates/pulsing-gui/src/app/chat.rs deleted file mode 100644 index 06da115ab..000000000 --- a/crates/pulsing-gui/src/app/chat.rs +++ /dev/null @@ -1,192 +0,0 @@ -use eframe::egui; - -use super::WorkspaceApp; -use crate::settings::{provider_available, ChatMode, MODEL_PRESETS}; -use crate::state::{ChatMessage, MessageKind}; - -pub fn render(app: &mut WorkspaceApp, ui: &mut egui::Ui) { - let chat = app.sessions().active_chat().clone(); - let busy = chat.busy; - - ui.with_layout(egui::Layout::bottom_up(egui::Align::LEFT), |ui| { - render_composer(app, ui, busy); - ui.separator(); - - egui::ScrollArea::vertical() - .auto_shrink([false, false]) - .stick_to_bottom(true) - .max_height(ui.available_height()) - .show(ui, |ui| { - if chat.messages.is_empty() && !busy { - render_empty_state(app, ui); - } else { - for msg in &chat.messages { - render_message(ui, msg); - } - } - }); - }); -} - -fn render_message(ui: &mut egui::Ui, msg: &ChatMessage) { - match &msg.kind { - MessageKind::User(text) => { - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| { - ui.label(egui::RichText::new("You").weak()); - egui::Frame::group(ui.style()) - .fill(ui.visuals().widgets.active.bg_fill) - .show(ui, |ui| { - ui.label(text); - }); - }); - }); - ui.add_space(8.0); - } - MessageKind::Assistant { body, streaming } => { - if body.is_empty() && !streaming { - return; - } - let display = if *streaming && body.is_empty() { - "▍".to_string() - } else if *streaming { - format!("{body}▍") - } else { - body.clone() - }; - ui.horizontal(|ui| { - ui.label(egui::RichText::new("Agent").weak()); - egui::Frame::group(ui.style()).show(ui, |ui| { - ui.label(display); - }); - }); - ui.add_space(8.0); - } - MessageKind::Tool { - name, - running, - ok, - detail, - } => { - let symbol = if *running { - "…" - } else if *ok { - "✓" - } else { - "✗" - }; - let summary = if detail.is_empty() { - name.clone() - } else { - format!("{name} — {detail}") - }; - ui.label( - egui::RichText::new(format!("{symbol} {summary}")) - .small() - .weak(), - ); - ui.add_space(4.0); - } - MessageKind::Error(text) => { - ui.colored_label(egui::Color32::RED, format!("Error: {text}")); - ui.add_space(8.0); - } - } -} - -fn render_empty_state(app: &mut WorkspaceApp, ui: &mut egui::Ui) { - ui.vertical_centered(|ui| { - ui.add_space(48.0); - ui.heading("What are we building?"); - ui.label("Ask about your project, edit files, or run agent workflows."); - ui.add_space(16.0); - for suggestion in [ - "Explain this codebase", - "Find bugs in recent changes", - "Add a new feature", - ] { - if ui.button(suggestion).clicked() { - *app.input_text_mut() = suggestion.to_string(); - } - } - }); -} - -fn render_composer(app: &mut WorkspaceApp, ui: &mut egui::Ui, busy: bool) { - let can_send = !busy && !app.input_text().trim().is_empty(); - - ui.horizontal(|ui| { - egui::ComboBox::from_label("Mode") - .selected_text(app.chat_mode().label()) - .show_ui(ui, |ui| { - for mode in ChatMode::ALL { - if ui - .selectable_label(app.chat_mode() == mode, mode.label()) - .clicked() - { - app.pick_mode(mode); - } - } - }); - - let model_label = short_model_label(&app.agent().model); - egui::ComboBox::from_label("Model") - .selected_text(&model_label) - .show_ui(ui, |ui| { - let mut last_section = ""; - for preset in MODEL_PRESETS { - if preset.section != last_section { - ui.separator(); - ui.label(egui::RichText::new(preset.section).weak()); - last_section = preset.section; - } - let available = provider_available(preset.provider); - let checked = app.agent().provider == preset.provider - && app.agent().model == preset.model; - if ui - .add_enabled(available, egui::SelectableLabel::new(checked, preset.label)) - .clicked() - { - app.pick_model(preset.provider, preset.model); - } - } - }); - - if busy { - if ui.button("Stop").clicked() { - app.stop_agent(); - } - } else if ui - .add_enabled(can_send, egui::Button::new("Send")) - .clicked() - { - app.send_message(); - } - }); - - ui.label(egui::RichText::new(app.chat_mode().hint()).small().weak()); - - let response = ui.add( - egui::TextEdit::multiline(app.input_text_mut()) - .desired_rows(3) - .hint_text("Ask anything about your project…"), - ); - if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift) - { - app.send_message(); - } - - ui.label( - egui::RichText::new("Enter to send · Shift+Enter for newline") - .small() - .weak(), - ); -} - -fn short_model_label(model: &str) -> String { - let m = model.trim(); - if m.len() <= 22 { - return m.to_string(); - } - format!("{}…", m.chars().take(21).collect::()) -} diff --git a/crates/pulsing-gui/src/app/left.rs b/crates/pulsing-gui/src/app/left.rs deleted file mode 100644 index 37a1a81c3..000000000 --- a/crates/pulsing-gui/src/app/left.rs +++ /dev/null @@ -1,146 +0,0 @@ -use eframe::egui; - -use super::{LeftTab, WorkspaceApp}; -use crate::model::{FileTreeNode, WorkspaceAction}; - -pub fn render(app: &mut WorkspaceApp, ui: &mut egui::Ui) { - ui.horizontal(|ui| { - for (tab, label) in [ - (LeftTab::Explorer, "Files"), - (LeftTab::Revisions, "History"), - (LeftTab::Workflows, "Workflows"), - ] { - if ui.selectable_label(app.left_tab() == tab, label).clicked() { - app.set_left_tab(tab); - } - } - }); - ui.separator(); - - match app.left_tab() { - LeftTab::Explorer => render_explorer(app, ui), - LeftTab::Revisions => render_revisions(app, ui), - LeftTab::Workflows => render_workflows(app, ui), - } -} - -fn render_explorer(app: &mut WorkspaceApp, ui: &mut egui::Ui) { - ui.horizontal(|ui| { - if ui.button("Open").clicked() { - if let Some(rel) = app.workspace().selected_file.clone() { - app.dispatch_action(WorkspaceAction::OpenFile(rel)); - } - } - if ui.button("Refresh").clicked() { - app.dispatch_action(WorkspaceAction::RefreshExplorer); - } - }); - if let Some(rel) = &app.workspace().selected_file { - ui.label( - egui::RichText::new(rel.display().to_string()) - .small() - .weak(), - ); - } - ui.separator(); - - egui::ScrollArea::vertical().show(ui, |ui| { - let tree = app.file_tree().to_vec(); - for node in &tree { - render_tree_node(app, ui, node, 0); - } - }); -} - -fn render_tree_node(app: &mut WorkspaceApp, ui: &mut egui::Ui, node: &FileTreeNode, depth: usize) { - let indent = depth as f32 * 14.0; - ui.horizontal(|ui| { - ui.add_space(indent); - if node.is_dir { - let icon = if node.expanded { "📂" } else { "📁" }; - if ui - .selectable_label(false, format!("{icon} {}", node.label)) - .clicked() - { - app.on_tree_click(&node.id, true); - } - } else if ui - .selectable_label(false, format!("📄 {}", node.label)) - .clicked() - { - app.on_tree_click(&node.id, false); - } - }); - if node.is_dir && node.expanded { - for child in &node.children { - render_tree_node(app, ui, child, depth + 1); - } - } -} - -fn render_revisions(app: &mut WorkspaceApp, ui: &mut egui::Ui) { - if ui.button("Refresh").clicked() { - app.dispatch_action(WorkspaceAction::RefreshRevisions); - } - ui.separator(); - - let snapshot = app.workspace().revisions.clone(); - if snapshot.revisions.is_empty() { - ui.label("No checkpoints yet"); - ui.label( - egui::RichText::new("Use `pulsing checkpoint` or the agent /checkpoint command.") - .small() - .weak(), - ); - return; - } - - egui::ScrollArea::vertical().show(ui, |ui| { - for rev in &snapshot.revisions { - let is_head = snapshot.head.as_deref() == Some(rev.id.as_str()); - ui.group(|ui| { - ui.horizontal(|ui| { - if is_head { - ui.colored_label(egui::Color32::LIGHT_GREEN, "HEAD"); - } - ui.strong(&rev.id); - ui.label(format!("{} files", rev.file_count)); - }); - ui.label(egui::RichText::new(&rev.message).small().weak()); - }); - } - }); -} - -fn render_workflows(app: &mut WorkspaceApp, ui: &mut egui::Ui) { - if ui.button("Refresh").clicked() { - app.dispatch_action(WorkspaceAction::RefreshWorkflows); - } - ui.separator(); - - let scripts = app.workspace().workflow_scripts.clone(); - if scripts.is_empty() { - ui.label("No workflow scripts"); - ui.label( - egui::RichText::new( - "Add `.py` files under `.pulsing/workflows/` (run `pulsing init`).", - ) - .small() - .weak(), - ); - return; - } - - egui::ScrollArea::vertical().show(ui, |ui| { - for path in &scripts { - let name = path - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_else(|| path.display().to_string()); - ui.group(|ui| { - ui.strong(name); - ui.label(egui::RichText::new("Python workflow").small().weak()); - }); - } - }); -} diff --git a/crates/pulsing-gui/src/app/mod.rs b/crates/pulsing-gui/src/app/mod.rs deleted file mode 100644 index b4adc9ee9..000000000 --- a/crates/pulsing-gui/src/app/mod.rs +++ /dev/null @@ -1,566 +0,0 @@ -mod chat; -mod left; -mod right; - -use std::path::{Path, PathBuf}; -use std::time::{Duration, Instant}; - -use eframe::egui; -use pulsing_forge::InteractiveConfig; - -use crate::controller::ForgeController; -use crate::model::{ - build_file_tree, count_files, FileTreeNode, SessionId, SessionStore, WorkspaceAction, - WorkspaceModel, -}; -use crate::settings::{build_agent_config, ChatMode}; -use crate::state::{ChatMessage, MessageKind}; - -const MAX_PREVIEW_BYTES: usize = 512 * 1024; - -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum LeftTab { - Explorer, - Revisions, - Workflows, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum CenterTab { - Chat, - File(usize), -} - -struct OpenFile { - rel: PathBuf, - content: String, - error: Option, -} - -pub struct WorkspaceApp { - agent: InteractiveConfig, - workspace: WorkspaceModel, - sessions: SessionStore, - chat_mode: ChatMode, - - left_tab: LeftTab, - center_tab: CenterTab, - file_tree: Vec, - open_files: Vec, - last_file_click: Option<(String, Instant)>, - - input_text: String, - forge: ForgeController, - toast: Option<(String, Instant)>, -} - -impl WorkspaceApp { - fn new(agent: InteractiveConfig) -> Self { - let workspace = WorkspaceModel::new(agent.cwd.clone()); - let sessions = - SessionStore::new(agent.provider.clone(), agent.model.clone(), ChatMode::Agent); - let mut app = Self { - agent, - workspace, - sessions, - chat_mode: ChatMode::Agent, - left_tab: LeftTab::Explorer, - center_tab: CenterTab::Chat, - file_tree: Vec::new(), - open_files: Vec::new(), - last_file_click: None, - input_text: String::new(), - forge: ForgeController::start(), - toast: None, - }; - app.rebuild_tree(); - app - } - - fn rebuild_tree(&mut self) { - self.file_tree = build_file_tree(&self.workspace.layout, &self.file_tree); - self.workspace.runtime.file_count = count_files(&self.file_tree); - } - - fn dispatch(&mut self, action: WorkspaceAction) { - match action { - WorkspaceAction::OpenFile(rel) => self.open_file(rel), - WorkspaceAction::CloseFile(rel) => self.close_file(&rel), - WorkspaceAction::RefreshExplorer => self.rebuild_tree(), - WorkspaceAction::NewSession => self.new_session(), - WorkspaceAction::FocusSession(id) => { - self.sessions.focus(id); - let (provider, model, mode) = self.sessions.active_settings(); - self.agent.provider = provider.to_string(); - self.agent.model = model.to_string(); - self.chat_mode = mode; - self.center_tab = CenterTab::Chat; - self.toast = Some(( - format!("Session: {}", self.sessions.session_title(id)), - Instant::now(), - )); - } - WorkspaceAction::RefreshRevisions => { - self.workspace.refresh_revisions(); - self.toast = Some(("Revisions refreshed".into(), Instant::now())); - } - WorkspaceAction::RefreshWorkflows => { - self.workspace.refresh_workflows(); - self.toast = Some(("Workflows refreshed".into(), Instant::now())); - } - } - self.sync_runtime(); - } - - fn new_session(&mut self) { - self.sessions.new_session( - self.agent.provider.clone(), - self.agent.model.clone(), - self.chat_mode, - ); - self.center_tab = CenterTab::Chat; - self.toast = Some(("New chat started".into(), Instant::now())); - self.sync_runtime(); - } - - fn open_file(&mut self, rel: PathBuf) { - if let Some(ix) = self.open_files.iter().position(|f| f.rel == rel) { - self.center_tab = CenterTab::File(ix); - return; - } - let abs = self.workspace.layout.root.join(&rel); - let (content, error) = load_preview(&rel, &abs); - let preview_err = error.clone(); - self.open_files.push(OpenFile { - rel: rel.clone(), - content, - error, - }); - self.center_tab = CenterTab::File(self.open_files.len() - 1); - if preview_err.is_none() { - self.toast = Some((format!("Opened {}", rel.display()), Instant::now())); - } - } - - fn close_file(&mut self, rel: &PathBuf) { - if let Some(ix) = self.open_files.iter().position(|f| &f.rel == rel) { - self.open_files.remove(ix); - self.center_tab = match self.center_tab { - CenterTab::File(i) if i == ix => CenterTab::Chat, - CenterTab::File(i) if i > ix => CenterTab::File(i - 1), - other => other, - }; - } - } - - fn sync_runtime(&mut self) { - let chat = self.sessions.active_chat(); - self.workspace.set_busy(chat.busy); - self.workspace.set_session_title(chat.session_title()); - } - - fn poll_agent_events(&mut self) { - let mut changed = false; - while let Some(event) = self.forge.try_recv() { - let session_id = SessionId(event.gui_session_id); - if let Some(chat) = self.sessions.chat_mut(session_id) { - chat.apply(event.event); - changed = true; - } else if event.gui_session_id == 0 { - self.toast = Some(("Forge controller failed".into(), Instant::now())); - } - } - if changed { - self.sync_runtime(); - } - } - - fn try_send(&mut self) { - let text = self.input_text.trim().to_string(); - if text.is_empty() || self.sessions.active_chat().busy { - return; - } - self.input_text.clear(); - - let chat = self.sessions.active_chat_mut(); - chat.messages.push(ChatMessage { - kind: MessageKind::User(text.clone()), - }); - chat.messages.push(ChatMessage { - kind: MessageKind::Assistant { - body: String::new(), - streaming: true, - }, - }); - chat.busy = true; - self.sync_runtime(); - - let session_id = self.sessions.active_id(); - self.forge.start_turn( - session_id.0, - build_agent_config( - &self.agent.cwd, - &self.agent.provider, - &self.agent.model, - self.chat_mode, - ), - text, - ); - } - - fn stop_generation(&mut self) { - if !self.sessions.active_chat().busy { - return; - } - let session_id = self.sessions.active_id(); - self.forge.cancel_turn(session_id.0); - self.toast = Some(("Cancellation requested".into(), Instant::now())); - } - - fn set_model(&mut self, provider: &str, model: &str) { - if self.sessions.active_chat().busy { - return; - } - if !self.sessions.active_chat().messages.is_empty() { - self.agent.provider = provider.into(); - self.agent.model = model.into(); - self.sessions.new_session( - self.agent.provider.clone(), - self.agent.model.clone(), - self.chat_mode, - ); - self.toast = Some(("Model change started a new chat".into(), Instant::now())); - self.sync_runtime(); - return; - } - self.agent.provider = provider.into(); - self.agent.model = model.into(); - self.sessions.set_active_settings( - self.agent.provider.clone(), - self.agent.model.clone(), - self.chat_mode, - ); - } - - fn set_chat_mode(&mut self, mode: ChatMode) { - if self.sessions.active_chat().busy { - return; - } - if !self.sessions.active_chat().messages.is_empty() { - self.chat_mode = mode; - self.sessions.new_session( - self.agent.provider.clone(), - self.agent.model.clone(), - self.chat_mode, - ); - self.toast = Some(("Mode change started a new chat".into(), Instant::now())); - self.sync_runtime(); - return; - } - self.chat_mode = mode; - self.sessions.set_active_settings( - self.agent.provider.clone(), - self.agent.model.clone(), - self.chat_mode, - ); - } - - fn on_file_click(&mut self, id: &str, is_dir: bool) { - if is_dir { - toggle_dir(&mut self.file_tree, id); - self.rebuild_tree(); - return; - } - let now = Instant::now(); - let double = self.last_file_click.as_ref().is_some_and(|(last, t)| { - last == id && now.duration_since(*t) < Duration::from_millis(400) - }); - self.last_file_click = Some((id.to_string(), now)); - self.workspace.set_selected_file(Some(PathBuf::from(id))); - if double { - self.dispatch(WorkspaceAction::OpenFile(PathBuf::from(id))); - } - } -} - -pub fn run(agent: InteractiveConfig) -> anyhow::Result<()> { - let options = eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - .with_inner_size([1280.0, 800.0]) - .with_title("Pulsing"), - ..Default::default() - }; - eframe::run_native( - "Pulsing", - options, - Box::new(move |_cc| Ok(Box::new(WorkspaceApp::new(agent)))), - ) - .map_err(|e| anyhow::anyhow!("{e}")) -} - -impl eframe::App for WorkspaceApp { - fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - self.poll_agent_events(); - if self.sessions.any_busy() { - ctx.request_repaint_after(Duration::from_millis(50)); - } - - if let Some((msg, t0)) = &self.toast { - if t0.elapsed() > Duration::from_secs(3) { - self.toast = None; - } else { - egui::TopBottomPanel::top("toast").show(ctx, |ui| { - ui.horizontal(|ui| { - ui.label(msg); - }); - }); - } - } - - let workspace_name = self - .workspace - .layout - .root - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_else(|| self.workspace.layout.root.display().to_string()); - let busy = self.workspace.runtime.local_busy; - let session_title = self.workspace.runtime.session_title.clone(); - - egui::TopBottomPanel::top("titlebar").show(ctx, |ui| { - ui.horizontal(|ui| { - ui.heading("Pulsing"); - ui.separator(); - ui.label(&workspace_name); - ui.separator(); - let status = if busy { - "● Agent running" - } else { - "● Ready" - }; - ui.colored_label( - if busy { - egui::Color32::LIGHT_GREEN - } else { - egui::Color32::GRAY - }, - status, - ); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(&session_title); - }); - }); - }); - - egui::TopBottomPanel::bottom("runtime").show(ctx, |ui| { - let r = &self.workspace.runtime; - ui.horizontal(|ui| { - ui.label(if busy { "Running" } else { "Ready" }); - ui.separator(); - ui.label(format!("files {}", r.file_count)); - ui.label(format!("revs {}", r.revision_count)); - ui.label(format!("workflows {}", r.workflow_count)); - ui.label("cluster · phase 3"); - }); - }); - - egui::SidePanel::left("left") - .resizable(true) - .default_width(240.0) - .show(ctx, |ui| { - left::render(self, ui); - }); - - egui::SidePanel::right("agents") - .resizable(true) - .default_width(220.0) - .show(ctx, |ui| { - right::render(self, ui); - }); - - egui::CentralPanel::default().show(ctx, |ui| { - self.render_center(ui); - }); - } -} - -impl WorkspaceApp { - fn render_center(&mut self, ui: &mut egui::Ui) { - ui.horizontal(|ui| { - if ui - .selectable_label(self.center_tab == CenterTab::Chat, "Chat") - .clicked() - { - self.center_tab = CenterTab::Chat; - } - let tabs: Vec<_> = self - .open_files - .iter() - .enumerate() - .map(|(ix, file)| { - let name = file - .rel - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_else(|| file.rel.display().to_string()); - (ix, name, file.rel.clone()) - }) - .collect(); - for (ix, name, rel) in tabs { - let tab = CenterTab::File(ix); - let selected = self.center_tab == tab; - ui.horizontal(|ui| { - if ui.selectable_label(selected, &name).clicked() { - self.center_tab = tab; - } - if ui.small_button("×").clicked() { - self.dispatch(WorkspaceAction::CloseFile(rel)); - } - }); - } - }); - ui.separator(); - - match self.center_tab { - CenterTab::Chat => chat::render(self, ui), - CenterTab::File(ix) => { - if let Some(file) = self.open_files.get(ix) { - if let Some(err) = &file.error { - ui.colored_label(egui::Color32::RED, format!("Preview failed: {err}")); - } else { - egui::ScrollArea::vertical().show(ui, |ui| { - ui.add(egui::Label::new(&file.content).wrap()); - }); - } - } - } - } - } -} - -fn toggle_dir(nodes: &mut [FileTreeNode], id: &str) -> bool { - for node in nodes { - if node.id == id && node.is_dir { - node.expanded = !node.expanded; - return true; - } - if toggle_dir(&mut node.children, id) { - return true; - } - } - false -} - -fn load_preview(rel_path: &Path, abs_path: &Path) -> (String, Option) { - let meta = match std::fs::metadata(abs_path) { - Ok(m) => m, - Err(err) => return (String::new(), Some(err.to_string())), - }; - if !meta.is_file() { - return (String::new(), Some("Not a file".into())); - } - if meta.len() as usize > MAX_PREVIEW_BYTES { - return ( - String::new(), - Some(format!( - "File too large to preview ({} KB max)", - MAX_PREVIEW_BYTES / 1024 - )), - ); - } - let bytes = match std::fs::read(abs_path) { - Ok(b) => b, - Err(err) => return (String::new(), Some(err.to_string())), - }; - if bytes.iter().take(8192).any(|b| *b == 0) { - return ( - String::new(), - Some("Binary file cannot be previewed".into()), - ); - } - let content = match String::from_utf8(bytes) { - Ok(s) => s, - Err(_) => return (String::new(), Some("Invalid UTF-8 text file".into())), - }; - let text = if is_markdown(rel_path) { - content - } else { - wrap_code_block(language_for_path(rel_path), &content) - }; - (text, None) -} - -fn is_markdown(path: &Path) -> bool { - matches!( - path.extension().and_then(|e| e.to_str()), - Some("md" | "markdown") - ) -} - -fn language_for_path(path: &Path) -> &'static str { - match path.extension().and_then(|e| e.to_str()) { - Some("rs") => "rust", - Some("py") => "python", - Some("toml") => "toml", - Some("json") => "json", - Some("yaml" | "yml") => "yaml", - Some("js") => "javascript", - Some("ts") => "typescript", - Some("sh" | "bash" | "zsh") => "bash", - _ => "text", - } -} - -fn wrap_code_block(lang: &str, code: &str) -> String { - let fence = if code.contains("```") { "````" } else { "```" }; - format!("{fence}{lang}\n{code}\n{fence}") -} - -// Re-export helpers for submodules -impl WorkspaceApp { - pub(crate) fn agent(&self) -> &InteractiveConfig { - &self.agent - } - pub(crate) fn workspace(&self) -> &WorkspaceModel { - &self.workspace - } - pub(crate) fn sessions(&self) -> &SessionStore { - &self.sessions - } - pub(crate) fn chat_mode(&self) -> ChatMode { - self.chat_mode - } - pub(crate) fn left_tab(&self) -> LeftTab { - self.left_tab - } - pub(crate) fn set_left_tab(&mut self, tab: LeftTab) { - self.left_tab = tab; - } - pub(crate) fn file_tree(&self) -> &[FileTreeNode] { - &self.file_tree - } - pub(crate) fn input_text(&self) -> &str { - &self.input_text - } - pub(crate) fn input_text_mut(&mut self) -> &mut String { - &mut self.input_text - } - pub(crate) fn dispatch_action(&mut self, action: WorkspaceAction) { - self.dispatch(action); - } - pub(crate) fn on_tree_click(&mut self, id: &str, is_dir: bool) { - self.on_file_click(id, is_dir); - } - pub(crate) fn send_message(&mut self) { - self.try_send(); - } - pub(crate) fn stop_agent(&mut self) { - self.stop_generation(); - } - pub(crate) fn pick_model(&mut self, provider: &str, model: &str) { - self.set_model(provider, model); - } - pub(crate) fn pick_mode(&mut self, mode: ChatMode) { - self.set_chat_mode(mode); - } -} diff --git a/crates/pulsing-gui/src/app/right.rs b/crates/pulsing-gui/src/app/right.rs deleted file mode 100644 index 73d0c3452..000000000 --- a/crates/pulsing-gui/src/app/right.rs +++ /dev/null @@ -1,49 +0,0 @@ -use eframe::egui; - -use super::WorkspaceApp; -use crate::model::WorkspaceAction; - -pub fn render(app: &mut WorkspaceApp, ui: &mut egui::Ui) { - let busy = app.workspace().runtime.local_busy; - let active = app.sessions().active_id(); - - ui.heading("Sessions"); - ui.horizontal(|ui| { - let status = if busy { "Running" } else { "Idle" }; - ui.colored_label( - if busy { - egui::Color32::LIGHT_GREEN - } else { - egui::Color32::GRAY - }, - status, - ); - }); - ui.separator(); - - let sessions: Vec<_> = app - .sessions() - .sessions() - .iter() - .map(|s| (s.id, s.chat.session_title())) - .collect(); - - for (id, title) in sessions { - let is_active = id == active; - if ui - .selectable_label(is_active, format!("🤖 {title}")) - .clicked() - { - app.dispatch_action(WorkspaceAction::FocusSession(id)); - } - } - - ui.add_space(8.0); - if ui.button("+ New chat").clicked() { - app.dispatch_action(WorkspaceAction::NewSession); - } - - ui.separator(); - ui.label(egui::RichText::new("Cluster").weak()); - ui.add_enabled(false, egui::Button::new("Remote agents (Soon)")); -} diff --git a/crates/pulsing-gui/src/controller/chat_turn.rs b/crates/pulsing-gui/src/controller/chat_turn.rs deleted file mode 100644 index 99524c424..000000000 --- a/crates/pulsing-gui/src/controller/chat_turn.rs +++ /dev/null @@ -1,288 +0,0 @@ -use std::collections::HashMap; -use std::sync::{mpsc, Arc}; -use std::thread; - -use pulsing_forge::protocol::{ForgeEventKind, SessionId, TurnId}; -use pulsing_forge::{AgentConfig, AgentEvent, LocalForgeClient}; -use tokio::sync::{mpsc as tokio_mpsc, Mutex}; - -enum ControllerCommand { - StartTurn { - gui_session_id: u64, - config: AgentConfig, - prompt: String, - }, - CancelTurn { - gui_session_id: u64, - }, -} - -#[derive(Debug)] -pub struct ControllerEvent { - pub gui_session_id: u64, - pub event: AgentEvent, -} - -#[derive(Clone)] -struct SessionBinding { - forge_session_id: SessionId, - active_turn: Option, -} - -pub struct ForgeController { - commands: tokio_mpsc::UnboundedSender, - events: mpsc::Receiver, -} - -impl ForgeController { - pub fn start() -> Self { - let (command_tx, command_rx) = tokio_mpsc::unbounded_channel(); - let (event_tx, event_rx) = mpsc::channel(); - thread::spawn(move || { - let runtime = match tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - { - Ok(runtime) => runtime, - Err(err) => { - let _ = event_tx.send(ControllerEvent { - gui_session_id: 0, - event: AgentEvent::Error(err.to_string()), - }); - return; - } - }; - runtime.block_on(run_controller(command_rx, event_tx)); - }); - Self { - commands: command_tx, - events: event_rx, - } - } - - pub fn start_turn(&self, gui_session_id: u64, config: AgentConfig, prompt: String) { - let _ = self.commands.send(ControllerCommand::StartTurn { - gui_session_id, - config, - prompt, - }); - } - - pub fn cancel_turn(&self, gui_session_id: u64) { - let _ = self - .commands - .send(ControllerCommand::CancelTurn { gui_session_id }); - } - - pub fn try_recv(&self) -> Option { - self.events.try_recv().ok() - } -} - -async fn run_controller( - mut commands: tokio_mpsc::UnboundedReceiver, - events: mpsc::Sender, -) { - let client = LocalForgeClient::default(); - let sessions: Arc>> = Arc::new(Mutex::new(HashMap::new())); - - while let Some(command) = commands.recv().await { - match command { - ControllerCommand::StartTurn { - gui_session_id, - config, - prompt, - } => match begin_turn(&client, &sessions, gui_session_id, config, prompt).await { - Ok((forge_session_id, turn_id, after_seq)) => { - tokio::spawn(forward_turn_events( - client.clone(), - sessions.clone(), - events.clone(), - gui_session_id, - forge_session_id, - turn_id, - after_seq, - )); - } - Err(err) => { - let _ = events.send(ControllerEvent { - gui_session_id, - event: AgentEvent::Error(err.to_string()), - }); - } - }, - ControllerCommand::CancelTurn { gui_session_id } => { - let binding = sessions.lock().await.get(&gui_session_id).cloned(); - let Some(SessionBinding { - forge_session_id, - active_turn: Some(turn_id), - }) = binding - else { - continue; - }; - if let Err(err) = client.cancel_turn(forge_session_id, turn_id).await { - let _ = events.send(ControllerEvent { - gui_session_id, - event: AgentEvent::Error(err.to_string()), - }); - } - } - } - } -} - -async fn begin_turn( - client: &LocalForgeClient, - sessions: &Arc>>, - gui_session_id: u64, - config: AgentConfig, - prompt: String, -) -> Result<(SessionId, TurnId, u64), pulsing_forge::protocol::ForgeProtocolError> { - let forge_session_id = { - let existing = sessions - .lock() - .await - .get(&gui_session_id) - .map(|binding| binding.forge_session_id.clone()); - match existing { - Some(id) => id, - None => { - let id = client.create_session(config).await?; - sessions.lock().await.insert( - gui_session_id, - SessionBinding { - forge_session_id: id.clone(), - active_turn: None, - }, - ); - id - } - } - }; - - let receipt = client.start_turn(forge_session_id.clone(), prompt).await?; - let turn_id = receipt - .turn_id - .clone() - .expect("start_turn receipt always has turn_id"); - if let Some(binding) = sessions.lock().await.get_mut(&gui_session_id) { - binding.active_turn = Some(turn_id.clone()); - } - Ok((forge_session_id, turn_id, receipt.accepted_seq)) -} - -async fn forward_turn_events( - client: LocalForgeClient, - sessions: Arc>>, - events: mpsc::Sender, - gui_session_id: u64, - forge_session_id: SessionId, - turn_id: TurnId, - after_seq: u64, -) { - let mut subscription = client - .subscribe(&forge_session_id, after_seq) - .await - .map_err(|err| err.to_string()); - let subscription = match subscription.as_mut() { - Ok(subscription) => subscription, - Err(message) => { - let _ = events.send(ControllerEvent { - gui_session_id, - event: AgentEvent::Error(message.clone()), - }); - clear_active_turn(&sessions, gui_session_id, &turn_id).await; - return; - } - }; - loop { - let event = match subscription.recv().await { - Ok(event) => event, - Err(err) => { - let _ = events.send(ControllerEvent { - gui_session_id, - event: AgentEvent::Error(err.to_string()), - }); - clear_active_turn(&sessions, gui_session_id, &turn_id).await; - return; - } - }; - if event.turn_id.as_ref() != Some(&turn_id) { - continue; - } - let (agent_event, terminal) = match event.kind { - ForgeEventKind::TurnOutputDelta { delta } => { - (Some(AgentEvent::TextDelta(delta)), false) - } - ForgeEventKind::ToolStarted { name } => (Some(AgentEvent::ToolStart { name }), false), - ForgeEventKind::ToolCompleted { name, ok, summary } => { - (Some(AgentEvent::ToolEnd { name, ok, summary }), false) - } - ForgeEventKind::ToolCancelled { name } => { - (Some(AgentEvent::ToolCancelled { name }), false) - } - ForgeEventKind::TurnCompleted { text } => (Some(AgentEvent::Done { text }), true), - ForgeEventKind::TurnFailed { message } => (Some(AgentEvent::Error(message)), true), - ForgeEventKind::TurnCancelled => (Some(AgentEvent::Cancelled), true), - _ => (None, false), - }; - if let Some(event) = agent_event { - let _ = events.send(ControllerEvent { - gui_session_id, - event, - }); - } - if terminal { - clear_active_turn(&sessions, gui_session_id, &turn_id).await; - return; - } - } -} - -async fn clear_active_turn( - sessions: &Arc>>, - gui_session_id: u64, - turn_id: &TurnId, -) { - if let Some(binding) = sessions.lock().await.get_mut(&gui_session_id) { - if binding.active_turn.as_ref() == Some(turn_id) { - binding.active_turn = None; - } - } -} - -#[cfg(test)] -mod tests { - use std::collections::HashSet; - use std::time::{Duration, Instant}; - - use super::*; - - fn demo_config() -> AgentConfig { - AgentConfig { - provider: "demo".into(), - model: "demo".into(), - ..AgentConfig::default() - } - } - - #[test] - fn routes_concurrent_session_events_to_their_origin() { - let controller = ForgeController::start(); - controller.start_turn(11, demo_config(), "remember eleven".into()); - controller.start_turn(22, demo_config(), "remember twenty two".into()); - - let deadline = Instant::now() + Duration::from_secs(3); - let mut completed = HashSet::new(); - while Instant::now() < deadline && completed.len() < 2 { - if let Some(event) = controller.try_recv() { - if matches!(event.event, AgentEvent::Done { .. }) { - completed.insert(event.gui_session_id); - } - } else { - thread::sleep(Duration::from_millis(10)); - } - } - assert_eq!(completed, HashSet::from([11, 22])); - } -} diff --git a/crates/pulsing-gui/src/controller/mod.rs b/crates/pulsing-gui/src/controller/mod.rs deleted file mode 100644 index e05039570..000000000 --- a/crates/pulsing-gui/src/controller/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod chat_turn; - -pub use chat_turn::ForgeController; diff --git a/crates/pulsing-gui/src/lib.rs b/crates/pulsing-gui/src/lib.rs deleted file mode 100644 index 144445d2e..000000000 --- a/crates/pulsing-gui/src/lib.rs +++ /dev/null @@ -1,11 +0,0 @@ -mod app; -mod controller; -mod model; -mod settings; -mod state; - -use pulsing_forge::InteractiveConfig; - -pub fn run(agent: InteractiveConfig) -> anyhow::Result<()> { - app::run(agent) -} diff --git a/crates/pulsing-gui/src/model/actions.rs b/crates/pulsing-gui/src/model/actions.rs deleted file mode 100644 index 15c615e14..000000000 --- a/crates/pulsing-gui/src/model/actions.rs +++ /dev/null @@ -1,15 +0,0 @@ -use std::path::PathBuf; - -use crate::model::sessions::SessionId; - -/// UI actions dispatched by `WorkspaceApp`. -#[derive(Clone, Debug)] -pub enum WorkspaceAction { - OpenFile(PathBuf), - CloseFile(PathBuf), - RefreshExplorer, - NewSession, - FocusSession(SessionId), - RefreshRevisions, - RefreshWorkflows, -} diff --git a/crates/pulsing-gui/src/model/files.rs b/crates/pulsing-gui/src/model/files.rs deleted file mode 100644 index c4fe2f696..000000000 --- a/crates/pulsing-gui/src/model/files.rs +++ /dev/null @@ -1,136 +0,0 @@ -use std::collections::HashSet; -use std::fs; -use std::path::Path; - -use pulsing_workspace::WorkspaceLayout; - -const DEFAULT_MAX_DEPTH: usize = 8; - -#[derive(Clone, Debug)] -pub struct FileTreeNode { - pub id: String, - pub label: String, - pub is_dir: bool, - pub expanded: bool, - pub children: Vec, -} - -impl FileTreeNode { - pub fn new_file(id: String, label: String) -> Self { - Self { - id, - label, - is_dir: false, - expanded: false, - children: Vec::new(), - } - } - - pub fn new_dir(id: String, label: String, expanded: bool, children: Vec) -> Self { - Self { - id, - label, - is_dir: true, - expanded, - children, - } - } -} - -pub fn build_file_tree(layout: &WorkspaceLayout, previous: &[FileTreeNode]) -> Vec { - let expanded = collect_expanded_ids(previous); - build_dir(layout, &layout.root, 0, DEFAULT_MAX_DEPTH, &expanded) -} - -pub fn count_files(items: &[FileTreeNode]) -> usize { - let mut n = 0; - walk(items, &mut |item| { - if !item.is_dir { - n += 1; - } - }); - n -} - -fn collect_expanded_ids(items: &[FileTreeNode]) -> HashSet { - let mut out = HashSet::new(); - walk(items, &mut |item| { - if item.is_dir && item.expanded { - out.insert(item.id.clone()); - } - }); - out -} - -fn walk(items: &[FileTreeNode], f: &mut dyn FnMut(&FileTreeNode)) { - for item in items { - f(item); - walk(&item.children, f); - } -} - -fn build_dir( - layout: &WorkspaceLayout, - dir: &Path, - depth: usize, - max_depth: usize, - expanded: &HashSet, -) -> Vec { - if depth > max_depth { - return Vec::new(); - } - - let entries = match fs::read_dir(dir) { - Ok(e) => e, - Err(_) => return Vec::new(), - }; - - let mut names: Vec<_> = entries.filter_map(|e| e.ok()).collect(); - names.sort_by_key(|e| e.file_name()); - - let mut dirs = Vec::new(); - let mut files = Vec::new(); - - for entry in names { - let path = entry.path(); - let Some(rel) = layout.rel_to_root(&path) else { - continue; - }; - if should_skip(&rel) { - continue; - } - - let id = rel.to_string_lossy().into_owned(); - let label = entry.file_name().to_string_lossy().into_owned(); - - if path.is_dir() { - let children = build_dir(layout, &path, depth + 1, max_depth, expanded); - let is_expanded = expanded.contains(&id); - dirs.push(FileTreeNode::new_dir( - id, - label, - is_expanded || depth == 0, - children, - )); - } else { - files.push(FileTreeNode::new_file(id, label)); - } - } - - dirs.extend(files); - dirs -} - -fn should_skip(rel: &Path) -> bool { - let s = rel.to_string_lossy(); - if s.starts_with(".git") || s.contains("/.git/") { - return true; - } - if s.starts_with("target") || s.contains("/target/") { - return true; - } - if s.starts_with("node_modules") || s.contains("/node_modules/") { - return true; - } - false -} diff --git a/crates/pulsing-gui/src/model/mod.rs b/crates/pulsing-gui/src/model/mod.rs deleted file mode 100644 index 752dc33fd..000000000 --- a/crates/pulsing-gui/src/model/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -mod actions; -mod files; -mod revisions; -mod sessions; -mod workflows; -mod workspace; - -pub use actions::WorkspaceAction; -pub use files::{build_file_tree, count_files, FileTreeNode}; -pub use sessions::{SessionId, SessionStore}; -pub use workspace::WorkspaceModel; diff --git a/crates/pulsing-gui/src/model/revisions.rs b/crates/pulsing-gui/src/model/revisions.rs deleted file mode 100644 index d498c8942..000000000 --- a/crates/pulsing-gui/src/model/revisions.rs +++ /dev/null @@ -1,13 +0,0 @@ -use pulsing_workspace::{list_revisions, RevisionInfo, WorkspaceLayout}; - -#[derive(Clone, Debug, Default)] -pub struct RevisionSnapshot { - pub head: Option, - pub revisions: Vec, -} - -pub fn load_revisions(layout: &WorkspaceLayout) -> RevisionSnapshot { - let revisions = list_revisions(layout).unwrap_or_default(); - let head = pulsing_workspace::current_head(layout).ok().flatten(); - RevisionSnapshot { head, revisions } -} diff --git a/crates/pulsing-gui/src/model/sessions.rs b/crates/pulsing-gui/src/model/sessions.rs deleted file mode 100644 index b15c7366c..000000000 --- a/crates/pulsing-gui/src/model/sessions.rs +++ /dev/null @@ -1,148 +0,0 @@ -use crate::settings::ChatMode; -use crate::state::ChatState; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct SessionId(pub u64); - -pub struct ChatSession { - pub id: SessionId, - pub chat: ChatState, - pub provider: String, - pub model: String, - pub mode: ChatMode, -} - -pub struct SessionStore { - sessions: Vec, - active: SessionId, - next_id: u64, -} - -impl SessionStore { - pub fn new(provider: String, model: String, mode: ChatMode) -> Self { - let id = SessionId(1); - Self { - sessions: vec![ChatSession { - id, - chat: ChatState::empty(), - provider, - model, - mode, - }], - active: id, - next_id: 2, - } - } - - pub fn sessions(&self) -> &[ChatSession] { - &self.sessions - } - - pub fn active_id(&self) -> SessionId { - self.active - } - - pub fn active_chat(&self) -> &ChatState { - self.sessions - .iter() - .find(|s| s.id == self.active) - .map(|s| &s.chat) - .expect("active session exists") - } - - pub fn active_chat_mut(&mut self) -> &mut ChatState { - let active = self.active; - self.sessions - .iter_mut() - .find(|s| s.id == active) - .map(|s| &mut s.chat) - .expect("active session exists") - } - - pub fn chat_mut(&mut self, id: SessionId) -> Option<&mut ChatState> { - self.sessions - .iter_mut() - .find(|session| session.id == id) - .map(|session| &mut session.chat) - } - - pub fn any_busy(&self) -> bool { - self.sessions.iter().any(|session| session.chat.busy) - } - - pub fn session_title(&self, id: SessionId) -> String { - self.sessions - .iter() - .find(|s| s.id == id) - .map(|s| s.chat.session_title()) - .unwrap_or_else(|| "Chat".into()) - } - - pub fn new_session(&mut self, provider: String, model: String, mode: ChatMode) -> SessionId { - let id = SessionId(self.next_id); - self.next_id += 1; - self.sessions.push(ChatSession { - id, - chat: ChatState::empty(), - provider, - model, - mode, - }); - self.active = id; - id - } - - pub fn focus(&mut self, id: SessionId) { - if self.sessions.iter().any(|s| s.id == id) { - self.active = id; - } - } - - pub fn active_settings(&self) -> (&str, &str, ChatMode) { - let session = self - .sessions - .iter() - .find(|session| session.id == self.active) - .expect("active session exists"); - (&session.provider, &session.model, session.mode) - } - - pub fn set_active_settings(&mut self, provider: String, model: String, mode: ChatMode) { - let active = self.active; - let session = self - .sessions - .iter_mut() - .find(|session| session.id == active) - .expect("active session exists"); - session.provider = provider; - session.model = model; - session.mode = mode; - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::state::{ChatMessage, MessageKind}; - - #[test] - fn background_session_updates_do_not_touch_active_chat() { - let mut sessions = SessionStore::new("demo".into(), "demo".into(), ChatMode::Agent); - let first = sessions.active_id(); - let second = sessions.new_session("demo".into(), "demo".into(), ChatMode::Agent); - sessions - .chat_mut(first) - .unwrap() - .messages - .push(ChatMessage { - kind: MessageKind::Assistant { - body: "background".into(), - streaming: false, - }, - }); - - assert_eq!(sessions.active_id(), second); - assert!(sessions.active_chat().messages.is_empty()); - assert_eq!(sessions.chat_mut(first).unwrap().messages.len(), 1); - } -} diff --git a/crates/pulsing-gui/src/model/workflows.rs b/crates/pulsing-gui/src/model/workflows.rs deleted file mode 100644 index ea385b3e4..000000000 --- a/crates/pulsing-gui/src/model/workflows.rs +++ /dev/null @@ -1,20 +0,0 @@ -use std::path::PathBuf; - -use pulsing_workspace::WorkspaceLayout; - -pub fn list_workflow_scripts(layout: &WorkspaceLayout) -> Vec { - let dir = layout.root.join(".pulsing").join("workflows"); - if !dir.is_dir() { - return Vec::new(); - } - let mut scripts: Vec = std::fs::read_dir(&dir) - .ok() - .into_iter() - .flatten() - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|ext| ext == "py")) - .collect(); - scripts.sort(); - scripts -} diff --git a/crates/pulsing-gui/src/model/workspace.rs b/crates/pulsing-gui/src/model/workspace.rs deleted file mode 100644 index fa1035482..000000000 --- a/crates/pulsing-gui/src/model/workspace.rs +++ /dev/null @@ -1,66 +0,0 @@ -use std::path::PathBuf; - -use pulsing_workspace::WorkspaceLayout; - -use super::revisions::RevisionSnapshot; -use super::workflows; - -#[derive(Clone, Debug, Default)] -pub struct RuntimeSummary { - pub local_busy: bool, - pub session_title: String, - pub file_count: usize, - pub revision_count: usize, - pub workflow_count: usize, -} - -pub struct WorkspaceModel { - pub layout: WorkspaceLayout, - pub runtime: RuntimeSummary, - pub selected_file: Option, - pub revisions: RevisionSnapshot, - pub workflow_scripts: Vec, -} - -impl WorkspaceModel { - pub fn new(cwd: PathBuf) -> Self { - let layout = WorkspaceLayout::new(cwd); - let revisions = super::revisions::load_revisions(&layout); - let workflow_scripts = workflows::list_workflow_scripts(&layout); - let revision_count = revisions.revisions.len(); - let workflow_count = workflow_scripts.len(); - Self { - layout, - runtime: RuntimeSummary { - revision_count, - workflow_count, - ..RuntimeSummary::default() - }, - selected_file: None, - revisions, - workflow_scripts, - } - } - - pub fn set_busy(&mut self, busy: bool) { - self.runtime.local_busy = busy; - } - - pub fn set_session_title(&mut self, title: String) { - self.runtime.session_title = title; - } - - pub fn set_selected_file(&mut self, path: Option) { - self.selected_file = path; - } - - pub fn refresh_revisions(&mut self) { - self.revisions = super::revisions::load_revisions(&self.layout); - self.runtime.revision_count = self.revisions.revisions.len(); - } - - pub fn refresh_workflows(&mut self) { - self.workflow_scripts = workflows::list_workflow_scripts(&self.layout); - self.runtime.workflow_count = self.workflow_scripts.len(); - } -} diff --git a/crates/pulsing-gui/src/settings.rs b/crates/pulsing-gui/src/settings.rs deleted file mode 100644 index 2424c52d5..000000000 --- a/crates/pulsing-gui/src/settings.rs +++ /dev/null @@ -1,144 +0,0 @@ -use pulsing_forge::{AgentConfig, DEFAULT_TOOL_NAMES}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ChatMode { - Agent, - AgentSafe, - Ask, - Plan, -} - -impl ChatMode { - pub const ALL: [ChatMode; 4] = [ - ChatMode::Agent, - ChatMode::AgentSafe, - ChatMode::Ask, - ChatMode::Plan, - ]; - - pub fn label(self) -> &'static str { - match self { - Self::Agent => "Agent", - Self::AgentSafe => "Agent · Safe", - Self::Ask => "Ask", - Self::Plan => "Plan", - } - } - - pub fn hint(self) -> &'static str { - match self { - Self::Agent => "Full tools — read, edit, and run commands in the workspace.", - Self::AgentSafe => "Full tools with restricted sandbox for shell commands.", - Self::Ask => "Chat only — no tools, best for quick questions.", - Self::Plan => "Read-only exploration — browse files before acting.", - } - } - - pub fn apply(self, cfg: &mut AgentConfig) { - match self { - Self::Agent => { - cfg.sandbox = "off".into(); - cfg.tool_names = DEFAULT_TOOL_NAMES - .iter() - .map(|s| (*s).to_string()) - .collect(); - cfg.system_prompt = None; - } - Self::AgentSafe => { - cfg.sandbox = "restricted".into(); - cfg.tool_names = DEFAULT_TOOL_NAMES - .iter() - .map(|s| (*s).to_string()) - .collect(); - cfg.system_prompt = None; - } - Self::Ask => { - cfg.sandbox = "off".into(); - cfg.tool_names = vec![]; - cfg.system_prompt = Some( - "You are a helpful coding assistant. Answer clearly and concisely without using tools." - .into(), - ); - } - Self::Plan => { - cfg.sandbox = "off".into(); - cfg.tool_names = ["update_plan", "Glob", "Read", "Grep"] - .iter() - .map(|s| (*s).to_string()) - .collect(); - cfg.system_prompt = Some( - "You help plan work by reading the codebase. Use read-only tools; do not edit files or run shell commands." - .into(), - ); - } - } - } -} - -pub struct ModelPreset { - pub provider: &'static str, - pub section: &'static str, - pub label: &'static str, - pub model: &'static str, -} - -pub const MODEL_PRESETS: &[ModelPreset] = &[ - ModelPreset { - provider: "demo", - section: "Demo", - label: "Demo (offline)", - model: "demo", - }, - ModelPreset { - provider: "anthropic", - section: "Anthropic", - label: "Claude Sonnet 4", - model: "claude-sonnet-4-20250514", - }, - ModelPreset { - provider: "anthropic", - section: "Anthropic", - label: "Claude 3.5 Sonnet", - model: "claude-3-5-sonnet-20241022", - }, - ModelPreset { - provider: "openai", - section: "OpenAI", - label: "GPT-4o", - model: "gpt-4o", - }, - ModelPreset { - provider: "openai", - section: "OpenAI", - label: "GPT-4o mini", - model: "gpt-4o-mini", - }, -]; - -pub fn provider_available(provider: &str) -> bool { - match provider.trim().to_lowercase().as_str() { - "demo" => true, - "openai" => std::env::var("OPENAI_API_KEY") - .map(|k| !k.is_empty()) - .unwrap_or(false), - _ => std::env::var("ANTHROPIC_API_KEY") - .map(|k| !k.is_empty()) - .unwrap_or(false), - } -} - -pub fn build_agent_config( - cwd: &std::path::Path, - provider: &str, - model: &str, - mode: ChatMode, -) -> AgentConfig { - let mut cfg = AgentConfig { - cwd: cwd.to_path_buf(), - provider: provider.to_string(), - model: model.to_string(), - ..AgentConfig::default() - }; - mode.apply(&mut cfg); - cfg -} diff --git a/crates/pulsing-gui/src/state.rs b/crates/pulsing-gui/src/state.rs deleted file mode 100644 index 93b0689a8..000000000 --- a/crates/pulsing-gui/src/state.rs +++ /dev/null @@ -1,186 +0,0 @@ -use pulsing_forge::AgentEvent; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum MessageKind { - User(String), - Assistant { - body: String, - streaming: bool, - }, - Tool { - name: String, - running: bool, - ok: bool, - detail: String, - }, - Error(String), -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ChatMessage { - pub kind: MessageKind, -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct ChatState { - pub messages: Vec, - pub busy: bool, -} - -impl ChatState { - pub fn empty() -> Self { - Self::default() - } - - pub fn session_title(&self) -> String { - self.messages - .iter() - .find_map(|m| { - if let MessageKind::User(text) = &m.kind { - let t = text.trim(); - if t.is_empty() { - None - } else if t.chars().count() > 28 { - Some(format!("{}…", t.chars().take(28).collect::())) - } else { - Some(t.to_string()) - } - } else { - None - } - }) - .unwrap_or_else(|| "New Chat".into()) - } - - pub fn apply(&mut self, event: AgentEvent) { - match event { - AgentEvent::TextDelta(delta) => { - if let Some(ChatMessage { - kind: MessageKind::Assistant { body, streaming }, - }) = self.messages.last_mut() - { - if *streaming { - body.push_str(&delta); - return; - } - } - self.messages.push(ChatMessage { - kind: MessageKind::Assistant { - body: delta, - streaming: true, - }, - }); - } - AgentEvent::ToolStart { name } => { - self.finish_streaming_assistant(); - self.messages.push(ChatMessage { - kind: MessageKind::Tool { - name, - running: true, - ok: true, - detail: String::new(), - }, - }); - } - AgentEvent::ToolEnd { name, ok, summary } => { - if let Some(ChatMessage { - kind: MessageKind::Tool { - name: n, - running, - ok: tool_ok, - detail, - }, - }) = self.messages.iter_mut().rev().find(|m| { - matches!(m.kind, MessageKind::Tool { name: ref tn, running: true, .. } if tn == &name) - }) { - *running = false; - *tool_ok = ok; - *detail = summary; - *n = name; - } else { - self.messages.push(ChatMessage { - kind: MessageKind::Tool { - name, - running: false, - ok, - detail: summary, - }, - }); - } - self.messages.push(ChatMessage { - kind: MessageKind::Assistant { - body: String::new(), - streaming: true, - }, - }); - } - AgentEvent::ToolCancelled { name } => { - self.apply(AgentEvent::ToolEnd { - name, - ok: false, - summary: "cancelled".into(), - }); - } - AgentEvent::Done { text } => { - self.finish_streaming_assistant(); - if let Some(ChatMessage { - kind: MessageKind::Assistant { body, streaming }, - }) = self.messages.last_mut() - { - if body.is_empty() { - *body = text; - } - *streaming = false; - } - self.busy = false; - } - AgentEvent::Error(message) => { - self.finish_streaming_assistant(); - self.messages.push(ChatMessage { - kind: MessageKind::Error(message), - }); - self.busy = false; - } - AgentEvent::Cancelled => { - self.finish_streaming_assistant(); - self.busy = false; - } - } - } - - fn finish_streaming_assistant(&mut self) { - if let Some(ChatMessage { - kind: MessageKind::Assistant { streaming, .. }, - }) = self.messages.last_mut() - { - *streaming = false; - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cancellation_is_terminal_for_the_chat_projection() { - let mut chat = ChatState { - messages: vec![ChatMessage { - kind: MessageKind::Assistant { - body: "partial".into(), - streaming: true, - }, - }], - busy: true, - }; - chat.apply(AgentEvent::Cancelled); - assert!(!chat.busy); - assert!(matches!( - chat.messages[0].kind, - MessageKind::Assistant { - streaming: false, - .. - } - )); - } -} diff --git a/crates/pulsing-py/Cargo.toml b/crates/pulsing-py/Cargo.toml index 08a573474..6a968771d 100644 --- a/crates/pulsing-py/Cargo.toml +++ b/crates/pulsing-py/Cargo.toml @@ -21,7 +21,6 @@ crate-type = ["cdylib", "rlib"] [dependencies] pulsing-actor = { workspace = true } -pulsing-forge = { path = "../pulsing-forge" } anyhow = { workspace = true } async-trait = { workspace = true } futures = { workspace = true } diff --git a/crates/pulsing-py/src/forge.rs b/crates/pulsing-py/src/forge.rs deleted file mode 100644 index 74d1103ab..000000000 --- a/crates/pulsing-py/src/forge.rs +++ /dev/null @@ -1,730 +0,0 @@ -//! PyO3 bindings for `pulsing-forge` — Rust-native tool runtime. - -use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; - -use pulsing_forge::approval::{ - ApprovalPolicy, ExecApprovalRequest, RequestPermissionsArgs, RequestPermissionsResponse, - ReviewDecision, -}; -use pulsing_forge::context::{LocalToolSession, NullToolSession, ToolSession, UpdatePlanArgs}; -use pulsing_forge::error::ToolError; -use pulsing_forge::exec_output::ExecOutputDelta; -use pulsing_forge::mcp::{new_shared_mcp_runtime, refresh_mcp_runtime, SharedMcpRuntime}; -use pulsing_forge::result::ToolResult; -use pulsing_forge::runtime::{ToolRuntime, ToolRuntimeConfig}; -use pulsing_forge::unified_exec::UnifiedExecManager; -use pulsing_forge::{AgentConfig, ForgeEventKind, LocalForgeClient, SessionId, TurnId}; -use pyo3::exceptions::PyRuntimeError; -use pyo3::prelude::*; -use pyo3::types::{PyAny, PyDict}; -use serde_json::Value; -use tokio::runtime::Handle; - -struct PyForgeSession { - event_cb: Py, - user_input_cb: Option>, - exec_approval_cb: Option>, - permissions_cb: Option>, - tokens_remaining_cb: Option>, - plugin_install_cb: Option>, - auto_approve: bool, -} - -unsafe impl Send for PyForgeSession {} -unsafe impl Sync for PyForgeSession {} - -impl PyForgeSession { - fn new( - event_cb: Py, - user_input_cb: Option>, - exec_approval_cb: Option>, - permissions_cb: Option>, - tokens_remaining_cb: Option>, - plugin_install_cb: Option>, - auto_approve: bool, - ) -> Self { - Self { - event_cb, - user_input_cb, - exec_approval_cb, - permissions_cb, - tokens_remaining_cb, - plugin_install_cb, - auto_approve, - } - } - - fn emit( - &self, - py: Python<'_>, - kind: &str, - payload: Value, - source: Option<&str>, - ) -> Result<(), ToolError> { - let dict = PyDict::new(py); - dict.set_item("kind", kind) - .map_err(|e| ToolError::respond(e.to_string()))?; - dict.set_item( - "payload", - json_to_py(py, &payload).map_err(|e| ToolError::respond(e.to_string()))?, - ) - .map_err(|e| ToolError::respond(e.to_string()))?; - if let Some(s) = source { - dict.set_item("source", s) - .map_err(|e| ToolError::respond(e.to_string()))?; - } - let ts = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs_f64()) - .unwrap_or(0.0); - dict.set_item("ts", ts) - .map_err(|e| ToolError::respond(e.to_string()))?; - self.event_cb - .call1(py, (dict,)) - .map_err(|e| ToolError::respond(e.to_string()))?; - Ok(()) - } -} - -impl ToolSession for PyForgeSession { - fn update_plan(&self, args: UpdatePlanArgs) -> Result<(), ToolError> { - Python::with_gil(|py| { - let plan: Vec = args - .plan - .iter() - .map(|p| { - serde_json::json!({ - "step": p.step, - "status": match p.status { - pulsing_forge::context::StepStatus::Pending => "pending", - pulsing_forge::context::StepStatus::InProgress => "in_progress", - pulsing_forge::context::StepStatus::Completed => "completed", - } - }) - }) - .collect(); - self.emit( - py, - "plan_updated", - serde_json::json!({ "plan": plan }), - None, - ) - }) - } - - fn request_new_context(&self) -> Result<(), ToolError> { - Python::with_gil(|py| self.emit(py, "new_context", serde_json::json!({}), None)) - } - - fn tokens_remaining(&self) -> Option { - Python::with_gil(|py| { - let cb = self.tokens_remaining_cb.as_ref()?; - let out = match cb.call0(py) { - Ok(out) => out, - Err(e) => { - tracing::warn!("tokens_remaining callback raised: {e}"); - return None; - } - }; - if out.is_none(py) { - return None; - } - match out.extract::(py) { - Ok(n) => Some(n), - Err(e) => { - tracing::warn!("tokens_remaining callback returned non-int: {e}"); - None - } - } - }) - } - - fn request_user_input(&self, arguments: Value) -> Result { - Python::with_gil(|py| { - self.emit(py, "user_input_request", arguments.clone(), None)?; - let cb = self.user_input_cb.as_ref().ok_or_else(|| { - ToolError::respond("request_user_input is not configured on this ToolSession") - })?; - let py_args = - json_to_py(py, &arguments).map_err(|e| ToolError::respond(e.to_string()))?; - let out = cb - .call1(py, (py_args,)) - .map_err(|e| ToolError::respond(e.to_string()))?; - py_to_json(&out.bind(py)).map_err(|e| ToolError::respond(e.to_string())) - }) - } - - fn on_exec_output_delta(&self, delta: ExecOutputDelta) -> Result<(), ToolError> { - Python::with_gil(|py| { - let stream = match delta.stream { - pulsing_forge::exec_output::ExecStream::Stdout => "stdout", - pulsing_forge::exec_output::ExecStream::Stderr => "stderr", - pulsing_forge::exec_output::ExecStream::Pty => "pty", - }; - self.emit( - py, - "exec_output_delta", - serde_json::json!({ - "session_id": delta.session_id, - "stream": stream, - "chunk": delta.chunk, - }), - None, - ) - }) - } - - fn approval_policy(&self) -> ApprovalPolicy { - if self.auto_approve { - ApprovalPolicy::Always - } else { - ApprovalPolicy::OnRequest - } - } - - fn request_exec_approval( - &self, - request: ExecApprovalRequest, - ) -> Result { - if self.auto_approve { - return Ok(ReviewDecision::Approved); - } - Python::with_gil(|py| { - let payload = - serde_json::to_value(&request).map_err(|e| ToolError::respond(e.to_string()))?; - self.emit(py, "exec_approval_request", payload.clone(), None)?; - let cb = self.exec_approval_cb.as_ref().ok_or_else(|| { - ToolError::respond("exec approval is not configured on this ToolSession") - })?; - let py_req = json_to_py(py, &payload).map_err(|e| ToolError::respond(e.to_string()))?; - let out = cb - .call1(py, (py_req,)) - .map_err(|e| ToolError::respond(e.to_string()))?; - parse_review_decision(&out.bind(py), &request) - }) - } - - fn request_permissions( - &self, - args: RequestPermissionsArgs, - ) -> Result { - if self.auto_approve { - return Ok(RequestPermissionsResponse { - permissions: args.permissions.clone(), - scope: "session".into(), - strict_auto_review: false, - }); - } - Python::with_gil(|py| { - let payload = - serde_json::to_value(&args).map_err(|e| ToolError::respond(e.to_string()))?; - self.emit(py, "request_permissions", payload.clone(), None)?; - let cb = self.permissions_cb.as_ref().ok_or_else(|| { - ToolError::respond("request_permissions is not configured on this ToolSession") - })?; - let py_args = - json_to_py(py, &payload).map_err(|e| ToolError::respond(e.to_string()))?; - let out = cb - .call1(py, (py_args,)) - .map_err(|e| ToolError::respond(e.to_string()))?; - serde_json::from_value( - py_to_json(&out.bind(py)).map_err(|e| ToolError::respond(e.to_string()))?, - ) - .map_err(|e| ToolError::respond(format!("invalid request_permissions response: {e}"))) - }) - } - - fn request_plugin_install( - &self, - tool_id: String, - tool_name: String, - suggest_reason: String, - ) -> Result { - if self.auto_approve { - return Ok(true); - } - Python::with_gil(|py| { - let payload = serde_json::json!({ - "tool_id": tool_id, - "tool_name": tool_name, - "suggest_reason": suggest_reason, - }); - self.emit(py, "plugin_install_request", payload.clone(), None)?; - let cb = self.plugin_install_cb.as_ref().ok_or_else(|| { - ToolError::respond("request_plugin_install is not configured on this ToolSession") - })?; - let py_args = - json_to_py(py, &payload).map_err(|e| ToolError::respond(e.to_string()))?; - let out = cb - .call1(py, (py_args,)) - .map_err(|e| ToolError::respond(e.to_string()))?; - if let Ok(b) = out.extract::(py) { - return Ok(b); - } - if let Ok(s) = out.extract::(py) { - return Ok(matches!( - s.trim().to_lowercase().as_str(), - "approved" | "allow" | "once" | "yes" | "true" - )); - } - Err(ToolError::respond( - "plugin_install callback returned invalid decision", - )) - }) - } -} - -fn noop_event_callback(py: Python<'_>) -> PyResult> { - Ok(py.eval_bound("lambda _event: None", None, None)?.unbind()) -} - -fn needs_py_forge_session( - event_callback: &Option>, - user_input_callback: &Option>, - exec_approval_callback: &Option>, - request_permissions_callback: &Option>, - tokens_remaining_callback: &Option>, - plugin_install_callback: &Option>, -) -> bool { - event_callback.is_some() - || user_input_callback.is_some() - || exec_approval_callback.is_some() - || request_permissions_callback.is_some() - || tokens_remaining_callback.is_some() - || plugin_install_callback.is_some() -} - -#[pyclass(name = "ForgeRuntime")] -pub struct PyForgeRuntime { - runtime: ToolRuntime, - event_cb: Option>, - mcp_slot: Option, -} - -/// Python client for the canonical Rust Forge session control plane. -#[pyclass(name = "ForgeClient")] -pub struct PyForgeClient { - client: LocalForgeClient, - runtime: tokio::runtime::Runtime, -} - -#[pymethods] -impl PyForgeClient { - #[new] - fn new() -> PyResult { - let runtime = tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .map_err(|err| PyRuntimeError::new_err(err.to_string()))?; - Ok(Self { - client: LocalForgeClient::default(), - runtime, - }) - } - - #[pyo3(signature = ( - cwd=".", - provider="demo", - model="demo", - max_tokens=8192, - max_turns=20, - sandbox="off", - tool_names=None, - system_prompt=None, - auto_approve=true - ))] - #[allow(clippy::too_many_arguments)] - fn create_session( - &self, - py: Python<'_>, - cwd: &str, - provider: &str, - model: &str, - max_tokens: u32, - max_turns: usize, - sandbox: &str, - tool_names: Option>, - system_prompt: Option, - auto_approve: bool, - ) -> PyResult { - let config = AgentConfig { - cwd: cwd.into(), - provider: provider.into(), - model: model.into(), - max_tokens, - max_turns, - sandbox: sandbox.into(), - approval_policy: if auto_approve { - ApprovalPolicy::Always - } else { - ApprovalPolicy::OnRequest - }, - tool_names: tool_names.unwrap_or_else(|| { - pulsing_forge::DEFAULT_TOOL_NAMES - .iter() - .map(|name| (*name).to_string()) - .collect() - }), - system_prompt, - }; - let client = self.client.clone(); - py.allow_threads(|| { - self.runtime - .block_on(client.create_session(config)) - .map(|id| id.to_string()) - .map_err(forge_protocol_error) - }) - } - - fn start_turn(&self, py: Python<'_>, session_id: &str, input: &str) -> PyResult { - let client = self.client.clone(); - let session_id = SessionId::from_string(session_id); - let input = input.to_string(); - let receipt = py.allow_threads(|| { - self.runtime - .block_on(client.start_turn(session_id, input)) - .map_err(forge_protocol_error) - })?; - Python::with_gil(|py| { - json_to_py( - py, - &serde_json::json!({ - "command_id": receipt.command_id.as_str(), - "session_id": receipt.session_id.as_str(), - "turn_id": receipt.turn_id.as_ref().map(|id| id.as_str()), - "accepted_seq": receipt.accepted_seq, - }), - ) - .map(Into::into) - }) - } - - fn wait_turn( - &self, - py: Python<'_>, - session_id: &str, - turn_id: &str, - after_seq: u64, - ) -> PyResult { - let client = self.client.clone(); - let session_id = SessionId::from_string(session_id); - let turn_id = TurnId::from_string(turn_id); - let value = py.allow_threads(|| { - self.runtime - .block_on(async move { - let mut subscription = client.subscribe(&session_id, after_seq).await?; - let mut events = Vec::new(); - let terminal = loop { - let event = subscription.recv().await?; - if event.turn_id.as_ref() != Some(&turn_id) { - continue; - } - let terminal = match &event.kind { - ForgeEventKind::TurnCompleted { text } => Some(serde_json::json!({ - "status": "completed", - "text": text, - })), - ForgeEventKind::TurnFailed { message } => Some(serde_json::json!({ - "status": "failed", - "message": message, - })), - ForgeEventKind::TurnCancelled => Some(serde_json::json!({ - "status": "cancelled", - })), - _ => None, - }; - events.push(serde_json::to_value(&event).map_err(|err| { - pulsing_forge::ForgeProtocolError::Internal(err.to_string()) - })?); - if let Some(terminal) = terminal { - break terminal; - } - }; - Ok::<_, pulsing_forge::ForgeProtocolError>(serde_json::json!({ - "terminal": terminal, - "events": events, - })) - }) - .map_err(forge_protocol_error) - })?; - Python::with_gil(|py| json_to_py(py, &value).map(Into::into)) - } - - fn cancel_turn(&self, py: Python<'_>, session_id: &str, turn_id: &str) -> PyResult { - let client = self.client.clone(); - let session_id = SessionId::from_string(session_id); - let turn_id = TurnId::from_string(turn_id); - let receipt = py.allow_threads(|| { - self.runtime - .block_on(client.cancel_turn(session_id, turn_id)) - .map_err(forge_protocol_error) - })?; - Python::with_gil(|py| { - json_to_py( - py, - &serde_json::json!({ - "command_id": receipt.command_id.as_str(), - "session_id": receipt.session_id.as_str(), - "turn_id": receipt.turn_id.as_ref().map(|id| id.as_str()), - "accepted_seq": receipt.accepted_seq, - }), - ) - .map(Into::into) - }) - } - - fn snapshot(&self, py: Python<'_>, session_id: &str) -> PyResult { - let client = self.client.clone(); - let session_id = SessionId::from_string(session_id); - let snapshot = py.allow_threads(|| { - self.runtime - .block_on(client.snapshot(&session_id)) - .map_err(forge_protocol_error) - })?; - let value = serde_json::to_value(snapshot) - .map_err(|err| PyRuntimeError::new_err(err.to_string()))?; - Python::with_gil(|py| json_to_py(py, &value).map(Into::into)) - } -} - -fn forge_protocol_error(err: pulsing_forge::ForgeProtocolError) -> PyErr { - PyRuntimeError::new_err(err.to_string()) -} - -#[pymethods] -impl PyForgeRuntime { - #[new] - #[pyo3(signature = (cwd=".", sandbox_policy="off", dangerously_disable_sandbox=false, auto_approve=false, event_callback=None, user_input_callback=None, exec_approval_callback=None, request_permissions_callback=None, tokens_remaining_callback=None, plugin_install_callback=None, start_mcp=true))] - fn new( - cwd: &str, - sandbox_policy: &str, - dangerously_disable_sandbox: bool, - auto_approve: bool, - event_callback: Option>, - user_input_callback: Option>, - exec_approval_callback: Option>, - request_permissions_callback: Option>, - tokens_remaining_callback: Option>, - plugin_install_callback: Option>, - start_mcp: bool, - ) -> PyResult { - let session: Arc = if needs_py_forge_session( - &event_callback, - &user_input_callback, - &exec_approval_callback, - &request_permissions_callback, - &tokens_remaining_callback, - &plugin_install_callback, - ) { - let event_cb = match &event_callback { - Some(cb) => cb.clone(), - None => Python::with_gil(noop_event_callback)?, - }; - Arc::new(PyForgeSession::new( - event_cb, - user_input_callback, - exec_approval_callback, - request_permissions_callback, - tokens_remaining_callback, - plugin_install_callback, - auto_approve, - )) - } else if auto_approve { - Arc::new(LocalToolSession::default().with_approval_policy(ApprovalPolicy::Always)) - } else { - Arc::new(NullToolSession) - }; - let mcp_slot = if start_mcp { - Some(new_shared_mcp_runtime()) - } else { - None - }; - if let Some(ref slot) = mcp_slot { - block_on_tool(refresh_mcp_runtime(slot)); - } - let runtime = ToolRuntime::new(ToolRuntimeConfig { - cwd: cwd.into(), - sandbox_policy: sandbox_policy.to_string(), - dangerously_disable_sandbox, - session, - exec: Arc::new(UnifiedExecManager::new()), - mcp_runtime: mcp_slot.clone(), - ..Default::default() - }); - Ok(Self { - runtime, - event_cb: event_callback, - mcp_slot, - }) - } - - /// Reload MCP catalog and reconnect configured servers. - fn refresh_mcp(&self) -> PyResult<()> { - if let Some(slot) = &self.mcp_slot { - block_on_tool(refresh_mcp_runtime(slot)); - } - Ok(()) - } - - fn mcp_tool_names(&self) -> PyResult> { - if let Some(slot) = &self.mcp_slot { - let names = block_on_tool(async { - let guard = slot.read().await; - guard - .as_ref() - .map(|runtime| runtime.tool_model_names()) - .unwrap_or_default() - }); - Ok(names) - } else { - Ok(vec![]) - } - } - - /// Model-visible MCP function tools (name, description, input_schema, server/tool ids). - fn mcp_tool_specs(&self) -> PyResult> { - Python::with_gil(|py| { - if let Some(slot) = &self.mcp_slot { - let specs = block_on_tool(async { - let guard = slot.read().await; - guard - .as_ref() - .map(|runtime| runtime.tool_specs_for_model()) - .unwrap_or_default() - }); - specs - .iter() - .map(|spec| json_to_py(py, spec).map(|v| v.into())) - .collect() - } else { - Ok(vec![]) - } - }) - } - - fn tool_names(&self) -> Vec { - self.runtime.tool_names() - } - - /// Execute a tool (sync — for actor workers and in-process hosts). - #[pyo3(signature = (name, arguments=None))] - fn call_tool( - &self, - py: Python<'_>, - name: String, - arguments: Option>, - ) -> PyResult { - let args = match arguments { - Some(obj) => py_to_json(&obj)?, - None => Value::Object(Default::default()), - }; - if let Some(ref cb) = self.event_cb { - let dict = PyDict::new(py); - dict.set_item("kind", "tool_begin")?; - let payload = PyDict::new(py); - payload.set_item("arguments", json_to_py(py, &args)?)?; - dict.set_item("payload", payload)?; - dict.set_item("source", &name)?; - cb.call1(py, (dict,))?; - } - let name_for = name.clone(); - let out = py.allow_threads(|| { - block_on_tool(async { self.runtime.call_tool(&name_for, args).await }) - }); - if let Some(ref cb) = self.event_cb { - let dict = PyDict::new(py); - dict.set_item("kind", "tool_end")?; - let payload = PyDict::new(py); - payload.set_item("is_error", out.is_error)?; - let preview: String = out.content.chars().take(500).collect(); - payload.set_item("content_preview", preview)?; - dict.set_item("payload", payload)?; - dict.set_item("source", &name)?; - cb.call1(py, (dict,))?; - } - tool_result_to_py(py, &out) - } -} - -fn parse_review_decision( - obj: &Bound<'_, PyAny>, - request: &ExecApprovalRequest, -) -> Result { - if let Ok(s) = obj.extract::() { - return map_decision_str(&s, request); - } - if let Ok(dict) = obj.downcast::() { - if let Some(item) = dict.get_item("decision").ok().flatten() { - if let Ok(s) = item.extract::() { - return map_decision_str(&s, request); - } - } - } - Err(ToolError::respond( - "exec approval callback returned invalid decision", - )) -} - -fn map_decision_str(raw: &str, request: &ExecApprovalRequest) -> Result { - match raw.trim().to_lowercase().as_str() { - "approved" | "allow" | "once" => Ok(ReviewDecision::Approved), - "approved_for_session" | "allow_session" => Ok(ReviewDecision::ApprovedForSession), - "approved_with_amendment" | "allow_always" => { - let prefix = request - .proposed_execpolicy_amendment - .clone() - .unwrap_or_else(|| request.command.clone()); - Ok(ReviewDecision::ApprovedExecpolicyAmendment { - proposed_execpolicy_amendment: prefix, - }) - } - "abort" => Ok(ReviewDecision::Abort), - _ => Ok(ReviewDecision::Denied), - } -} - -pub(crate) fn block_on_tool(f: F) -> T -where - F: std::future::Future, -{ - if let Ok(handle) = Handle::try_current() { - tokio::task::block_in_place(|| handle.block_on(f)) - } else { - tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .expect("forge tokio runtime") - .block_on(f) - } -} - -pub(crate) fn py_to_json(obj: &Bound<'_, PyAny>) -> PyResult { - let py = obj.py(); - let json = py.import("json")?; - let s: String = json.call_method1("dumps", (obj,))?.extract()?; - serde_json::from_str(&s).map_err(|e| PyRuntimeError::new_err(e.to_string())) -} - -pub(crate) fn json_to_py<'py>(py: Python<'py>, value: &Value) -> PyResult> { - let json = py.import("json")?; - let s = serde_json::to_string(value).map_err(|e| PyRuntimeError::new_err(e.to_string()))?; - Ok(json.call_method1("loads", (s,))?) -} - -fn tool_result_to_py(py: Python<'_>, r: &ToolResult) -> PyResult { - let dict = PyDict::new(py); - dict.set_item("content", &r.content)?; - dict.set_item("is_error", r.is_error)?; - if let Some(ref structured) = r.structured { - dict.set_item("structured", json_to_py(py, structured)?)?; - } - Ok(dict.into()) -} - -pub fn add_to_module(m: &Bound<'_, PyModule>) -> PyResult<()> { - m.add_class::()?; - m.add_class::()?; - crate::llm::add_to_module(m)?; - Ok(()) -} diff --git a/crates/pulsing-py/src/lib.rs b/crates/pulsing-py/src/lib.rs index b114373b1..05c4b0226 100644 --- a/crates/pulsing-py/src/lib.rs +++ b/crates/pulsing-py/src/lib.rs @@ -8,8 +8,6 @@ use pyo3::prelude::*; mod actor; mod connect; mod errors; -mod forge; -mod llm; mod policies; mod python_error_converter; mod python_executor; @@ -24,7 +22,7 @@ pub use python_executor::{init_python_executor, python_executor, ExecutorError}; /// - Actor types: NodeId, ActorId, ActorRef /// - Message types: Message, StreamMessage /// - Streaming: StreamReader, StreamWriter -/// - Load balancing policies: Random, RoundRobin, PowerOfTwo, ConsistentHash, CacheAware +/// - Load balancing policies: Random, RoundRobin, PowerOfTwo, ConsistentHash #[pymodule] pub fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> { // Add error classes @@ -41,8 +39,6 @@ pub fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> { tracing_py::add_to_module(m)?; - forge::add_to_module(m)?; - // Add version m.add("__version__", env!("CARGO_PKG_VERSION"))?; diff --git a/crates/pulsing-py/src/llm.rs b/crates/pulsing-py/src/llm.rs deleted file mode 100644 index 421c10e18..000000000 --- a/crates/pulsing-py/src/llm.rs +++ /dev/null @@ -1,207 +0,0 @@ -//! PyO3 bindings for `pulsing-forge` LLM client. - -use pulsing_forge::llm::{LlmClient, LlmError, LlmMessage, LlmStream, StreamRequest}; -use pyo3::exceptions::{PyRuntimeError, PyValueError}; -use pyo3::prelude::*; -use pyo3::types::{PyDict, PyList}; -use serde_json::Value; - -use crate::forge::{block_on_tool, json_to_py, py_to_json}; - -#[pyclass(name = "LlmClient")] -#[derive(Clone)] -pub struct PyLlmClient { - inner: LlmClient, -} - -#[pyclass(name = "LlmStream")] -pub struct PyLlmStream { - chunks: Vec, - final_message: LlmMessage, - entered: bool, -} - -#[pymethods] -impl PyLlmClient { - #[new] - #[pyo3(signature = (*, provider="anthropic", api_key=None, base_url=None))] - fn new(provider: &str, api_key: Option, base_url: Option) -> PyResult { - let inner = LlmClient::new(provider, api_key, base_url) - .map_err(|e| PyValueError::new_err(e.to_string()))?; - Ok(Self { inner }) - } - - #[getter] - fn provider(&self) -> String { - self.inner.provider().as_str().to_string() - } - - #[pyo3(signature = (*, model, max_tokens, messages, system=None, tools=None))] - fn stream_messages( - &self, - py: Python<'_>, - model: String, - max_tokens: u32, - messages: &Bound<'_, PyAny>, - system: Option, - tools: Option<&Bound<'_, PyAny>>, - ) -> PyResult { - let messages_json = py_list_to_values(py, messages)?; - let tools_json = match tools { - Some(t) => py_list_to_values(py, t)?, - None => Vec::new(), - }; - let req = StreamRequest { - model, - max_tokens, - messages: messages_json, - system, - tools: tools_json, - }; - let client = self.inner.clone(); - let stream = block_on_tool(async move { client.stream_messages(req).await }) - .map_err(|e: LlmError| PyRuntimeError::new_err(e.to_string()))?; - Ok(PyLlmStream::from_rust(stream)) - } - - #[staticmethod] - fn error_message(exc: &Bound<'_, PyAny>) -> String { - exc.str().ok().map(|s| s.to_string()).unwrap_or_default() - } - - fn is_authentication_error(&self, exc: &Bound<'_, PyAny>) -> PyResult { - Ok(classify_py_error(exc)?.is_authentication_error()) - } - - fn is_retryable_error(&self, exc: &Bound<'_, PyAny>) -> PyResult { - Ok(classify_py_error(exc)?.is_retryable_error()) - } - - fn is_api_error(&self, exc: &Bound<'_, PyAny>) -> PyResult { - Ok(classify_py_error(exc)?.is_api_error()) - } -} - -#[pymethods] -impl PyLlmStream { - fn __enter__(mut slf: PyRefMut<'_, Self>) -> PyRefMut<'_, Self> { - slf.entered = true; - slf - } - - fn __exit__( - &mut self, - _exc_type: Option<&Bound<'_, PyAny>>, - _exc: Option<&Bound<'_, PyAny>>, - _tb: Option<&Bound<'_, PyAny>>, - ) -> bool { - false - } - - fn close(&self) {} - - #[getter] - fn text_stream(slf: PyRef<'_, Self>) -> PyResult> { - let py = slf.py(); - let iter = PyLlmTextIter { - chunks: slf.chunks.clone(), - index: 0, - }; - Ok(Py::new(py, iter)?.into_any()) - } - - fn get_final_message(&self, py: Python<'_>) -> PyResult> { - llm_message_to_py(py, &self.final_message) - } -} - -#[pyclass] -struct PyLlmTextIter { - chunks: Vec, - index: usize, -} - -#[pymethods] -impl PyLlmTextIter { - fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { - slf - } - - fn __next__(mut slf: PyRefMut<'_, Self>) -> PyResult> { - if slf.index >= slf.chunks.len() { - return Ok(None); - } - let chunk = slf.chunks[slf.index].clone(); - slf.index += 1; - Ok(Some(chunk)) - } -} - -impl PyLlmStream { - fn from_rust(stream: LlmStream) -> Self { - let chunks = stream.text_chunks(); - let final_message = stream.final_message(); - Self { - chunks, - final_message, - entered: false, - } - } -} - -fn py_list_to_values(py: Python<'_>, obj: &Bound<'_, PyAny>) -> PyResult> { - if let Ok(list) = obj.downcast::() { - list.iter() - .map(|item| py_to_json(&item)) - .collect::>>() - } else { - Ok(vec![py_to_json(obj)?]) - } -} - -fn llm_message_to_py(py: Python<'_>, msg: &LlmMessage) -> PyResult> { - let dict = PyDict::new(py); - dict.set_item( - "content", - json_to_py(py, &Value::Array(msg.content.clone()))?, - )?; - if let Some(usage) = &msg.usage { - let u = PyDict::new(py); - u.set_item("input_tokens", usage.input_tokens)?; - u.set_item("output_tokens", usage.output_tokens)?; - dict.set_item("usage", u)?; - } else { - dict.set_item("usage", py.None())?; - } - dict.set_item("stop_reason", msg.stop_reason.clone())?; - Ok(dict.into()) -} - -fn classify_py_error(exc: &Bound<'_, PyAny>) -> PyResult { - if let Ok(status) = exc.getattr("status_code") { - if let Ok(code) = status.extract::() { - let body = exc.str().map(|s| s.to_string()).unwrap_or_default(); - return Ok(LlmError::Api { status: code, body }); - } - } - let msg = exc.str().map(|s| s.to_string()).unwrap_or_default(); - if msg.contains("401") || msg.contains("403") || msg.to_lowercase().contains("auth") { - return Ok(LlmError::Api { - status: 401, - body: msg, - }); - } - if msg.to_lowercase().contains("rate limit") { - return Ok(LlmError::Api { - status: 429, - body: msg, - }); - } - Ok(LlmError::Other(msg)) -} - -pub fn add_to_module(m: &Bound<'_, PyModule>) -> PyResult<()> { - m.add_class::()?; - m.add_class::()?; - Ok(()) -} diff --git a/crates/pulsing-py/src/policies.rs b/crates/pulsing-py/src/policies.rs index 6f75bf9a9..7ed7bd7d8 100644 --- a/crates/pulsing-py/src/policies.rs +++ b/crates/pulsing-py/src/policies.rs @@ -4,8 +4,8 @@ //! that can be used with the router actor. use pulsing_actor::policies::{ - CacheAwareConfig, CacheAwarePolicy, ConsistentHashPolicy, LoadBalancingPolicy, - PowerOfTwoPolicy, RandomPolicy, RoundRobinPolicy, Worker, + ConsistentHashPolicy, LoadBalancingPolicy, PowerOfTwoPolicy, RandomPolicy, RoundRobinPolicy, + Worker, }; use pyo3::prelude::*; use std::collections::HashMap; @@ -21,7 +21,6 @@ use std::sync::Arc; #[derive(Debug, Clone)] pub struct PyWorkerInfo { url: String, - model_id: String, healthy: Arc, load: Arc, processed: Arc, @@ -30,11 +29,9 @@ pub struct PyWorkerInfo { #[pymethods] impl PyWorkerInfo { #[new] - #[pyo3(signature = (url, model_id="default".to_string()))] - fn new(url: String, model_id: String) -> Self { + fn new(url: String) -> Self { Self { url, - model_id, healthy: Arc::new(AtomicBool::new(true)), load: Arc::new(AtomicUsize::new(0)), processed: Arc::new(AtomicU64::new(0)), @@ -46,11 +43,6 @@ impl PyWorkerInfo { &self.url } - #[getter] - fn model_id(&self) -> &str { - &self.model_id - } - #[getter] fn is_healthy(&self) -> bool { self.healthy.load(Ordering::Relaxed) @@ -85,9 +77,8 @@ impl PyWorkerInfo { fn __repr__(&self) -> String { format!( - "WorkerInfo(url='{}', model='{}', healthy={}, load={})", + "WorkerInfo(url='{}', healthy={}, load={})", self.url, - self.model_id, self.is_healthy(), self.load() ) @@ -133,10 +124,6 @@ impl Worker for PyWorkerWrapper { self.inner.processed.load(Ordering::Relaxed) } - fn model_id(&self) -> &str { - &self.inner.model_id - } - fn as_any(&self) -> &dyn std::any::Any { self } @@ -310,136 +297,6 @@ impl PyConsistentHashPolicy { } } -/// Cache-aware load balancing policy configuration -#[pyclass(name = "CacheAwareConfig")] -#[derive(Clone)] -pub struct PyCacheAwareConfig { - /// Minimum prefix match ratio (0.0 to 1.0) - #[pyo3(get, set)] - pub cache_threshold: f32, - /// Absolute difference threshold for load imbalance - #[pyo3(get, set)] - pub balance_abs_threshold: usize, - /// Relative ratio threshold for load imbalance - #[pyo3(get, set)] - pub balance_rel_threshold: f32, - /// Interval between eviction cycles (0 to disable) - #[pyo3(get, set)] - pub eviction_interval_secs: u64, - /// Maximum tree size per tenant - #[pyo3(get, set)] - pub max_tree_size: usize, -} - -#[pymethods] -impl PyCacheAwareConfig { - #[new] - #[pyo3(signature = ( - cache_threshold=0.5, - balance_abs_threshold=32, - balance_rel_threshold=1.0001, - eviction_interval_secs=60, - max_tree_size=100000 - ))] - fn new( - cache_threshold: f32, - balance_abs_threshold: usize, - balance_rel_threshold: f32, - eviction_interval_secs: u64, - max_tree_size: usize, - ) -> Self { - Self { - cache_threshold, - balance_abs_threshold, - balance_rel_threshold, - eviction_interval_secs, - max_tree_size, - } - } - - fn __repr__(&self) -> String { - format!( - "CacheAwareConfig(cache_threshold={}, balance_abs={}, balance_rel={}, eviction_secs={}, max_tree={})", - self.cache_threshold, - self.balance_abs_threshold, - self.balance_rel_threshold, - self.eviction_interval_secs, - self.max_tree_size - ) - } -} - -impl From for CacheAwareConfig { - fn from(py_config: PyCacheAwareConfig) -> Self { - CacheAwareConfig { - cache_threshold: py_config.cache_threshold, - balance_abs_threshold: py_config.balance_abs_threshold, - balance_rel_threshold: py_config.balance_rel_threshold, - eviction_interval_secs: py_config.eviction_interval_secs, - max_tree_size: py_config.max_tree_size, - } - } -} - -/// Cache-aware load balancing policy -#[pyclass(name = "CacheAwarePolicy")] -pub struct PyCacheAwarePolicy { - inner: CacheAwarePolicy, -} - -#[pymethods] -impl PyCacheAwarePolicy { - #[new] - #[pyo3(signature = (config=None))] - fn new(config: Option) -> Self { - let inner = match config { - Some(cfg) => CacheAwarePolicy::with_config(cfg.into()), - None => CacheAwarePolicy::new(), - }; - Self { inner } - } - - /// Initialize workers in the tree - fn init_workers(&self, workers: Vec) { - let rust_workers = py_workers_to_rust(&workers); - self.inner.init_workers(&rust_workers); - } - - /// Add a worker - fn add_worker(&self, url: &str, model_id: &str) { - self.inner.add_worker_by_url(url, model_id); - } - - /// Remove a worker - fn remove_worker(&self, url: &str) { - self.inner.remove_worker_by_url(url); - } - - #[pyo3(signature = (workers, request_text=None))] - fn select_worker( - &self, - workers: Vec, - request_text: Option<&str>, - ) -> Option { - let rust_workers = py_workers_to_rust(&workers); - self.inner.select_worker(&rust_workers, request_text) - } - - /// Manually trigger cache eviction - fn evict_cache(&self, max_size: usize) { - self.inner.evict_cache(max_size); - } - - #[getter] - fn name(&self) -> &'static str { - self.inner.name() - } - - fn __repr__(&self) -> String { - "CacheAwarePolicy()".to_string() - } -} - // ============================================================================ // Module Registration // ============================================================================ @@ -453,8 +310,6 @@ pub fn add_to_module(m: &Bound<'_, pyo3::types::PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; - m.add_class::()?; - m.add_class::()?; Ok(()) } diff --git a/crates/pulsing-rpymod/Cargo.toml b/crates/pulsing-rpymod/Cargo.toml index e9443f55d..65100f705 100644 --- a/crates/pulsing-rpymod/Cargo.toml +++ b/crates/pulsing-rpymod/Cargo.toml @@ -34,3 +34,9 @@ rustpython-vm = { version = "0.5", default-features = false, features = [ ] } serde = { workspace = true } tokio = { workspace = true } + +# RustPython 0.5 assumes POSIX_SPAWN_SETSID is c_int. Newer libc releases +# changed it to c_short; upstream fixed the conversion after 0.5 +# (RustPython/RustPython#8343). Keep this constraint until the next release. +[target.'cfg(unix)'.dependencies] +libc = "=0.2.183" diff --git a/crates/pulsing-workspace/src/init.rs b/crates/pulsing-workspace/src/init.rs index d30e198ec..7b91763d1 100644 --- a/crates/pulsing-workspace/src/init.rs +++ b/crates/pulsing-workspace/src/init.rs @@ -10,22 +10,19 @@ use crate::layout::{cluster_id_for, WorkspaceLayout, WorkspaceManifest}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Template { Minimal, - Agent, } impl Template { pub fn parse(s: &str) -> Result { match s.to_lowercase().as_str() { "minimal" => Ok(Self::Minimal), - "agent" => Ok(Self::Agent), - _ => bail!("unknown template {s:?} (expected minimal or agent)"), + _ => bail!("unknown template {s:?} (expected minimal)"), } } fn as_str(self) -> &'static str { match self { Self::Minimal => "minimal", - Self::Agent => "agent", } } } @@ -35,7 +32,7 @@ pub struct InitOptions { pub template: Template, pub name: Option, pub force: bool, - /// Natural-language goal; stored in workspace.json and used for LLM-guided bootstrap. + /// Optional descriptive note retained in the workspace manifest. pub guide: Option, } @@ -88,7 +85,6 @@ pub fn init_workspace(root: &Path, opts: InitOptions) -> Result { let cluster = match opts.template { Template::Minimal => minimal_cluster_json(&cluster_id, &name), - Template::Agent => agent_cluster_json(&cluster_id, &name), }; fs::write( layout.cluster_file(), @@ -129,36 +125,6 @@ fn minimal_cluster_json(cluster_id: &str, name: &str) -> serde_json::Value { json!({ "cluster_id": cluster_id, "name": name, - "provider": "anthropic", - "model": null, - "auto_approve": false, - "sandbox": "off", - "default_agents": [], - "shared_tool_worker": false, - "puzzles": {} - }) -} - -fn agent_cluster_json(cluster_id: &str, name: &str) -> serde_json::Value { - json!({ - "cluster_id": cluster_id, - "name": name, - "provider": "anthropic", - "model": null, - "auto_approve": false, - "sandbox": "off", - "default_agents": ["guide"], - "shared_tool_worker": false, - "puzzles": { - "unit-tests": { - "title": "Unit test suite", - "kind": "test", - "path": "tests", - "blurb": "Run pytest; keep green.", - "status": "open", - "assign_to": "" - } - } }) } @@ -225,11 +191,11 @@ fn write_scripts_readme(layout: &WorkspaceLayout) -> Result<()> { const WORKFLOWS_README: &str = "# Pulsing workflows\n\n\ Code-as-workflow: plain Python, no graph DSL.\n\n\ ```bash\n\ -pulsing run # immersive session (default: example.py)\n\ +pulsing run # run example.py once\n\ pulsing run my_workflow.py # explicit script\n\ ```\n\n\ -After success you stay in the CLI (`›` prompt). Type `exit` to return to the shell.\n\ -On failure you return to the shell — then `pulsing rollback` or safe-mode fix.\n"; +Each workflow runs once and returns to the shell.\n\ +Use `pulsing rollback` to restore a checkpoint.\n"; const WORKFLOW_EXAMPLE: &str = r#"""Example workflow — extension mode. diff --git a/docs/design/agent-craft-migration.md b/docs/design/agent-craft-migration.md deleted file mode 100644 index 84c574bd5..000000000 --- a/docs/design/agent-craft-migration.md +++ /dev/null @@ -1,609 +0,0 @@ -# pulsing.craft → pulsing.agent 官方迁移计划 - -> **状态更新(2026-07-26)**:本文保留为已执行迁移的历史与兼容性清单,不再定义最终产品边界。最终边界以 [`Forge 核心架构`](../src/design/forge/core-architecture.zh.md) 为准:Rust Forge 拥有 Session、Agent loop、Event 与 Evolution 控制面;`pulsing.agent` 收敛为兼容 API、App Protocol 或参考应用,而不是另一套执行引擎。 -> -> **目标**:将 `pulsing.craft` 重构为 `pulsing.agent`(统一 Agent SDK),`pulsing.forge` 吸收 Host 集成层,`pulsing.cli` 吸收工作区 CLI;Craft 品牌与 `pcraft` 命令进入弃用期。 -> -> **给实现 AI 的指令**:严格按本计划分阶段执行。每阶段独立可验收;未列出的细节参考 [`craft-agent-refactor.md`](./craft-agent-refactor.md)、[`craft-npc-refactor.md`](./craft-npc-refactor.md)、[`docs/src/design/forge/craft-architecture.zh.md`](../src/design/forge/craft-architecture.zh.md)。不修改 `crates/pulsing-actor/` 核心语义,Rust Forge 改动限于 Host 集成所需接口。 - ---- - -## 1. 背景与目标 - -### 1.1 为什么要去掉 Craft 品牌 - -| 问题 | 现状 | 迁移后 | -|------|------|--------| -| **命名误导** | `pulsing.craft` 暗示「游戏/手工」产品,但核心已是通用多 Agent SDK | `pulsing.agent` 直接表达定位 | -| **职责重叠** | Craft 的 `agent/forge_*`、`runtime/split_tools` 与 `pulsing.forge` 重复实现 Host 集成 | Forge 管执行,Agent 管编排 | -| **CLI 碎片化** | `pcraft`、`pulsing craft`、`python -m pulsing.craft` 三套入口 | 统一 `pulsing agent` | -| **Gossip 前缀混乱** | `craft/ws//…` 与 Forge `naming.py` 的 `DEFAULT_WORKSPACE_PREFIX = "craft/ws"` 绑定 Craft 品牌 | 统一 `agent/ws//…` | -| **包名冲突** | 轻量 `pulsing.agent`(`@agent` 装饰器、`runtime()`)与即将成为主 SDK 的 Agent 层同名 | 轻量工具箱迁至 `pulsing.agentkit` | - -### 1.2 迁移目标 - -1. **Pulsing core 保持薄** — 仅分布式 Actor 运行时(`pulsing.core`、`crates/pulsing-actor`)。 -2. **`pulsing.forge` = 工具执行层** — 吸收 Craft 的 Host 集成:工具路由、`ForgeSession`、事件 `tell`、审批桥接。 -3. **`pulsing.agent` = 统一 Agent SDK** — 吸收 Craft 的 `agent/`、`runtime/`(LLM turn loop)、`cluster/`、`workspace/`(配置与发现)。 -4. **`pulsing.cli` 增加 `agent` 子命令** — 吸收 `craft/commands/` 与 `craft/cli.py`。 -5. **`examples/craft/` = 游戏隐喻层** — NPC class、puzzle/quest、demo LLM、`Summon`/`QuestReport` 等产品向工具。 -6. **弃用 `pulsing.craft`、`pcraft`、`pulsing craft`** — 保留 shim 与 deprecation warning,两个 minor 版本后删除。 - -### 1.3 不在本次范围 - -- HubActor 对等 Agent 重构(见 [`craft-agent-refactor.md`](./craft-agent-refactor.md),可与 Phase 2 并行)。 -- Forge Rust handler 新增(已有 `pulsing-forge` crate,仅搬 Python Host 胶水)。 -- `.pulsing/` 工作区目录结构变更(`cluster.json` 格式保持兼容,仅更新文档中的命令示例)。 - ---- - -## 2. 目标架构 - -### 2.1 三层分工 - -```mermaid -flowchart TB - subgraph CLI["pulsing.cli"] - AgentCmd["pulsing agent init|wake|watch|…"] - ForgeCmd["pulsing forge …"] - CoreCmd["pulsing actor|inspect|…"] - end - - subgraph AgentSDK["pulsing.agent — 统一 Agent SDK"] - AgentActor["Agent (@pul.remote)"] - LlmLoop["LlmChat · turn loop"] - Cluster["cluster/ · discovery · resolve"] - Workspace["workspace/ · config · session"] - Perms["permissions · activity · log"] - end - - subgraph Forge["pulsing.forge — 工具执行"] - Host["host/ · tool_host · forge_session · events"] - Worker["worker · supervisor · isolated spawn"] - RustRT["RustForgeAdapter → pulsing-forge"] - end - - subgraph Core["pulsing.core — Actor 运行时"] - Remote["@remote · spawn · resolve"] - Gossip["gossip · mailbox · isolated spawn"] - end - - subgraph Examples["examples/craft — 游戏隐喻(可选)"] - NpcClass["npc/ · loader · NpcClass"] - Quest["quest · puzzle · world_view"] - DemoLLM["demo_llm · demo 命令"] - end - - CLI --> AgentSDK - CLI --> Examples - AgentSDK --> Forge - AgentSDK --> Core - Forge --> Core - Examples --> AgentSDK -``` - -### 2.2 职责边界 - -| 层 | 包 / 路径 | 职责 | 不应包含 | -|----|-----------|------|----------| -| **Pulsing** | `pulsing.core`, `crates/pulsing-actor` | 分布式 Actor、mailbox、gossip、隔离 spawn | LLM、工具 handler、工作区 CLI | -| **Forge** | `pulsing.forge`, `crates/pulsing-forge` | 沙箱内工具执行、ToolSession、事件投递、MCP hub | LLM turn loop、NPC 隐喻、puzzle | -| **Agent** | `pulsing.agent` | Agent actor、LLM 编排、集群发现、工作区配置、权限 | 重复实现 Read/Bash/patch | -| **CLI** | `pulsing.cli` | 顶层命令分发、`pulsing agent` 子命令 | 业务逻辑(委托给 agent/examples) | -| **Examples** | `examples/craft/` | NPC class、quest、demo、TUI 文案 | 核心 SDK API | - -### 2.3 目标目录结构(迁移完成后) - -``` -python/pulsing/ -├── core/ # 不变 -├── forge/ -│ ├── host/ # ★ 新增:自 craft/agent/forge_*.py 迁入 -│ │ ├── events.py -│ │ ├── runtime.py -│ │ ├── session.py -│ │ └── tool_host.py -│ ├── naming.py # DEFAULT_WORKSPACE_PREFIX → "agent/ws" -│ └── … # 现有 worker/backend/session 等 -├── agent/ # ★ 扩展为统一 SDK(吸收 craft) -│ ├── agent.py # Agent actor(原 CraftAgent) -│ ├── actor.py # 基类 CraftActor → AgentActor -│ ├── bootstrap.py -│ ├── config.py # AgentConfig(原 NpcConfig) -│ ├── session.py -│ ├── activity.py -│ ├── log.py -│ ├── permissions.py # 自 craft/runtime/permissions.py -│ ├── llm/ # 自 craft/runtime/llm_*.py -│ │ ├── chat.py -│ │ ├── client.py -│ │ └── blocks.py -│ ├── cluster/ -│ │ ├── constants.py # agent/ws/ 前缀 -│ │ ├── discovery.py -│ │ ├── resolve.py -│ │ └── activity.py -│ ├── workspace/ -│ │ ├── config.py -│ │ ├── root.py -│ │ ├── session.py -│ │ └── tool_pool.py -│ └── tools/ # Agent 层本地工具(FetchUrl 等) -│ └── fetch_url.py -├── agentkit/ # ★ 原轻量 pulsing.agent 迁至此处 -│ ├── __init__.py # @agent 装饰器、runtime()、llm() -│ └── … -├── cli/ -│ ├── __main__.py # 增加 agent 子命令路由 -│ └── agent/ # ★ 自 craft/commands/ 迁入 -│ ├── __init__.py -│ ├── world.py -│ ├── watch.py -│ ├── dashboard.py -│ ├── npc.py -│ ├── puzzle.py -│ ├── demo.py -│ └── agent_cmd.py -└── craft/ # ⚠ 弃用 shim(Phase 4 删除) - └── … # re-export + DeprecationWarning - -examples/craft/ # ★ 游戏隐喻 -├── npc/ -│ ├── loader.py -│ └── classes/ # 默认 NPC class 定义 -├── quest.py -├── tools/ -│ ├── summon.py -│ └── quest_report.py -├── demo_llm.py -└── README.md -``` - ---- - -## 3. 命名映射 - -### 3.1 类型与符号 - -| 旧 (craft) | 新 (agent) | 说明 | -|------------|------------|------| -| `CraftAgent` | `Agent` | `@pul.remote` 主 actor,`python/pulsing/agent/agent.py` | -| `NpcAgent` | `Agent` | 别名删除,统一 `Agent` | -| `CraftActor` | `AgentActor` | 基类,`python/pulsing/agent/actor.py` | -| `NpcConfig` | `AgentConfig` | `python/pulsing/agent/config.py` | -| `setup_agent(agent, NpcConfig)` | `setup_agent(agent, AgentConfig)` | `bootstrap.py` | -| `spawn_npc(...)` | `spawn_agent(...)` | `helpers.py` → `pulsing.agent.spawn` | -| `resolve_craft_agent` | `resolve_agent` | `cluster/resolve.py` | -| `build_tools_for_agent` | `pulsing.forge.host.build_tools` | 工具表构建下沉 Forge Host | -| `init_forge_host` | `pulsing.forge.host.init_runtime` | Host 初始化 | -| `build_craft_forge_session` | `pulsing.forge.host.build_session` | Session 构建 | -| `make_host_emit` | `pulsing.forge.host.make_emit` | 事件 emit | -| `NpcClass` | 保留于 `examples/craft/npc/` | 仅游戏隐喻层 | -| `SummonTool` | `examples/craft/tools/summon.py` | 产品向工具 | -| `QuestReportTool` | `examples/craft/tools/quest_report.py` | 产品向工具 | - -### 3.2 Gossip 与路径前缀 - -| 旧 | 新 | 定义位置 | -|----|-----|----------| -| `craft/ws//` | `agent/ws//` | `pulsing/agent/cluster/constants.py` | -| `craft/ws//_tools` | `agent/ws//_tools` | `pulsing/forge/naming.py` | -| `craft/ws//_mcp_hub` | `agent/ws//_mcp_hub` | `pulsing/forge/naming.py` | -| `/events` | 不变 | `forge_event_inbox_name()` | -| metadata `craft.kind` | `agent.kind` | Agent.metadata() | -| metadata `craft.npc_class` | `agent.npc_class`(可选,examples 层) | 仅 demo/NPC 场景 | - -**双前缀兼容期**(Phase 1–3):`resolve()` 依次尝试 `agent/ws/…` 与 `craft/ws/…`;新 spawn 仅注册 `agent/ws/…`。 - -### 3.3 包与入口 - -| 旧 | 新 | -|----|-----| -| `from pulsing.craft.agent import CraftAgent` | `from pulsing.agent import Agent` | -| `from pulsing.craft.npc.config import NpcConfig` | `from pulsing.agent import AgentConfig` | -| `from pulsing.craft.workspace.config import WorkspaceConfig` | `from pulsing.agent.workspace import WorkspaceConfig` | -| `from pulsing.craft.cluster.constants import full_agent_name` | `from pulsing.agent.cluster import full_agent_name` | -| `pcraft` | `pulsing agent` | -| `pulsing craft` | `pulsing agent`(shim 转发) | -| `python -m pulsing.craft` | `python -m pulsing.cli agent` 或 `pulsing agent` | -| `pip install pulsing[craft]` | `pip install pulsing[agent]`(`[craft]` 保留为 alias) | -| 轻量 `from pulsing.agent import agent, runtime, llm` | `from pulsing.agentkit import agent, runtime, llm` | - -### 3.4 文件路径对照(核心搬迁) - -| 源 (`python/pulsing/craft/`) | 目标 | -|------------------------------|------| -| `agent/npc.py` | `agent/agent.py` | -| `agent/actor.py` | `agent/actor.py` | -| `agent/bootstrap.py` | `agent/bootstrap.py` | -| `agent/session.py` | `agent/session.py` | -| `agent/activity.py` | `agent/activity.py` | -| `agent/log.py` | `agent/log.py` | -| `agent/tool_host.py` | `forge/host/tool_host.py` | -| `agent/forge_runtime.py` | `forge/host/runtime.py` | -| `agent/forge_session.py` | `forge/host/session.py` | -| `agent/forge_events.py` | `forge/host/events.py` | -| `agent/summon_tool.py` | `examples/craft/tools/summon.py` | -| `npc/config.py` | `agent/config.py` | -| `npc/loader.py` | `examples/craft/npc/loader.py` | -| `runtime/llm_chat.py` | `agent/llm/chat.py` | -| `runtime/llm_client.py` | `agent/llm/client.py` | -| `runtime/llm_blocks.py` | `agent/llm/blocks.py` | -| `runtime/permissions.py` | `agent/permissions.py` | -| `runtime/split_tools.py` | `forge/host/tools.py`(+ examples 注册 hook) | -| `runtime/cluster_tools.py` | `agent/cluster/tools.py` | -| `runtime/quest_tools.py` | `examples/craft/tools/quest_report.py` | -| `runtime/demo_llm.py` | `examples/craft/demo_llm.py` | -| `runtime/constants.py` | 拆分 → `agent/constants.py` + `forge/host/constants.py` | -| `runtime/tools_pkg.py` + `tools_impl.py` | `agent/tools/` + `forge/`(FetchUrl → agent,FS → forge) | -| `cluster/constants.py` | `agent/cluster/constants.py` | -| `cluster/discovery.py` | `agent/cluster/discovery.py` | -| `cluster/resolve.py` | `agent/cluster/resolve.py` | -| `cluster/activity.py` | `agent/cluster/activity.py` | -| `workspace/config.py` | `agent/workspace/config.py` | -| `workspace/root.py` | `agent/workspace/root.py` | -| `workspace/session.py` | `agent/workspace/session.py` | -| `workspace/tool_pool.py` | `agent/workspace/tool_pool.py` | -| `workspace/quest.py` | `examples/craft/quest.py` | -| `workspace/world_view.py` | `examples/craft/world_view.py` | -| `commands/*.py` | `cli/agent/*.py` | -| `cli.py` | `cli/agent/parser.py` + `cli/__main__.py` 路由 | -| `helpers.py` | `agent/helpers.py` | -| `paths.py` | `agent/paths.py` | -| `payload/full_tool_worker.py` | `forge/payload/full_tool_worker.py`(或保持 re-export) | - ---- - -## 4. 分阶段迁移计划 - -### Phase 0:准备与命名空间清理 - -**目标**:为 `pulsing.agent` 腾出包名;建立新目录骨架;不破坏现有用户。 - -| 类别 | 文件 / 动作 | -|------|-------------| -| 新建 | `python/pulsing/agentkit/` — 将现有 `python/pulsing/agent/{base,runtime,llm,utils}.py` 原样迁入 | -| 新建 | `python/pulsing/agent/` 子包骨架:`agent.py`、`config.py`、`cluster/`、`workspace/`、`llm/`(空 `__init__.py`) | -| 新建 | `python/pulsing/forge/host/` 骨架 | -| 新建 | `examples/craft/` 目录 | -| 修改 | `python/pulsing/agent/__init__.py` — 改为导出 SDK 符号(暂从 craft re-export) | -| 修改 | `python/pulsing/agentkit/__init__.py` — 保持原 `pulsing.agent` 公开 API | -| 修改 | `README.md`、`README.zh.md`、`docs/src/agent/*.md` — `@agent` / `runtime()` 示例改为 `pulsing.agentkit` | -| 修改 | `pyproject.toml` — 增加 `[project.optional-dependencies] agent = [...]`(与 `craft` 相同依赖) | - -**验收标准** - -- [ ] `from pulsing.agentkit import agent, runtime, llm` 与迁移前 `pulsing.agent` 行为一致 -- [ ] `pytest tests/python/agent/` 通过(改 import 后) -- [ ] `ruff check python/pulsing` 无新增错误 -- [ ] CI 文档构建不 broken link - -**风险** - -| 风险 | 缓解 | -|------|------| -| 外部用户仍 `import pulsing.agent` 轻量 API | `pulsing.agent` 顶层暂 re-export agentkit 符号 + `DeprecationWarning` | -| 文档/示例大量引用旧路径 | 脚本批量替换 + CI grep 门禁 | - ---- - -### Phase 1:Forge Host 集成下沉 - -**目标**:将 Craft 的 Forge 胶水层迁入 `pulsing.forge.host`;`Agent` 通过 Forge 公开 API 初始化 Host,不再依赖 `pulsing.craft.agent.forge_*`。 - -| 类别 | 文件 / 动作 | -|------|-------------| -| 搬迁 | `craft/agent/forge_events.py` → `forge/host/events.py` | -| 搬迁 | `craft/agent/forge_runtime.py` → `forge/host/runtime.py` | -| 搬迁 | `craft/agent/forge_session.py` → `forge/host/session.py` | -| 搬迁 | `craft/agent/tool_host.py` → `forge/host/tool_host.py` | -| 搬迁 | `craft/runtime/split_tools.py` 中 Forge 相关部分 → `forge/host/tools.py` | -| 修改 | `forge/naming.py` — 增加 `AGENT_WORKSPACE_PREFIX = "agent/ws"`,`DEFAULT_WORKSPACE_PREFIX` 暂保留 `craft/ws` | -| 修改 | `forge/p2p_transport.py` — 注释/类型中的 `CraftAgent` → `HostAgent` | -| 修改 | `craft/agent/bootstrap.py` — 改为 `from pulsing.forge.host import init_runtime` | -| 新建 | `tests/python/forge/test_host_integration.py` — 从 `tests/python/craft/test_forge_events.py` 提炼 | - -**验收标准** - -- [ ] `pytest tests/python/craft/test_forge_events.py` 通过(craft 仍可用,内部走 forge.host) -- [ ] `pytest tests/python/test_forge_integrated.py` 通过 -- [ ] `CraftAgent` spawn 后 `_forge_host` 类型为 `ForgeHostLink` 或 `RustForgeAdapter` -- [ ] 无 `pulsing.craft` → `pulsing.forge` 的循环 import - -**风险** - -| 风险 | 缓解 | -|------|------| -| `split_tools` 同时依赖 NPC class 与 Forge 常量 | 拆为 `forge/host/tools.py` + `examples/craft/register_tools.py` 回调 | -| 事件 sink 名称仍用 `craft/ws/…` | Phase 1 不改 gossip 名,仅搬代码;命名在 Phase 2 切换 | - ---- - -### Phase 2:Agent SDK 核心搬迁 - -**目标**:`pulsing.agent` 成为可独立 import 的 SDK;`CraftAgent`/`NpcConfig` 的新实现就位;craft 包 re-export。 - -| 类别 | 文件 / 动作 | -|------|-------------| -| 搬迁 | `craft/agent/{actor,bootstrap,session,activity,log}.py` → `agent/` | -| 搬迁 | `craft/agent/npc.py` → `agent/agent.py`(类名 `CraftAgent` → `Agent`) | -| 搬迁 | `craft/npc/config.py` → `agent/config.py`(`NpcConfig` → `AgentConfig`) | -| 搬迁 | `craft/runtime/{llm_chat,llm_client,llm_blocks,permissions}.py` → `agent/llm/`、`agent/permissions.py` | -| 搬迁 | `craft/cluster/*.py` → `agent/cluster/` | -| 搬迁 | `craft/workspace/{config,root,session,tool_pool}.py` → `agent/workspace/` | -| 搬迁 | `craft/runtime/cluster_tools.py` → `agent/cluster/tools.py` | -| 修改 | `agent/cluster/constants.py` — `WS_AGENT_PREFIX = "agent/ws/"`;提供 `legacy_craft_prefix()` 用于双前缀 resolve | -| 修改 | `forge/naming.py` — `DEFAULT_WORKSPACE_PREFIX = "agent/ws"` | -| 修改 | `craft/agent/npc.py` — 薄 shim:`CraftAgent = Agent` + warning | -| 修改 | `craft/npc/config.py` — `NpcConfig = AgentConfig` + warning | -| 新建 | `agent/__init__.py` 导出:`Agent`, `AgentConfig`, `spawn_agent`, `full_agent_name`, … | - -**验收标准** - -- [ ] `from pulsing.agent import Agent, AgentConfig` 可 spawn 并 `run_turn` / `deliver_message` -- [ ] 新 spawn 的 gossip 名为 `agent/ws//` -- [ ] `resolve("craft/ws/…")` 在兼容期内仍可找到旧 actor -- [ ] `pytest tests/python/craft/test_agent.py` 通过(经 shim 或更新 import) -- [ ] `pytest tests/python/craft/test_cluster.py` 通过 - -**风险** - -| 风险 | 缓解 | -|------|------| -| 集群中混跑 craft 前缀与 agent 前缀 actor | `list_cluster_agents` 合并去重;文档说明需 `wake` 重启 | -| `Agent` 与 `@agent` 装饰器同名混淆 | 装饰器仅在 `agentkit`;文档强调 `Agent` 为 actor 类 | -| LLM 模块 import 链长 | `agent/llm/` 子包延迟 import 重型依赖(anthropic/openai) | - ---- - -### Phase 3:CLI 与游戏隐喻分离 - -**目标**:`pulsing agent` 成为官方 CLI;游戏隐喻迁入 `examples/craft`;`pcraft` / `pulsing craft` 转发。 - -| 类别 | 文件 / 动作 | -|------|-------------| -| 搬迁 | `craft/commands/*.py` → `cli/agent/*.py` | -| 搬迁 | `craft/cli.py` 解析逻辑 → `cli/agent/parser.py` | -| 修改 | `cli/__main__.py` — `sys.argv[1] == "agent"` 路由至 `cli/agent` | -| 修改 | `cli/help_text.py` — 顶层帮助增加 `agent`,`craft` 标为 deprecated | -| 搬迁 | `craft/npc/loader.py`、`workspace/quest.py`、`workspace/world_view.py`、`runtime/demo_llm.py`、`agent/summon_tool.py`、`runtime/quest_tools.py` → `examples/craft/` | -| 修改 | `cli/agent/demo.py`、`npc.py`、`puzzle.py` — import `examples.craft` | -| 修改 | `pyproject.toml` — `[project.scripts]` 保留 `pcraft` 指向 shim;新增文档推荐 `pulsing agent` | -| 修改 | `examples/python/craft_demo.sh` — 命令改为 `pulsing agent demo` | -| 新建 | `examples/craft/README.md` | - -**验收标准** - -- [ ] `pulsing agent init` / `wake` / `watch` / `npc say` / `puzzle list` 与当前 `pcraft` 行为等价 -- [ ] `pcraft` 运行打印一次 `DeprecationWarning`,功能正常 -- [ ] `pulsing craft …` 转发至 `pulsing agent …` 且打印 warning -- [ ] `pulsing agent demo` 在无 API key 时可离线运行(demo_llm) -- [ ] `pytest tests/python/craft/test_cli.py` 通过(双入口各测一遍) - -**风险** - -| 风险 | 缓解 | -|------|------| -| `examples/craft` 不在 wheel 内 | `pyproject.toml` 用 `package-data` 或保持源码树路径;CLI 用 `importlib.resources` 加载默认 NPC | -| dashboard 脚本硬编码 `pcraft` | `cli/agent/dashboard.py` 统一 `agent_argv()` 生成命令 | -| 用户 shell 别名 `alias pcraft=…` | CHANGELOG 说明;shim 保留 ≥2 minor | - ---- - -### Phase 4:删除 craft 包与旧前缀 - -**目标**:移除 `pulsing.craft`;移除 `craft/ws` 双前缀;清理 shim。 - -| 类别 | 文件 / 动作 | -|------|-------------| -| 删除 | `python/pulsing/craft/` 整个包(shim 除外可先保留一版) | -| 删除 | `pyproject.toml` 中 `pcraft` script、`[craft]` optional-dep(保留 `[agent]`) | -| 删除 | `cli/__main__.py` 中 `craft` 子命令转发 | -| 修改 | `agent/cluster/constants.py` — 移除 `craft/ws` 兼容 resolve | -| 修改 | `forge/naming.py` — 移除 `craft/ws` 常量 | -| 修改 | 全库 grep `pulsing.craft`、`pcraft`、`craft/ws` 清零 | -| 重命名 | `tests/python/craft/` → `tests/python/agent/` | -| 更新 | `docs/design/*.md`、`docs/src/design/pulsing-cli.md`、`python/pulsing/forge/README.md` | - -**验收标准** - -- [ ] `python -c "import pulsing.craft"` 失败或仅显示 removed 提示 -- [ ] `rg 'pulsing\.craft|pcraft|craft/ws' python/ tests/` 无命中(除 CHANGELOG / 本迁移文档) -- [ ] 全量 `pytest tests/python/` 通过 -- [ ] `maturin develop` + `pulsing agent demo` 端到端 smoke 通过 - -**风险** - -| 风险 | 缓解 | -|------|------| -| 用户集群仍有 `craft/ws` 注册 actor | Phase 3 CHANGELOG 提前公告;提供 `pulsing agent migrate-names` 一次性工具(可选) | -| 下游 fork 依赖 `pulsing.craft` | Phase 2 起 shim 已 warning;Phase 4 主版本号 bump | - ---- - -## 5. 兼容策略 - -### 5.1 Shim 与 re-export - -**Phase 2 起**,`python/pulsing/craft/__init__.py`: - -```python -import warnings - -warnings.warn( - "pulsing.craft is deprecated; use pulsing.agent", - DeprecationWarning, - stacklevel=2, -) - -from pulsing.agent import Agent as CraftAgent -from pulsing.agent import AgentConfig as NpcConfig -from pulsing.agent import spawn_agent as spawn_npc - -__all__ = ["CraftAgent", "NpcAgent", "NpcConfig", "spawn_npc"] -``` - -**CLI shim**(`python/pulsing/craft/cli.py` 保留至 Phase 4): - -```python -def main(...): - warnings.warn("pcraft is deprecated; use `pulsing agent`", DeprecationWarning) - from pulsing.cli.agent import main as agent_main - agent_main(argv, prog="pcraft") -``` - -### 5.2 Gossip 双前缀(Phase 2–3) - -```python -# pulsing/agent/cluster/resolve.py -_LEGACY_PREFIX = "craft/ws/" -_CURRENT_PREFIX = "agent/ws/" - -async def resolve_agent(name: str, *, workspace_id: str, cls=Agent): - for prefix in (_CURRENT_PREFIX, _LEGACY_PREFIX): - full = f"{prefix}{workspace_id}/{name}" - try: - return await pul.resolve(full, cls=cls) - except Exception: - continue - raise LookupError(name) -``` - -### 5.3 可选依赖别名 - -```toml -[project.optional-dependencies] -agent = ["anthropic>=0.40.0", "openai>=1.0.0"] -craft = ["pulsing[agent]"] # deprecated alias,Phase 4 删除 -``` - -### 5.4 弃用时间线 - -| 版本 | 行为 | -|------|------| -| v0.2.x | Phase 0–2;`pulsing.craft` + `pcraft` 可用,import 时 warning | -| v0.3.x | Phase 3;CLI warning;文档仅写 `pulsing agent` | -| v0.4.0 | Phase 4;删除 `pulsing.craft`、`pcraft`、`craft/ws` | - ---- - -## 6. CLI 命令映射表 - -| 旧命令 | 新命令 | 实现文件(新) | 备注 | -|--------|--------|----------------|------| -| `pcraft` | `pulsing agent` | `cli/agent/parser.py` | 默认子命令 `look` | -| `pulsing craft` | `pulsing agent` | `cli/__main__.py` | shim 转发 | -| `pcraft init` | `pulsing agent init` | `cli/agent/world.py` | 创建 `.pulsing/` | -| `pcraft look` | `pulsing agent look` | `cli/agent/world.py` | 默认命令 | -| `pcraft wake` | `pulsing agent wake` | `cli/agent/world.py` | 启动节点 + spawn agents | -| `pcraft sleep` | `pulsing agent sleep` | `cli/agent/world.py` | 未实现保持 stub | -| `pcraft watch` | `pulsing agent watch` | `cli/agent/watch.py` | | -| `pcraft dashboard` | `pulsing agent dashboard` | `cli/agent/dashboard.py` | Zellij/tmux | -| `pcraft demo` | `pulsing agent demo` | `cli/agent/demo.py` | 依赖 `examples/craft/demo_llm.py` | -| `pcraft agent logs ` | `pulsing agent logs ` | `cli/agent/agent_cmd.py` | 子命令层级拉平 | -| `pcraft npc who` | `pulsing agent npc who` | `cli/agent/npc.py` | 游戏隐喻保留 `npc` 子命令 | -| `pcraft npc summon ` | `pulsing agent npc summon ` | `cli/agent/npc.py` | | -| `pcraft npc say …` | `pulsing agent npc say …` | `cli/agent/npc.py` | | -| `pcraft puzzle list` | `pulsing agent puzzle list` | `cli/agent/puzzle.py` | | -| `pcraft puzzle show ` | `pulsing agent puzzle show ` | `cli/agent/puzzle.py` | | -| `pcraft puzzle mark ` | `pulsing agent puzzle mark ` | `cli/agent/puzzle.py` | | -| `python -m pulsing.craft` | `pulsing agent` | — | 模块入口删除 | - -**不变命令**(与 craft 无关): - -- `pulsing forge …` — Forge REPL / 工具调试 -- `pulsing actor …` — 通用 actor 启动 -- `pulsing inspect …` — 集群检视 - ---- - -## 7. 测试迁移策略 - -### 7.1 测试目录重组 - -| 当前 | 迁移后 | 阶段 | -|------|--------|------| -| `tests/python/craft/test_agent.py` | `tests/python/agent/test_agent.py` | Phase 2 复制 + Phase 4 删旧 | -| `tests/python/craft/test_cluster.py` | `tests/python/agent/test_cluster.py` | 同上 | -| `tests/python/craft/test_workspace.py` | `tests/python/agent/test_workspace.py` | 同上 | -| `tests/python/craft/test_forge_events.py` | `tests/python/forge/test_host_events.py` | Phase 1 | -| `tests/python/craft/test_cli.py` | `tests/python/cli/test_agent_cli.py` | Phase 3 | -| `tests/python/craft/test_demo.py` | `tests/python/examples/test_craft_demo.py` | Phase 3 | -| `tests/python/craft/test_npc.py` | `tests/python/examples/test_craft_npc.py` | Phase 3 | -| `tests/python/craft/test_*`(watch/dashboard/world/…) | `tests/python/cli/test_agent_*.py` 或 `tests/python/agent/` | 按职责拆分 | - -**保留在 craft 目录的过渡测试**(Phase 2–3):`test_craft_shim.py` — 验证 `from pulsing.craft import CraftAgent` 触发 warning 且行为一致。 - -### 7.2 测试分层 - -``` -tests/python/ -├── agent/ # SDK 单元 + 集成(spawn、resolve、turn、cluster) -├── forge/ # Host 集成、事件、工具路由(已有 + test_host_*) -├── cli/ # argparse、命令 dispatch(mock actor system) -└── examples/ # demo LLM、NPC class、quest(可选 metaphors) -``` - -### 7.3 门禁命令 - -每 Phase 合并前必须绿色: - -```bash -# 单元 + 集成 -pytest tests/python/agent/ tests/python/forge/ tests/python/cli/ -q - -# 弃用 warning 回归 -pytest tests/python/craft/test_craft_shim.py -W error::DeprecationWarning - -# 全量(Phase 4) -pytest tests/python/ -q - -# 静态检查 -ruff check python/pulsing tests/python -``` - -### 7.4 关键测试用例(不可删) - -| 用例 | 文件 | 验证点 | -|------|------|--------| -| Agent spawn + ping | `test_agent.py` | `Agent.spawn`、metadata、`full_agent_name` | -| 集群 discover | `test_cluster.py` | `list_cluster_agents`、`agent/ws/` 前缀 | -| Forge 事件 tell | `test_host_events.py` | `emit_forge_event` → `on_forge_event` | -| Workspace init/load | `test_workspace.py` | `.pulsing/cluster.json` | -| CLI 解析 | `test_agent_cli.py` | 子命令路由、默认 `look` | -| Demo 离线 | `test_craft_demo.py` | 无 API key 时 `demo_llm` 脚本 | - -### 7.5 Import 批量替换(Phase 2 参考) - -```bash -# 仅供参考,执行前人工 review -rg -l 'pulsing\.craft\.agent' tests/python python/pulsing \ - | xargs sed -i '' 's/pulsing\.craft\.agent/pulsing.agent/g' -rg -l 'NpcConfig' tests/python \ - | xargs sed -i '' 's/NpcConfig/AgentConfig/g' -``` - ---- - -## 8. 相关文档 - -| 文档 | 关系 | -|------|------| -| [`craft-agent-refactor.md`](./craft-agent-refactor.md) | HubActor → 对等 Agent;可与 Phase 2 并行 | -| [`craft-npc-refactor.md`](./craft-npc-refactor.md) | schedule_self 自主 NPC;examples 层参考 | -| [`docs/src/design/forge/craft-architecture.zh.md`](../src/design/forge/craft-architecture.zh.md) | Forge × Host 分层;迁移后改标题为 agent-architecture | -| [`docs/src/design/pulsing-cli.md`](../src/design/pulsing-cli.md) | 顶层 CLI 设计;补充 `agent` 子命令 | -| [`python/pulsing/forge/README.md`](../../python/pulsing/forge/README.md) | Forge 使用说明;更新 naming 示例 | - ---- - -## 9. 总体验收清单(迁移完成) - -- [ ] `pulsing agent init && pulsing agent wake --agents guide` 端到端可用 -- [ ] `from pulsing.agent import Agent, AgentConfig, spawn_agent` 为官方公开 API -- [ ] `from pulsing.forge.host import init_runtime, build_tools` 为 Host 集成入口 -- [ ] Gossip 新 actor 仅使用 `agent/ws//` -- [ ] `examples/craft/` 可独立阅读,演示 NPC/puzzle 隐喻 -- [ ] `pulsing.craft`、`pcraft`、`craft/ws` 已删除或 hard-deprecate -- [ ] `pulsing.agentkit` 承载原轻量 `@agent` / `runtime()` / `llm()` 工具箱 -- [ ] 全量 pytest + ruff 绿色 diff --git a/docs/design/agent-workspace-dock-panels.md b/docs/design/agent-workspace-dock-panels.md deleted file mode 100644 index 0caff078f..000000000 --- a/docs/design/agent-workspace-dock-panels.md +++ /dev/null @@ -1,376 +0,0 @@ -# Agent Workspace — Dock 骨架与面板梳理 - -> 配套:[agent-workspace-gui.md](./agent-workspace-gui.md) -> **布局概念**:Zed 式 Left / Center / Right / Bottom 分区。 -> **当前实现**:`eframe` / `egui`(`SidePanel`、`CentralPanel`、`TopBottomPanel`),不再使用 GPUI / `gpui-component`。 - ---- - -## 1. 四区 anatomy(概念 → egui 映射) - -原 GPUI `DockArea` 五挂载点,在 egui 中对应: - -``` - ┌─────────────────────────────────────┐ - │ TitleBar(窗口级,非 Dock 内) │ -├──────────┬────────┴─────────────────────────┬──────────┤ -│ │ │ │ -│ LEFT │ CENTER │ RIGHT │ -│ dock │ (主工作区 TabPanel) │ dock │ -│ │ │ │ -│ 260px │ │ 240px │ -│ 可折叠 │ │ 可折叠 │ -│ │ │ │ -├──────────┴──────────────────────────────────┴──────────┤ -│ BOTTOM dock(Runtime,默认 28px 条,可拉高到 200px) │ -└────────────────────────────────────────────────────────┘ -``` - -| 区域 | egui API | 默认 | -|------|----------|------| -| Left | `egui::SidePanel::left` | 开,220px;内嵌 Files / History / Workflows Tab | -| Center | `egui::CentralPanel` | Chat + 文件预览 Tab | -| Right | `egui::SidePanel::right` | 开,220px;Sessions + Cluster | -| Bottom | `egui::TopBottomPanel::bottom` | 状态条(Ready / counts) | -| TitleBar | 窗口原生标题 | — | - -Left 内 Tab 用 `ui.horizontal` + `selectable_label` 实现,等价于原 `DockItem::Tabs`。 - ---- - -## 2. 默认布局(已实现) - -```text -WorkspaceApp (eframe) -├── SidePanel::left → app/left.rs (Explorer | Revisions | Workflows) -├── CentralPanel → app/mod.rs (Chat tab + 文件预览 tab) -├── SidePanel::right → app/right.rs (Sessions | Cluster 占位) -└── TopBottomPanel → 状态栏 (files / revs / workflows counts) -``` -│ └── (预留) Panel: Search 或 Outline size: 45% ← Phase 2+ -└── TopBottomPanel → 状态栏 (files / revs / workflows counts) -``` - -Center 内 Chat / 文件预览 Tab 由 `CenterTab` 枚举管理;后续可扩展 Diff、WorkflowLog。 - -**Mermaid(逻辑关系)** - -```mermaid -flowchart TB - subgraph Left["Left Dock"] - LT[Tabs] - E[Explorer] - R[Revisions] - W[Workflows] - LT --> E & R & W - end - - subgraph Center["Center"] - CT[Tabs] - CH[Chat] - FP[FilePreview] - DF[Diff] - WL[WorkflowLog] - CT --> CH & FP & DF & WL - end - - subgraph Right["Right Dock"] - AP[AgentsPanel] - end - - subgraph Bottom["Bottom Dock"] - BT[Tabs] - RS[RuntimeSummary] - CL[Cluster] - TT[ToolTrace] - WO[WorkflowOutput] - BT --> RS & CL & TT & WO - end - - E -->|open file| FP - R -->|compare| DF - W -->|run| WL - AP -->|switch session| CH -``` - ---- - -## 3. 面板分类(两类) - -### A. 侧栏面板(`Panel` trait,固定在 Left / Right / Bottom) - -长期停靠、有 `panel_name()`、可折叠/拖拽(Dock 管理)。 - -| `panel_name` | 中文 | 位置 | 职责 | -|--------------|------|------|------| -| `explorer` | 资源管理器 | Left Tab | 工作区文件树 | -| `revisions` | 版本快照 | Left Tab | checkpoint 时间线 | -| `workflows` | 工作流 | Left Tab | `.pulsing/workflows/*.py` | -| `agents` | Agent 会话 | Right | duo-agent / 多会话 | -| `runtime` | 运行时 | Bottom Tab | 集群与进程状态 | - -### B. 中央文档(Center `Tabs` 里的条目,动态开闭) - -类似 Zed 的 editor tab,由用户操作打开,可关闭。 - -| Tab 类型 | 标识 | 打开方式 | -|----------|------|----------| -| `ChatTab` | `chat:{session_id}` | 默认 / Agents 侧栏切换 | -| `FileTab` | `file:{rel_path}` | Explorer 单击 | -| `DiffTab` | `diff:{rev_id}` | Revisions 双击 | -| `WorkflowLogTab` | `wf-log:{run_id}` | Workflows 点 Run | - ---- - -## 4. 各面板规格 - -### 4.1 Explorer(`explorer`) - -| 项 | 内容 | -|----|------| -| **职责** | 展示 `WorkspaceLayout.root` 文件树;脏文件标记 | -| **组件** | `Tree` / `VirtualList` | -| **数据** | `FileIndex::scan(layout)` → `Vec` | -| **事件出** | `OpenFile(path)` → Center 开 `FileTab` | -| **事件入** | `RevisionCreated` → 刷新 dirty 标记 | -| **不做什么** | 不编辑文件、不跑 agent | - -```rust -pub struct FileNode { - pub rel_path: PathBuf, - pub is_dir: bool, - pub dirty: bool, // 相对 HEAD checkpoint -} -``` - ---- - -### 4.2 Revisions(`revisions`) - -| 项 | 内容 | -|----|------| -| **职责** | workspace journal 时间线;checkpoint / rollback | -| **组件** | `VirtualList` + `Button` + `Dialog` | -| **数据** | `list_revisions(&layout)`, `current_head(&layout)` | -| **事件出** | `OpenDiff(rev_id)`, `RequestRollback(rev_id)` | -| **事件入** | `RevisionCreated`, `HeadChanged` | - -```rust -pub struct RevisionRow { - pub id: String, - pub message: String, - pub created_at: String, - pub file_count: usize, - pub is_head: bool, -} -``` - ---- - -### 4.3 Workflows(`workflows`) - -| 项 | 内容 | -|----|------| -| **职责** | 列出并运行 workflow 脚本 | -| **组件** | `List` + Run/Stop `Button` | -| **数据** | `list_workflow_scripts()` → `Vec` | -| **事件出** | `RunWorkflow(script)`, `StopWorkflow(run_id)` → Bottom `WorkflowOutput` | -| **事件入** | `WorkflowStarted/Finished/Output` | - -```rust -pub enum WorkflowState { Idle, Running { run_id, pid }, Failed } -pub struct WorkflowEntry { - pub path: PathBuf, - pub name: String, - pub state: WorkflowState, -} -``` - ---- - -### 4.4 Agents(`agents`)— Right dock - -| 项 | 内容 | -|----|------| -| **职责** | 多 Agent 会话管理(Local + Remote craft) | -| **组件** | `VirtualList` + `Button`(New / Spawn) | -| **数据** | `SessionStore::list()` + `list_cluster_agents()` (Phase 3) | -| **事件出** | `FocusSession(id)` → Center 切 `ChatTab` | -| **事件入** | `AgentEvent`, `CraftAgentStatus` | - -```rust -pub enum SessionKind { - LocalForge, - RemoteNamed { path: String }, // craft/ws/{cluster_id}/coder -} -pub struct AgentSessionMeta { - pub id: SessionId, - pub title: String, - pub kind: SessionKind, - pub busy: bool, -} -``` - -**与 Center Chat 的关系**:每个 session 对应一个 `ChatTab`;Agents 面板是会话**目录**,Chat 是**内容**。 - ---- - -### 4.5 Center Tabs(主工作区) - -#### ChatTab(核心,迁移自现有 `app.rs`) - -| 项 | 内容 | -|----|------| -| **职责** | 单 session 对话 + Composer | -| **组件** | `list` 消息流 + `Input` + Mode/Model `DropdownButton` | -| **数据** | `SessionStore::chat(session_id)` | -| **事件** | `AgentEvent` → `ChatState::apply` | - -#### FileTab - -| 项 | 内容 | -|----|------| -| **职责** | 只读文件预览 | -| **组件** | `TextView` + `SyntaxHighlighter` | -| **数据** | `std::fs::read_to_string` | - -#### DiffTab - -| 项 | 内容 | -|----|------| -| **职责** | revision 与工作区 diff | -| **组件** | 双栏 `TextView` 或 unified diff | -| **数据** | `revision_dir(id)/files/` vs 工作区 | - -#### WorkflowLogTab - -| 项 | 内容 | -|----|------| -| **职责** | 单次 workflow 运行的 stdout | -| **组件** | 滚动 `VirtualList` | -| **数据** | `WorkflowRunner` 的 log channel | - ---- - -### 4.6 Runtime(`runtime`)— Bottom dock - -Bottom 默认显示 **RuntimeSummary**(一行),双击或拖高展开 Tabs。 - -| Tab | 职责 | 数据源 | -|-----|------|--------| -| **Summary** | 一行:节点数、actor 数、当前工具 | 聚合 | -| **Cluster** | SWIM 成员 + named actors 表 | HTTP `/cluster/members`, `all_named_actors` | -| **ToolTrace** | 当前 session 的 ToolStart/End 时间线 | `AgentEvent` | -| **WorkflowOutput** | workflow 子进程输出 | `WorkflowRunner` | - -```rust -pub struct RuntimeSummary { - pub nodes_alive: usize, - pub nodes_total: usize, - pub named_actors: usize, - pub active_tool: Option, - pub workflow_running: bool, -} -``` - ---- - -## 5. 状态边界:什么不属于 Panel - -Panel **只负责渲染 + 发意图**;共享状态进 `WorkspaceModel`(未来 `pulsing-workspace-gui`): - -```rust -pub struct WorkspaceModel { - pub layout: WorkspaceLayout, - pub files: FileIndex, - pub revisions: Vec, - pub head: Option, - pub workflows: Vec, - pub sessions: SessionStore, - pub runtime: RuntimeSnapshot, - pub center_tabs: CenterTabState, // 打开哪些 File/Diff/Chat tab -} -``` - -**跨面板事件**(`WorkspaceAction`): - -```rust -pub enum WorkspaceAction { - OpenFile(PathBuf), - OpenDiff { revision_id: String }, - OpenChat(SessionId), - RunWorkflow(PathBuf), - Checkpoint { message: Option }, - Rollback { revision_id: String }, - FocusAgent(SessionId), -} -``` - -Panel 发 `WorkspaceAction` → `WorkspaceApp::dispatch` 更新状态 → 下一帧重绘。 - ---- - -## 6. 代码模块映射(`pulsing-gui`) - -```text -crates/pulsing-gui/src/ -├── app/ -│ ├── mod.rs # WorkspaceApp:布局 + dispatch -│ ├── left.rs # Explorer / Revisions / Workflows -│ ├── chat.rs # 消息流 + Composer -│ └── right.rs # Sessions / Cluster -├── model/ # WorkspaceModel, SessionStore, actions -├── controller/ # agent turn 后台任务 -├── settings.rs -└── state.rs # ChatState -``` - ---- - -## 7. 面板实现约定(egui) - -各区域为独立 `render(app, ui)` 函数,通过 `WorkspaceAction` 与 `WorkspaceApp::dispatch` 通信,无需 GPUI `Panel` trait。 - ---- - -## 8. 默认尺寸与初始状态 - -| 区域 | 默认尺寸 | 默认开关 | -|------|----------|----------| -| Left | 220px | open | -| Right | 220px | open | -| Bottom | 状态条一行 | open | -| Center | 占满剩余 | — | - -Left 内 Tabs 默认 active:**Explorer** -Center 默认 active:**Chat** -Right 默认 active:**Sessions** - ---- - -## 9. 迁移状态(GPUI → egui) - -| 原 GPUI 计划 | 当前 egui 实现 | -|--------------|----------------| -| `WorkspaceShell` + `DockArea` | `WorkspaceApp` + `SidePanel` / `CentralPanel` | -| `panels/*` 模块 | `app/{left,chat,right}.rs` | -| Composer Mode/Model | `app/chat.rs` | -| Explorer 文件树 | `app/left.rs` | -| Revisions / Workflows | `app/left.rs`(列表占位,待交互) | - -**Phase 0 已完成**:三栏布局 + Explorer + Chat + Sessions + 状态栏。 - ---- - -## 10. 面板一览表(速查) - -| 面板 | 区域 | 模块 | 核心 API | -|------|------|------|----------| -| Explorer | Left | `app/left.rs` | `WorkspaceLayout`, walkdir | -| Revisions | Left | `app/left.rs` | `pulsing_workspace::journal` | -| Workflows | Left | `app/left.rs` | `session::workspace::list_workflow_scripts` | -| Chat | Center | `app/chat.rs` | `pulsing_forge::AgentEvent` | -| File preview | Center | `app/mod.rs` | fs read | -| Sessions | Right | `app/right.rs` | `SessionStore` | -| Cluster | Right | `app/right.rs` | 占位(Phase 3) | -| Status | Bottom | `app/mod.rs` | workspace counts | diff --git a/docs/design/agent-workspace-gui.md b/docs/design/agent-workspace-gui.md deleted file mode 100644 index ff58b4fda..000000000 --- a/docs/design/agent-workspace-gui.md +++ /dev/null @@ -1,369 +0,0 @@ -# Agent Workspace GUI — 设计文档 - -> **状态更新(2026-07-26)**:GUI 的目标边界以 [`Forge 核心架构`](../src/design/forge/core-architecture.zh.md) 为准。GUI 是 `ForgeClient`,只发送命令并投影事件;Session、Turn、取消、工作区 revision 和演化状态都由 Forge 拥有。本文其余内容保留为布局与迁移参考,凡涉及 GUI 自有 worker、事件 receiver 或执行状态的设计均被该边界取代。 -> -> 目标:类似 **Zed** 的现代化 Agent 工作空间——文件管理、工作流版本、Duo-Agent 会话、Pulsing 多进程/Actor 运行时可视。 -> **实现栈**:`eframe` / `egui`(`pulsing gui` 桌面窗口)。 - -## 1. 设计原则 - -| 原则 | 说明 | -|------|------| -| **Zed 式布局** | 左侧 Explorer + 中央编辑/对话 + 底部/右侧 Dock(终端、工作流、运行时) | -| **单一工作区根** | 以 `WorkspaceLayout`(`.pulsing/`)为真相源,GUI 不另建配置 | -| **事件驱动 UI** | 通过 `ForgeClient.subscribe(session_id, after_seq)` 投影版本化 Forge Event | -| **执行状态外置** | GUI 不拥有 worker、取消 token 或 busy 真相;状态来自 Forge Session 投影 | -| **Safe / Extension 分层** | Safe 模式纯 Rust;Extension 模式通过 embed Python 接 Craft 多 Agent | -| **渐进交付** | Phase 0→3,每阶段可独立 `pulsing gui` 可用 | - -## 2. 总体布局 - -``` -┌──────────┬────────────────────────────────────────────┬─────────────┐ -│ EXPLORER │ EDITOR / CHAT │ AGENTS │ -│ │ ┌──────────────────────────────────────┐ │ │ -│ 📁 src/ │ │ Tab: Chat · README · diff@0003 │ │ ○ coder │ -│ 📁 .pul..│ │ │ │ ● reviewer │ -│ │ │ [消息流 / 文件预览 / diff] │ │ ○ planner │ -│ REVISIONS│ │ │ │ │ -│ * 0003 │ └──────────────────────────────────────┘ │ + Spawn │ -│ 0002 │ │ │ -│ WORKFLOWS│──────────────────────────────────────────────│ │ -│ ▶ example│ Composer: [Agent▾][model▾] @file ↑ │ │ -└──────────┴────────────────────────────────────────────┴─────────────┘ -┌───────────────────────────────────────────────────────────────────────┐ -│ RUNTIME Nodes:2 Actors:14 │ workflow:example.py RUNNING │ Logs │ -│ node-A ● Alive node-B ● Alive │ craft/ws/abc/coder ● busy │ -└───────────────────────────────────────────────────────────────────────┘ -``` - -### 区域职责 - -| 区域 | 功能 | 主要数据源 | -|------|------|------------| -| **Explorer** | 工作区文件树、`.pulsing/` 折叠显示 | `WorkspaceLayout::root` + `walkdir` | -| **Revisions** | Checkpoint 时间线、回滚、与 HEAD diff | `pulsing_workspace::{list_revisions, current_head}` | -| **Workflows** | `.pulsing/workflows/*.py` 列表、运行/停止、日志 | `session::workspace::list_workflow_scripts` | -| **Editor/Chat** | 多 Tab:对话、文件只读、revision diff | `ChatState` + 文件内容 | -| **Agents** | Duo / 多 Agent 列表、spawn、切换会话 | `list_cluster_agents()` / `craft/ws/{id}/*` | -| **Runtime Bar** | 集群节点、命名 Actor、workflow 进程状态 | HTTP observer + `SystemActor` | - -## 3. 架构分层 - -```mermaid -flowchart TB - subgraph GUI["pulsing-gui (egui)"] - Layout[SidePanel / CentralPanel 布局] - Explorer[ExplorerPanel] - Chat[ChatPanel] - Agents[AgentsPanel] - Runtime[RuntimePanel] - Revisions[RevisionsPanel] - Workflows[WorkflowsPanel] - end - - subgraph Core["pulsing-workspace-gui (新 crate,建议)"] - Bus[WorkspaceBus] - Sessions[SessionStore] - Files[FileIndex] - Rev[RevisionStore] - Wf[WorkflowRunner] - Cluster[ClusterObserver] - end - - subgraph Existing["已有后端"] - WS[pulsing-workspace] - Forge[pulsing-forge] - CLI[pulsing-cli session] - Actor[pulsing-actor HTTP] - Py[Python Craft / embed] - end - - Layout --> Explorer & Chat & Agents & Runtime & Revisions & Workflows - Explorer & Chat & Agents --> Bus - Bus --> Sessions & Files & Rev & Wf & Cluster - Files --> WS - Rev --> WS - Wf --> CLI - Cluster --> Actor - Cluster --> Py - Chat --> Forge - Agents --> Py -``` - -### 新 crate:`pulsing-workspace-gui`(推荐) - -把 **UI 无关** 的状态与轮询放在独立 crate,供 `pulsing-gui` 与未来 TUI 复用: - -```rust -// 统一事件总线 -pub enum WorkspaceEvent { - FileChanged { path: PathBuf }, - RevisionCreated { info: RevisionInfo }, - HeadChanged { id: String }, - WorkflowStarted { script: PathBuf, pid: u32 }, - WorkflowOutput { line: String }, - WorkflowFinished { exit_code: i32 }, - ClusterMembers { members: Vec }, - NamedActors { actors: Vec }, - CraftAgent { name: String, status: AgentStatus }, - AgentEvent(AgentEvent), // safe-mode forge - ForgeEvent { kind: String, .. }, // extension craft -} - -pub struct WorkspaceModel { - pub layout: WorkspaceLayout, - pub sessions: SessionStore, // 多 chat / 多 agent 会话 - pub revisions: Vec, - pub head: Option, - pub workflows: Vec, - pub cluster: ClusterSnapshot, -} -``` - -## 4. 面板详细设计 - -### 4.1 Explorer(文件管理) - -- **egui 组件**:`CollapsingHeader` 文件树 + `ScrollArea` -- **根节点**:`WorkspaceLayout.root`(隐藏 `.git` 等,`.pulsing` 可折叠子树) -- **交互**: - - 单击 → 中央 Tab 打开只读预览(`Read` 工具同源) - - 右键 → Open in Chat(`@path` 填入 composer) - - 与 **HEAD revision** 对比 → 高亮未 checkpoint 的修改文件(`git status` 或 journal diff) - -```rust -pub struct FileNode { - pub path: PathBuf, - pub kind: FileNodeKind, // File | Dir | PulsingMeta - pub dirty: bool, // 相对 last checkpoint -} -``` - -### 4.2 Revisions(工作流版本管理) - -复用 `pulsing-workspace` journal,**不是 git**,是 workspace 级快照: - -| 操作 | API | GUI | -|------|-----|-----| -| 列表 | `list_revisions(&layout)` | 左侧时间线,`*` 标记 HEAD | -| 创建 | `checkpoint(&layout, CheckpointOptions { message })` | 按钮 / 发送后自动 checkpoint(可配置) | -| 回滚 | `rollback(&layout, RollbackOptions { revision_id })` | 确认 Dialog | -| Diff | 读 `revision_dir(id)/files/` vs 工作区 | 中央 diff Tab | - -```rust -pub struct RevisionRow { - pub info: RevisionInfo, - pub is_head: bool, - pub parent: Option, -} -``` - -### 4.3 Workflows(工作流) - -| 项 | 说明 | -|----|------| -| 发现 | `list_workflow_scripts()` → `.pulsing/workflows/*.py` | -| 运行 | `embed::run_workflow_script` 或子进程 `pulsing run -s script.py` | -| 状态 | `WorkflowEntry { script, state: Idle \| Running \| Failed, pid?, log_rx }` | -| UI | 列表 + Run/Stop;日志在底部 Dock `Workflow` tab | - -与 **Revisions** 联动:workflow 关键步骤完成后可自动 `checkpoint(message="after workflow step N")`。 - -### 4.4 Duo-Agent 会话管理 - -命名空间:`craft/ws/{cluster_id}/{agent_name}`(`cluster_id` = `WorkspaceManifest.cluster_id`)。 - -```rust -pub struct AgentSession { - pub id: SessionId, - pub kind: SessionKind, - pub title: String, - pub target: AgentTarget, - pub chat: ChatState, - pub busy: bool, -} - -pub enum SessionKind { - LocalForge, // 当前 pulsing-gui 单 agent - RemoteNamed(String), // craft/ws/.../coder - Workflow, // workflow 驱动的一次性 run -} - -pub enum AgentTarget { - Local { config: AgentConfig }, - NamedActor { path: String }, -} -``` - -**Agents 侧栏**(类似 Cursor 多 Chat): -- `Local` — 默认 Forge agent(已实现) -- `+ Spawn` — 调 `pulsing agent spawn `(extension) -- 每个 remote agent 独立 `ChatState` + 可选 `P2PToolSession` 事件流 - -**Python API(extension)**: -```python -rows = await list_cluster_agents(system, workspace_id=cluster_id) -await message_cluster_agent(system, name, payload) -``` - -### 4.5 Runtime(多进程 / 多 Actor 状态) - -三层观测,合并到 **Runtime Bar** + **Runtime Dock**: - -| 层级 | 来源 | 展示 | -|------|------|------| -| **SWIM 集群** | `GET /cluster/members` 或 `system.members()` | 节点列表、Alive/Suspect/Dead | -| **命名 Actor** | `system.all_named_actors()` / `GET /actors` | `craft/ws/...` 实例数、所在节点 | -| **本地 System** | `SystemActorProxy.health_check()` | actors_count、uptime | -| **Workflow 子进程** | GUI 自己 spawn 的 pid | Running/退出码 | -| **Forge 工具** | `AgentEvent::ToolStart/End` | 当前 agent 的工具时间线 | - -```rust -pub struct ClusterSnapshot { - pub nodes: Vec, - pub named_actors: Vec, - pub local_health: Option, - pub updated_at: Instant, -} - -pub struct AgentRuntimeRow { - pub path: String, - pub node_id: String, - pub status: ActorStatus, // Idle | Busy | Error - pub current_tool: Option, -} -``` - -轮询策略:集群 2s、Forge 事件 50ms(已有)、workflow stdout 阻塞读。 - -## 5. 中央区域:Tab 模型 - -使用 `egui::SidePanel` / `CentralPanel` 与顶部 Tab 栏: - -| Tab 类型 | 内容 | -|----------|------| -| `Chat(session_id)` | 现有 ChatPanel | -| `File(path)` | `TextView` + `SyntaxHighlighter` | -| `Diff { base, head }` | 双栏或 unified diff | -| `WorkflowLog(run_id)` | 滚动日志 | -| `Plan` | `Accordion` 展示 `PlanItem` / `PLAN_UPDATED` | - -## 6. Composer 增强(Cursor 风格) - -在现有 `[Mode▾][Model▾]` 基础上: - -| 控件 | 行为 | -|------|------| -| `@` | Popover + `Tree` 选文件,插入 context | -| `/` | 命令:checkpoint、rollback、workflow run、agent spawn | -| 目标 Agent | 当前 session 为 remote 时显示 agent 名 | - -## 7. 数据流(单轮对话) - -```mermaid -sequenceDiagram - participant User - participant GUI as ChatPanel - participant Bus as WorkspaceBus - participant Forge as pulsing-forge - participant WS as pulsing-workspace - - User->>GUI: Send prompt - GUI->>Bus: StartTurn(session_id, prompt) - Bus->>Forge: run_agent_turn_observed - loop stream - Forge-->>Bus: AgentEvent - Bus-->>GUI: WorkspaceEvent::AgentEvent - end - Forge-->>Bus: Done - opt auto_checkpoint - Bus->>WS: checkpoint - Bus-->>GUI: RevisionCreated - end -``` - -## 8. Crate / 模块规划 - -``` -crates/ - pulsing-workspace-gui/ # 新建:WorkspaceModel, Bus, 轮询 - src/ - model.rs - bus.rs - files.rs - revisions.rs - workflows.rs - cluster.rs - sessions.rs - - pulsing-gui/ # 现有:egui 视图 - src/ - app/ - mod.rs # WorkspaceApp:布局 + dispatch - left.rs # Explorer / Revisions / Workflows - chat.rs # 消息流 + Composer - right.rs # Sessions / Cluster - model/ # WorkspaceModel, SessionStore, actions - controller/ # agent turn 后台任务 - settings.rs - state.rs - - pulsing-cli/src/gui/ - mod.rs # 启动 workspace model + gui -``` - -**依赖关系**: -``` -pulsing-gui → pulsing-workspace-gui → pulsing-workspace, pulsing-forge -pulsing-workspace-gui → pulsing-actor (HTTP client, optional) -pulsing-cli gui → 初始化 WorkspaceLayout,传 cluster_id -``` - -## 9. 分阶段交付 - -### Phase 0 — 骨架(1–2 周) -- [x] `WorkspaceModel` + `list_revisions` + 文件 walk -- [x] egui 三栏布局:Left Explorer | Center Chat | Right Sessions -- [x] Explorer 文件树只读 - -### Phase 1 — 版本 + 工作流(1–2 周) -- [ ] Revisions 面板:timeline、checkpoint、rollback、Dialog 确认 -- [ ] Workflows 面板:列表、Run、底部日志 Tab -- [ ] 文件 Tab 预览 - -### Phase 2 — 多会话(2 周) -- [ ] `SessionStore`:多 Local chat tab -- [ ] Composer `@` 文件引用 -- [ ] `TextView::markdown` 渲染助手回复 - -### Phase 3 — Duo-Agent + Runtime(2–3 周) -- [ ] Extension mode:embed Python `list_cluster_agents` -- [ ] Agents 侧栏:spawn、切换 remote session -- [ ] Runtime Bar:集群成员 + named actors 轮询 -- [ ] `ForgeEvent` / `P2PToolSession` 接入 extension agent - -## 10. 与现有代码映射 - -| 已有 | 新 GUI 用法 | -|------|-------------| -| `pulsing-gui/src/app/` | `WorkspaceApp` + `left` / `chat` / `right` 模块 | -| `session/workspace.rs` | `RevisionsPanel` / `WorkflowsPanel` 直接调用 | -| `session/commands.rs` `InputAction` | Composer `/` 命令同语义 | -| `pulsing_workspace::journal` | Revision 全流程 | -| `AgentEvent` | Local session 流式 UI | -| `python/.../cluster/discovery.py` | Agents 面板 | -| `crates/pulsing-actor` observer HTTP | Runtime 面板 | - -## 11. 非目标(首版不做) - -- 完整代码编辑器(Monaco 级)— 先只读 + 外链编辑器 -- Git 集成 — 用 workspace journal 代替 -- 云端同步会话 -- WebView 面板 - ---- - -**下一步建议**:继续 **Phase 1**(Revisions 交互、Workflows 运行、diff Tab),在现有 `pulsing gui` egui 布局上渐进增强。 - -**布局与面板细节**见:[agent-workspace-dock-panels.md](./agent-workspace-dock-panels.md)(概念布局;实现为 egui)。 diff --git a/docs/design/codex-forge-tool-migration.md b/docs/design/codex-forge-tool-migration.md deleted file mode 100644 index a6f33fa24..000000000 --- a/docs/design/codex-forge-tool-migration.md +++ /dev/null @@ -1,3 +0,0 @@ -# 已归档 - -该文档已从公开文档站移除。Forge 对外说明见 [`docs/src/forge/`](../src/forge/);工程细节见 [`docs/src/design/forge/engineering.zh.md`](../src/design/forge/engineering.zh.md)。 diff --git a/docs/design/craft-agent-refactor.md b/docs/design/craft-agent-refactor.md deleted file mode 100644 index 961582735..000000000 --- a/docs/design/craft-agent-refactor.md +++ /dev/null @@ -1,980 +0,0 @@ -# Craft Agent Refactor: From HubActor to Peer-to-Peer Agents - -> **目标**: 去掉 HubActor 作为中心瓶颈,将所有 Agent 变成对等节点,释放真正的多 Agent 并发能力。 -> -> **给实现 AI 的指令**: 严格按本设计文档实现。如遇未覆盖的细节,参考现有 `hub_actor.py` / `coordinator.py` / `cluster_tools.py` 的代码,保持兼容风格。改动集中在 `python/pulsing/craft/` 目录,不修改 `crates/` 下的 Rust 代码。 - ---- - -## 1. 问题诊断 - -### 1.1 当前架构的核心矛盾 - -```mermaid -graph TD - subgraph "HubActor 承担了互相冲突的职责" - H["HubActor
❌ 对话引擎 + 协调中心 + 权限管理 + 沙箱管理
所有操作受 turn_lock 串行化"] - end - - W1["Worker
不能用 Agent 工具"] -->|"排队等 turn_lock"| H - W2["Worker
不能用 Agent 工具"] -->|"排队等 turn_lock"| H - PA["Peer HubActor"] -.->|"receive_agent_message → 进队列"| H - - style H fill:#f96,stroke:#333,stroke-width:3px -``` - -### 1.2 具体问题 - -| 问题 | 证据 | 影响 | -|---|---|---| -| **turn_lock 全局串行化** | `hub_actor.py:L493` `async with self._turn_lock:` | 其他 agent 的消息必须等当前 turn 完成 | -| **Worker 不能 spawn sub-agent** | `coordinator.py:L44-48` `_worker_tool_table` 排除了 `COORDINATOR_TOOL_NAMES` | 无法递归委托复杂任务 | -| **消息排队不透明** | `hub_actor.py:L234-244` `receive_agent_message` 进队列,sender 不知道何时处理 | 无法构建可靠的多 agent 协作 | -| **Coordinator task notification 也是排队** | `coordinator.py:L197-206` worker 结果通过 `enqueue_coordinator_notification` | hub 空闲时才被 drain | -| **Agent 角色是装饰性的** | `agent_role` / `agent_description` 存在但只用于 `get_cluster_info()` 返回 | 所有 agent 用同一套 system prompt 和工具 | -| **四种概念混在一起** | HubActor / CoordinatorRuntime / ClusterRuntime / SessionActor | 心智负担重,代码重复 | - ---- - -## 2. 目标架构 - -```mermaid -graph TD - subgraph "对等 Agent 网络" - A1["Agent 'lead'
独立 turn loop
可 spawn sub-agent"] - A2["Agent 'coder'
独立 turn loop
代码工具集"] - A3["Agent 'reviewer'
独立 turn loop
审查工具集"] - end - - subgraph "递归委托示例" - A4["Sub-Agent
深度=1"] - A5["Sub-Sub-Agent
深度=2"] - end - - A1 -->|"receive_message(msg)"| A2 - A2 -->|"receive_message(msg)"| A3 - A3 -->|"receive_message(msg)"| A1 - - A1 -->|"Agent tool spawn"| A4 - A4 -->|"Agent tool spawn"| A5 - - U["👤 User / CLI"] -->|"run_turn(text)"| A1 - - style A1 fill:#6f6,stroke:#333 - style A2 fill:#6f6,stroke:#333 - style A3 fill:#6f6,stroke:#333 - style A4 fill:#6f9,stroke:#333 - style A5 fill:#6f9,stroke:#333 -``` - -### 核心原则 - -1. **每个 Agent 都是对等节点** — 没有 hub/worker 之分,每个 agent 拥有完整的 `AsyncTurnRunner` -2. **Agent 直接通信** — `receive_message(from_agent, message)` 而非经过中心 hub 排队 -3. **递归委托** — 任何 Agent 都可以使用 `Agent` 工具 spawn sub-agent,sub-agent 也可以再 spawn -4. **可选工具集** — 每个 Agent 可以有不同的 system prompt 和工具白名单 -5. **独立 turn loop** — 每个 Agent 在自己的 `asyncio.Task` 中处理消息,不阻塞其他 Agent - ---- - -## 3. 新 Agent 类设计 - -### 3.1 完整 API - -```python -# 文件: python/pulsing/craft/agent.py - -@pul.remote -class Agent: - """ - 对等 Agent — 每个实例拥有独立的 turn loop、工具集和 system prompt。 - - Spawn: await Agent.spawn(name="craft/agent/lead", ...) - Resolve: await pul.resolve("craft/agent/lead", cls=Agent) - - 消息入口: - - receive_message(from_agent, message) -> dict # 非阻塞,放入 inbox - - receive_message_and_wait(from_agent, message, timeout) -> dict # 阻塞等待结果 - - run_turn(text) -> dict # 用户直接对话 (兼容旧 API) - - run_turn_stream(text) -> AsyncGenerator # 流式对话 (兼容旧 API) - """ - - def __init__( - self, - *, - # --- identity --- - name: str, # agent 短名 (如 "lead", "coder") - workspace_id: str | None = None, # workspace 隔离 - role: str = "", # 角色描述 (用于 discovery) - description: str = "", # 描述 (用于 discovery) - - # --- LLM config --- - model: str, - provider: str = "anthropic", - api_key: str | None = None, - base_url: str | None = None, - max_tokens: int = 8192, - - # --- prompt --- - system_prompt: str | None = None, # None = 使用内置默认值 - prompt_callback: Any | None = None, # 权限回调 - - # --- tools --- - tool_allowlist: list[str] | None = None, # None = 全部工具; 否则按名称过滤 - tool_denylist: list[str] | None = None, # 排除特定工具 - - # --- delegation --- - max_delegation_depth: int = 3, # Agent 工具最大递归深度 - delegation_default_model: str | None = None, # sub-agent 默认模型 - - # --- sandbox --- - sandbox_policy: str = "off", - dangerously_disable_sandbox: bool = False, - - # --- permissions --- - auto_approve: bool = False, - - # --- session --- - cwd: str = ".", - resume_id: str | None = None, - cost_log: bool = True, - stream_assistant: bool = True, - ) -> None: - ... -``` - -### 3.2 内部状态 - -```python - def __init__(self, ...): - # === identity === - self._name: str - self._workspace_id: str | None - self._role: str - self._description: str - - # === LLM === - self._provider: str - self._model: str - self._api_key: str | None - self._base_url: str | None - self._max_tokens: int - - # === prompt === - self._system_prompt: str - self._prompt_callback: Any | None - - # === tools === - self._tool_allowlist: set[str] | None - self._tool_denylist: set[str] | None - self._tools: dict[str, Tool] # 最终生效的工具表 - - # === delegation === - self._delegation_depth: int = 0 # 当前 agent 的深度 (0 = root) - self._max_delegation_depth: int - self._delegation_default_model: str - self._sub_agent_refs: dict[str, str] # task_id -> actor_name (用于 TaskStop) - - # === sandbox === - self._sandbox_policy: str - self._dangerously_disable_sandbox: bool - - # === permissions === - self._checker: PermissionChecker # 去掉 plan workspace 耦合 - self._mode: str = "default" # "default" | "plan" | "dream" - - # === session === - self._cwd: str - self._session: SessionStore - - # === runner === - self._runner: AsyncTurnRunner | None - - # === inbox + concurrency === - self._inbox: asyncio.Queue[Message] # 所有入站消息 - self._processor_task: asyncio.Task | None # 后台消息处理循环 - self._active_turns: set[asyncio.Task] # 正在运行的 turn (用于 graceful shutdown) - self._turn_semaphore: asyncio.Semaphore # 限制并发 turn 数 (默认 1,即串行) - - # === isolated worker === - self._worker_lock: asyncio.Lock - self._worker_handle: pul.IsolatedSpawnHandle | None - self._worker_proxy: pul.ActorProxy | None - - # === lifecycle === - self._on_start_done: bool - self._on_start_lock: asyncio.Lock - - # === buddy === - self._buddy: BuddyState -``` - -### 3.3 消息协议 (Message) - -```python -# 文件: python/pulsing/craft/message.py - -from __future__ import annotations - -import dataclasses -import asyncio -import uuid -from typing import Any - - -@dataclasses.dataclass -class Message: - """Agent 间通信的统一消息格式。""" - - # 元数据 - id: str = dataclasses.field(default_factory=lambda: uuid.uuid4().hex[:12]) - from_agent: str = "" # 发送方短名 - to_agent: str = "" # 接收方短名 (冗余,用于日志) - kind: str = "user" # "user" | "agent_message" | "task_notification" | "system" - - # 内容 - content: str = "" - - # 回复机制 - reply_future: asyncio.Future | None = None # 设置后,turn 完成时 set_result - reply_timeout: float = 600.0 - - # 委托链 (用于日志和调试) - delegation_chain: list[str] = dataclasses.field(default_factory=list) # ["lead", "coder"] - delegation_depth: int = 0 -``` - -### 3.4 消息处理循环 - -```python - async def on_start(self, actor_id) -> None: - """启动时:创建 runner + 启动消息处理循环。""" - async with self._on_start_lock: - if self._on_start_done: - return - await self._init_runner() - self._processor_task = asyncio.create_task(self._process_loop()) - self._on_start_done = True - - async def on_stop(self) -> None: - """关闭时:取消循环 + 等待活跃 turn + 清理 worker。""" - if self._processor_task: - self._processor_task.cancel() - try: - await self._processor_task - except asyncio.CancelledError: - pass - # 等待活跃 turn 完成 (最多 10 秒) - for task in list(self._active_turns): - task.cancel() - if self._active_turns: - await asyncio.wait(self._active_turns, timeout=10.0) - # 清理 isolated worker - if self._worker_handle is not None: - proc = self._worker_handle.process - if proc.returncode is None: - proc.terminate() - - async def _process_loop(self) -> None: - """后台循环:持续从 inbox 取消息,semaphore 控制并发。""" - while True: - msg = await self._inbox.get() - # 每次取一条消息,acquire semaphore 后创建 task 处理 - await self._turn_semaphore.acquire() - task = asyncio.create_task(self._handle_one_message(msg)) - self._active_turns.add(task) - task.add_done_callback(lambda t: self._on_turn_done(t)) - - def _on_turn_done(self, task: asyncio.Task) -> None: - self._active_turns.discard(task) - self._turn_semaphore.release() - - async def _handle_one_message(self, msg: Message) -> None: - """处理一条消息:调用 runner.run_turn,管理 reply_future。""" - try: - # 准备 user-level 文本 - if msg.kind == "agent_message": - user_text = f"[message from {msg.from_agent}]\n{msg.content}" - elif msg.kind == "task_notification": - user_text = msg.content # 已经是 XML 格式 - else: - user_text = msg.content - - self._maybe_inject_pending_notifications() - result = await self._runner.run_turn(user_text) - - # 回复 sender (如果有 reply_future) - if msg.reply_future and not msg.reply_future.done(): - msg.reply_future.set_result(result) - - except asyncio.CancelledError: - if msg.reply_future and not msg.reply_future.done(): - msg.reply_future.set_exception( - asyncio.CancelledError("turn cancelled") - ) - except Exception as e: - if msg.reply_future and not msg.reply_future.done(): - msg.reply_future.set_exception(e) -``` - -### 3.5 公网 API (与旧 API 兼容) - -```python - # === 兼容 run_hub.py 的 API === - - def ping(self) -> dict[str, Any]: - """健康检查 (兼容旧 controller_repl)。""" - return { - "ok": True, - "agent": self._name, - "role": self._role, - "workspace_id": self._workspace_id, - "session_id": self._session.session_id, - "cwd": self._cwd, - "delegation_depth": self._delegation_depth, - } - - def get_cluster_info(self) -> dict[str, Any]: - """元数据卡片 (兼容旧 /info)。""" - return { - "name": self._name, - "full_name": full_agent_name(self._name, workspace_id=self._workspace_id), - "workspace_id": self._workspace_id, - "role": self._role, - "description": self._description, - "session_id": self._session.session_id, - "cwd": self._cwd, - "model": self._model, - "provider": self._provider, - "delegation_depth": self._delegation_depth, - "max_delegation_depth": self._max_delegation_depth, - } - - async def receive_message( - self, - from_agent: str, - message: str, - *, - wait: bool = False, - timeout: float = 600.0, - ) -> dict[str, Any]: - """ - 接收来自其他 Agent 的消息。 - - wait=False: 放入 inbox 后立即返回 {"ok": True, "accepted": True} - wait=True: 阻塞等待 turn 完成并返回完整结果 - """ - ... - - def get_session_id(self) -> str: - return self._session.session_id - - def get_role_prompt(self) -> str: ... - def set_role_prompt(self, text: str) -> str: ... - def reset_role_prompt(self) -> str: ... - def set_role_prompt_from_file(self, path: str) -> str: ... - - async def run_turn(self, text: str) -> dict[str, Any]: - """用户对话入口 (兼容旧 run_turn RPC)。""" - ... - - async def run_turn_stream(self, text: str) -> AsyncGenerator: - """流式对话入口 (兼容旧 run_turn_stream RPC)。""" - ... -``` - ---- - -## 4. Agent 工具 (递归委托) - -### 4.1 工具 Schema - -```python -# 文件: python/pulsing/craft/tools/agent_tool.py - -class AgentTool(Tool): - @property - def name(self) -> str: - return "Agent" - - @property - def description(self) -> str: - return ( - "Spawn a sub-agent to handle a task autonomously. " - "The sub-agent runs in its own turn loop with a subset of tools. " - "Results are reported as XML messages." - ) - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "goal": { - "type": "string", - "description": "High-level objective. Be specific about expected output.", - }, - "agent_name": { - "type": "string", - "description": "Short name for the sub-agent (e.g. 'researcher'). Auto-generated if omitted.", - }, - "role": { - "type": "string", - "description": "System prompt override for sub-agent. If empty, inherits parent's prompt.", - }, - "tool_allowlist": { - "type": "array", - "items": {"type": "string"}, - "description": "Limit sub-agent to these tools. If omitted, inherits parent's tools minus Agent/TaskStop.", - }, - "model": { - "type": "string", - "description": "Model override for sub-agent.", - }, - "task_id": { - "type": "string", - "description": "Stable id for follow-up messages. Generated if omitted.", - }, - }, - ["goal"], - ) - - def is_read_only(self) -> bool: - return True - - def execute(self, **kwargs: Any) -> ToolResult: - raise RuntimeError( - "Agent tool is executed via Agent._execute_agent_tool, not in-process." - ) -``` - -### 4.2 执行逻辑 (在 Agent 类中) - -```python - async def _execute_agent_tool(self, **kwargs: Any) -> ToolResult: - """在 Agent 的上下文中执行 Agent 工具 (spawn sub-agent)。""" - goal = str(kwargs.get("goal", "")).strip() - if not goal: - return ToolResult(content="Agent: goal is required.", is_error=True) - - # 深度检查 - if self._delegation_depth >= self._max_delegation_depth: - return ToolResult( - content=( - f"Agent: max delegation depth ({self._max_delegation_depth}) " - f"reached at depth {self._delegation_depth}." - ), - is_error=True, - ) - - # 生成 agent 名和 task_id - agent_name = str(kwargs.get("agent_name") or "").strip() - if not agent_name: - agent_name = f"sub-{uuid.uuid4().hex[:6]}" - task_id = str(kwargs.get("task_id") or "").strip() or f"task-{uuid.uuid4().hex[:10]}" - - # 构建 sub-agent 的工具集 - allowlist = kwargs.get("tool_allowlist") - if allowlist is None: - # 默认:继承父 agent 的非 Agent/TaskStop 工具 - allowlist = [ - n for n in self._tools - if n not in ("Agent", "TaskStop") - ] - - # 构建 role (system prompt) - role = str(kwargs.get("role") or "").strip() - if not role: - role = ( - f"You are a sub-agent of '{self._name}'. " - f"Your parent's role: {self._role}. " - f"Complete the assigned task and report results." - ) - - # Spawn sub-agent - full_name = full_agent_name(agent_name, workspace_id=self._workspace_id) - sub = await Agent.spawn( - name=agent_name, - workspace_id=self._workspace_id, - role=role, - description=f"Sub-agent of {self._name}", - model=kwargs.get("model") or self._delegation_default_model or self._model, - provider=self._provider, - api_key=self._api_key, - base_url=self._base_url, - tool_allowlist=allowlist, - max_delegation_depth=self._max_delegation_depth, - sandbox_policy=self._sandbox_policy, - dangerously_disable_sandbox=self._dangerously_disable_sandbox, - auto_approve=self._checker._auto_approve, - cwd=self._cwd, - stream_assistant=False, # sub-agent 不需要 stream - cost_log=self._session is not None, - ) - - # 设置 delegation depth - sub_proxy = pul.ActorProxy(sub.ref, Agent._methods, Agent._async_methods) - # (通过 RPC 设置 depth,或者把 depth 作为 spawn 参数传入) - - # 记录 sub-agent reference - self._sub_agent_refs[task_id] = full_name - - # 发送初始任务 - asyncio.create_task( - self._run_sub_agent(task_id, goal, sub_proxy, agent_name) - ) - - return ToolResult( - content=json.dumps({ - "task_id": task_id, - "agent": agent_name, - "full_name": full_name, - "status": "started", - "goal": goal, - }, ensure_ascii=False), - ) - - async def _run_sub_agent( - self, - task_id: str, - goal: str, - sub_proxy: pul.ActorProxy, - agent_name: str, - ) -> None: - """在后台驱动 sub-agent 的 turn loop。""" - try: - result = await sub_proxy.receive_message( - from_agent=self._name, - message=goal, - wait=True, - ) - # 格式化结果通知 - status = "completed" if result.get("ok") else "failed" - summary = result.get("assistant_text", "")[:2000] - notification = _format_task_notification( - task_id=task_id, - agent_name=agent_name, - status=status, - summary=summary, - result=result.get("assistant_text", "")[:8000], - ) - self._pending_notifications.append(notification) - except Exception as e: - notification = _format_task_notification( - task_id=task_id, - agent_name=agent_name, - status="failed", - summary=str(e)[:2000], - result="", - ) - self._pending_notifications.append(notification) - finally: - self._sub_agent_refs.pop(task_id, None) -``` - -### 4.3 Task Notification 注入 - -不同于旧 CoordinatorRuntime 的 "enqueue → 等 hub 空闲才 drain",新设计在每次 turn 开始前注入: - -```python - # 在 Agent 类中 - _pending_notifications: list[str] = [] - - def _maybe_inject_pending_notifications(self) -> None: - """将积压的 sub-agent 完成通知注入到 runner 的消息历史中。""" - for notification in self._pending_notifications: - self._runner.append_synthetic_user_message(notification) - self._pending_notifications.clear() -``` - ---- - -## 5. 工具系统重构 - -### 5.1 统一工具注册 - -```python -# 文件: python/pulsing/craft/tools/registry.py - -""" -工具注册表 — 所有 Agent 从这里获取工具定义。 - -每个工具有一个 category: - - "filesystem" : Read, Glob, Grep, Edit, Write, Bash → 隔离执行 - - "memory" : MemoryAppend, MemorySearch → 本地执行 - - "coordination": Agent, SendMessage, TaskStop → 在 Agent 上下文中执行 - - "cluster" : ListClusterAgents, MessageClusterAgent → 在 Agent 上下文中执行 - - "ux" : AskUserQuestion, BuddyStatus, SkillsList, McpCatalog → 本地执行 - - "mode" : EnterDreamMode, ExitDreamMode, EnterPlanMode, ExitPlanMode → 本地执行 - - "web" : FetchUrl → 本地执行 - - "skill" : SkillRun → 本地执行 -""" - -from dataclasses import dataclass -from typing import Literal - -ToolCategory = Literal[ - "filesystem", "memory", "coordination", "cluster", "ux", "mode", "web", "skill" -] - -@dataclass -class ToolDef: - """工具定义:类 + 元数据。""" - tool_cls: type[Tool] - category: ToolCategory - requires_allowlist: bool = False # 是否需要在 tool_allowlist 中显式指定 - -# 全局注册表 -_REGISTRY: dict[str, ToolDef] = {} - -def register(category: ToolCategory, requires_allowlist: bool = False): - """装饰器:注册工具类。""" - def decorator(cls: type[Tool]): - instance = cls() # 创建实例获取 name - _REGISTRY[instance.name] = ToolDef( - tool_cls=cls, - category=category, - requires_allowlist=requires_allowlist, - ) - return cls - return decorator - -def build_tools( - *, - checker: PermissionChecker, - tool_allowlist: set[str] | None = None, - tool_denylist: set[str] | None = None, - delegation_depth: int = 0, - max_delegation_depth: int = 3, - include_coordination_tools: bool = True, - **kwargs, -) -> dict[str, Tool]: - """ - 根据配置构建工具表。 - - - tool_allowlist 不为 None → 仅包含列表中指定的工具 - - tool_denylist → 排除列表中指定的工具 - - delegation_depth >= max_delegation_depth → 自动排除 Agent 工具 - """ - ... -``` - -### 5.2 现有工具迁移 - -将 `tools_pkg.py` 中的工具类用 `@register` 装饰: - -```python -# 文件: python/pulsing/craft/tools/filesystem.py - -from pulsing.craft.tools.registry import register - -@register(category="filesystem") -class ReadTool(Tool): - ... - -@register(category="filesystem") -class BashTool(Tool): - ... - -# 文件: python/pulsing/craft/tools/coordination.py - -@register(category="coordination", requires_allowlist=True) -class AgentTool(Tool): - ... - -@register(category="coordination") -class SendMessageTool(Tool): - ... - -@register(category="coordination") -class TaskStopTool(Tool): - ... -``` - ---- - -## 6. 并发模型 - -### 6.1 Per-Agent 消息处理 - -``` -inbox (asyncio.Queue) - │ - ▼ -_process_loop() ← 后台 asyncio.Task - │ - ├── await inbox.get() ← 阻塞等待下一条消息 - ├── await semaphore ← 限制并发 turn 数 - │ - ▼ -_handle_one_message(msg) ← asyncio.Task - │ - ├── _maybe_inject_pending_notifications() - ├── runner.run_turn(user_text) - └── msg.reply_future.set_result(...) -``` - -### 6.2 并发控制选项 - -```python - def __init__(self, ..., max_concurrent_turns: int = 1): - # max_concurrent_turns=1: 串行处理 (安全默认,当前行为) - # max_concurrent_turns=3: 最多同时处理 3 个 turn - # max_concurrent_turns=0: 无限制 (⚠️ 需要文件锁保护) - self._turn_semaphore = asyncio.Semaphore(max_concurrent_turns) -``` - -### 6.3 文件冲突保护 - -当 `max_concurrent_turns > 1` 时,需要对文件操作加锁: - -```python -# 文件: python/pulsing/craft/tools/file_lock.py - -class FileLockManager: - """基于文件路径的 asyncio.Lock 管理器。""" - - def __init__(self): - self._locks: dict[str, asyncio.Lock] = {} - - def get_lock(self, path: str) -> asyncio.Lock: - key = str(Path(path).resolve()) - if key not in self._locks: - self._locks[key] = asyncio.Lock() - return self._locks[key] -``` - ---- - -## 7. 文件结构变更 - -### 7.1 删除的文件 - -``` -python/pulsing/craft/runtime/hub_actor.py → 合并到 agent.py -python/pulsing/craft/runtime/coordinator.py → 合并到 agent.py -python/pulsing/craft/runtime/cluster_tools.py → 合并到 tools/coordination.py -python/pulsing/craft/cluster/messaging.py → Agent.receive_message 替代 -python/pulsing/craft/runtime/split_tools.py → tools/registry.py 替代 -``` - -### 7.2 新增的文件 - -``` -python/pulsing/craft/ -├── agent.py # ★ 核心 Agent 类 (合并 HubActor + Coordinator + Cluster) -├── message.py # ★ Message 协议定义 -├── tools/ -│ ├── __init__.py -│ ├── registry.py # ★ 工具注册表 + build_tools -│ ├── base.py # Tool / ToolResult (从 tool_base.py 移入) -│ ├── filesystem.py # Read / Glob / Grep / Edit / Write / Bash -│ ├── memory.py # MemoryAppend / MemorySearch -│ ├── coordination.py # Agent / SendMessage / TaskStop / ListClusterAgents / MessageClusterAgent -│ ├── ux.py # AskUserQuestion / BuddyStatus / SkillsList / McpCatalog -│ ├── mode.py # EnterDreamMode / ExitDreamMode / EnterPlanMode / ExitPlanMode -│ ├── web.py # FetchUrl -│ └── skill.py # SkillRun -├── engine_async.py # 保留,不变 -├── engine.py # 保留,不变 -├── permissions.py # 保留,去掉 plan workspace 耦合 -├── sandbox.py # 保留,不变 -├── session.py # 保留,session_store.py 重命名 -├── memory_kairos.py # 保留,不变 -├── companion_buddy.py # 保留,不变 -├── isolated_worker.py # 保留,FullToolWorker 封装 -├── run.py # CLI: 启动单个 agent (原 run_hub.py 简化) -├── fleet.py # CLI: 启动 agent 集群 + 控制台 -├── cli/ -│ ├── __init__.py -│ ├── common.py # 共享 argparse 参数 -│ ├── agent.py # `pulsing craft agent` 命令 -│ ├── fleet.py # `pulsing craft fleet` 命令 -│ └── control.py # control REPL (原 controller_repl.py) -└── ... -``` - -### 7.3 保留不变的文件 - -``` -python/pulsing/craft/ -├── paths.py # 保留 -├── repl.py # 保留 (兼容 _print_hub_stream_event) -├── run.py # 保留 (minimal REPL) -├── session_actor.py # 保留 (轻量 session, 独立用途) -├── normalize.py # 保留 -├── helpers.py # 保留 -├── dispatch.py # 保留 -├── parser.py # 保留 -├── cli.py # 保留 -├── payload/ -│ ├── full_tool_worker.py # 保留 -│ └── tool_actor.py # 保留 -├── cluster/ -│ ├── constants.py # 保留 -│ ├── discovery.py # 保留 -│ ├── controller_repl.py # 更新:用 Agent 替代 HubActor -│ └── ... # run_cluster/run_agent/run_ctl 更新 -├── workspace/ # 保留 -├── commands/ # 保留 -``` - ---- - -## 8. 兼容性迁移 - -### 8.1 需要更新的调用方 - -| 文件 | 变更 | -|---|---| -| `runtime/run_hub.py` | `HubActor.spawn` → `Agent.spawn` | -| `cluster/run_agent.py` | `HubActor.spawn` → `Agent.spawn` | -| `cluster/run_cluster.py` | `HubActor.spawn` → `Agent.spawn` | -| `cluster/controller_repl.py` | `hub_proxy.run_turn` → `agent_proxy.run_turn` | -| `cluster/messaging.py` | `proxy.receive_agent_message` → `proxy.receive_message` | -| `cluster/discovery.py` | 不变 (gossip 查询机制不变) | -| `runtime/tui_app.py` | `hub_proxy.*` → `agent_proxy.*` | -| `runtime/slash_hub.py` | `_hub_send_agent` → `_agent_send_message` | -| `tests/*` | 更新 import 路径 + API 调用 | - -### 8.2 API 兼容对照表 - -| 旧 API (HubActor) | 新 API (Agent) | -|---|---| -| `HubActor.spawn(name=..., ...)` | `Agent.spawn(name=..., ...)` | -| `hub.ping()` | `agent.ping()` | -| `hub.get_cluster_info()` | `agent.get_cluster_info()` | -| `hub.receive_agent_message(from, msg, wait=True)` | `agent.receive_message(from, msg, wait=True)` | -| `hub.run_turn(text)` | `agent.run_turn(text)` | -| `hub.run_turn_stream(text)` | `agent.run_turn_stream(text)` | -| `hub.call_tool(name, kwargs)` | *内部方法,不再暴露* | -| `hub.coordinator_tasks_text()` | `agent.list_sub_agents()` (新增) | -| `hub.coordinator_stop_task(tid)` | `agent.stop_sub_agent(tid)` (新增) | -| `pul.resolve(HUB_SPAWN_NAME, cls=HubActor)` | `pul.resolve("craft/agent/lead", cls=Agent)` | -| `from pulsing.craft.cluster.messaging import message_cluster_agent` | 直接用 `agent.receive_message(from, msg)` | - ---- - -## 9. 实现步骤 (按顺序) - -### Step 1: 创建 `message.py` - -新建 `python/pulsing/craft/message.py`,定义 `Message` dataclass。**无依赖**,可以先写。 - -### Step 2: 创建 `tools/` 包 - -``` -python/pulsing/craft/tools/ -├── __init__.py # 导出所有工具类 -├── base.py # Tool / ToolResult (从 tool_base.py 移入,保持 API 兼容) -├── registry.py # 工具注册表 + build_tools 函数 -├── filesystem.py # Read / Glob / Grep / Edit / Write / Bash -├── memory.py -├── coordination.py # Agent / SendMessage / TaskStop / ListClusterAgents / MessageClusterAgent -├── ux.py -├── mode.py -├── web.py -└── skill.py -``` - -每个工具类用 `@register` 装饰。**依赖**: `base.py`。**不依赖 Agent**。 - -### Step 3: 创建 `agent.py` - -这是核心文件。实现顺序: - -1. **`Agent.__init__`** — 初始化所有内部状态 -2. **工具构建** — 调用 `registry.build_tools()` -3. **isolated worker 管理** — 从 `hub_actor.py` 搬 `_ensure_worker` / `_respawn_worker_locked` / `_isolated_tool_with_retry` -4. **`_init_runner`** — 创建 `AsyncTurnRunner` -5. **`on_start` / `on_stop`** — 生命周期 -6. **`_process_loop` / `_handle_one_message`** — 消息处理 -7. **`receive_message`** — 公网 API -8. **`run_turn` / `run_turn_stream`** — 用户对话 API -9. **`_execute_agent_tool` / `_run_sub_agent`** — sub-agent 委托 -10. **`_execute_send_message_tool` / `_execute_task_stop_tool`** — 协调工具 -11. **`call_tool`** — 工具路由 -12. **Slash commands** — `/help`, `/tasks`, `/role`, `/agents` 等 -13. **Ping / get_cluster_info / get_session_id** — 兼容 API - -**依赖**: `message.py`, `tools/`, `engine_async.py`, `permissions.py`, `sandbox.py`, `session.py`, `isolated_worker.py` - -### Step 4: 迁移工具文件 - -将 `tools_pkg.py` 中的工具类按 category 拆分到 `tools/` 子模块,添加 `@register` 装饰器。 - -将 `split_tools.py` 的 `_IsolatedSchemaTool` 逻辑合并到 `tools/registry.py` 的 `build_tools()` 中。 - -### Step 5: 更新 CLI 入口 - -更新 `run_hub.py` → `run.py`,使用 `Agent.spawn` 替代 `HubActor.spawn`。 - -### Step 6: 更新 cluster 相关文件 - -- `cluster/run_agent.py` — `HubActor.spawn` → `Agent.spawn` -- `cluster/run_cluster.py` — 同上 -- `cluster/controller_repl.py` — `hub_proxy.*` → `agent_proxy.*` -- `cluster/messaging.py` — 删除或用 `agent.receive_message()` 替代 - -### Step 7: 更新 TUI - -`runtime/tui_app.py` 和 `runtime/slash_hub.py` 中的 `hub` 引用改为 `agent`。 - -### Step 8: 更新测试 - -更新 `tests/python/test_craft_*.py` 中的 import 和 API 调用。 - -### Step 9: 删除旧文件 - -确认无引用后删除: -- `runtime/hub_actor.py` -- `runtime/coordinator.py` -- `runtime/cluster_tools.py` -- `runtime/split_tools.py` -- `cluster/messaging.py` - ---- - -## 10. 关键设计决策 (FAQ) - -### Q: 为什么保留 `turn_semaphore` 默认值=1 (串行)? - -A: 安全默认。文件操作 (Edit/Write/Bash) 在并发时会冲突。后续可以通过 `max_concurrent_turns=3` + `FileLockManager` 逐步放开。 - -### Q: sub-agent 为什么不直接 spawn 在同一个 Pulsing node? - -A: 它就是 spawn 在同一个 node。但通过 `pul.spawn` 创建的是独立的 Pulsing actor 实例,拥有独立的 mailbox。未来可以扩展到跨节点 spawn。 - -### Q: `Agent` 工具和 `MessageClusterAgent` 工具的区别? - -A: -- **Agent 工具**: spawn 新的 Agent actor,给它一个 goal,等它完成 -- **MessageClusterAgent**: 给已存在的 peer agent 发消息 - -两者都通过 `receive_message` 实现,但 Agent 工具多了 spawn 步骤。 - -### Q: delegation depth 怎么传递? - -A: spawn 时通过构造参数传入 `_delegation_depth = parent._delegation_depth + 1`。在 `Agent.__init__` 中设置,不通过 RPC。 - -### Q: `_StubCoordinatorTool` 怎么办? - -A: 删除。`registry.build_tools()` 根据 `include_coordination_tools` 参数和 `delegation_depth` 决定是否包含 Agent 工具。不需要 stub。 - -### Q: 旧 `SessionActor` (minimal REPL) 要改吗? - -A: 不需要。`SessionActor` 是独立用途的轻量 session,不涉及 LLM 或多 agent。 - ---- - -## 11. 验收标准 - -- [ ] `python -m pulsing.craft agent` 可以启动单个 agent 并交互 -- [ ] Agent 可以使用 `Agent` 工具 spawn sub-agent -- [ ] Sub-agent 完成后,结果注入到 parent agent 的对话中 -- [ ] Sub-agent 可以在 `delegation_depth >= max_delegation_depth` 时被拒绝 -- [ ] `python -m pulsing.craft fleet --agents lead,coder` 启动两个 agent -- [ ] Agent A 可以通过 `MessageClusterAgent` 向 Agent B 发消息 -- [ ] `/agents` 命令可以列出集群中的 agent -- [ ] `/send coder "write a test"` 可以向指定 agent 发消息并等待回复 -- [ ] 所有现有测试通过 (或等价更新后通过) -- [ ] `pcraft` / `pulsing craft` CLI 正常工作 diff --git a/docs/design/craft-npc-refactor.md b/docs/design/craft-npc-refactor.md deleted file mode 100644 index 6a99b6719..000000000 --- a/docs/design/craft-npc-refactor.md +++ /dev/null @@ -1,830 +0,0 @@ -# Craft 重构:让 Pulsing 做 Pulsing 的事,Craft 只做游戏隐喻 - -> **核心洞察**:Pulsing 本身就是一个分布式 actor 系统,已内置 actor spawn、gossip 发现、跨节点 RPC、进程隔离、流式传输、supervision 重启、以及 `schedule_self` 尾递归 actor 模式。HubActor 用 600 行代码重新发明了这些能力。重构的本质不是"修 HubActor",而是**删掉它,让 NPC 直接作为 Pulsing actor 存在,用 self-messaging 实现自主行为链**。 -> -> **给实现 AI 的指令**:先通读 `llms.binding.md` 理解 Pulsing API,再动代码。 - ---- - -## 1. Pulsing 已经提供了什么 - -``` -┌─────────────────────────────────────────────────────────┐ -│ Pulsing 内置能力 │ -│ │ -│ @pul.remote → actor 定义、自动 proxy、gossip 注册 │ -│ spawn(name=) → 创建 actor、注册到集群 │ -│ resolve(name, cls=) → 跨节点发现 actor │ -│ all_named_actors() → 列出集群中所有 actor │ -│ spawn(new_process=True) → OS 级进程隔离 │ -│ async def → yield → 自动流式 RPC 响应 │ -│ restart_policy → actor 挂了自动复活 │ -│ init(addr, seeds) → 加入/创建 gossip 集群 │ -│ shutdown() → 离开集群 │ -│ mailbox → 自动串行化消息处理 │ -│ schedule_self(msg, delay) → actor 给自己发消息 │ -└─────────────────────────────────────────────────────────┘ -``` - -### 1.1 Pulsing → Craft 映射表 - -| Pulsing API | Craft 概念 | 说明 | -|---|---|---| -| `@pul.remote` | NPC 类定义 | Pulsing 自动生成 proxy,注册到 gossip | -| `NPC.spawn(name="guide", public=True)` | summon NPC | Pulsing 自动注册,其他节点可发现 | -| `pul.resolve("craft/ws//guide", cls=NPC)` | 找到 NPC | Pulsing gossip 自动发现 | -| `system.all_named_actors()` | `/look` 和 `/who` | Pulsing 列出所有已注册 actor | -| `pul.spawn(FullToolWorker(), new_process=True)` | 工具沙箱 | Pulsing OS 级进程隔离 | -| `async def → yield` | 流式回复 | Pulsing 自动 `async for` 流式传输 | -| `restart_policy="on_failure"` | NPC 复活 | Pulsing supervision 自动重启 | -| `pul.init(addr=..., seeds=...)` | World wake | 加入/创建 gossip 集群 | -| `pul.shutdown()` | World sleep | 离开集群 | -| **`schedule_self(msg, delay)`** | **NPC 自主行为** | **NPC 给自己发消息,驱动自主工作链** | - -### 1.2 HubActor 做了什么(全是 Pulsing 已有的事) - -| HubActor 做的事 | Pulsing 等价物 | 结论 | -|---|---|---| -| `turn_lock` 串行化 | Pulsing actor mailbox 天然串行 | **多余** | -| `_inbound_agent_messages` 队列 | Pulsing mailbox 自动排队 | **多余** | -| `receive_agent_message` RPC | NPC 方法直接作为 Pulsing RPC | **多余** | -| `CoordinatorRuntime` spawn task | `NPC.spawn(name=...)` | **多余** | -| `ClusterRuntime` resolve + RPC | `pul.resolve()` + 方法调用 | **多余** | -| Coordinator 150ms 轮询等待 | `schedule_self` 自主行为链 | **多余** | -| `call_tool` 工具路由 | NPC 内部方法 | **保留**(craft 特有) | -| `_ensure_worker` / `_respawn_worker` | Pulsing supervision | **可简化** | -| `run_turn` / `run_turn_stream` | NPC 内部方法 | **保留**(LLM turn 是 craft 特有) | - ---- - -## 2. 新架构:Self-Messaging 驱动的自主 NPC - -### 2.1 核心模式:NPC 给自己发消息 - -Pulsing 的 `schedule_self(msg, delay)` 允许 actor 向自己的 mailbox 发送消息。这让 NPC 从"被动等 Player 指令"变成"自主驱动工作链"——这就是"尾递归优化"模式:每个 turn 完成后通过 self-message 触发下一个 turn,不占用调用栈。 - -``` -被动 NPC (HubActor 模式): 自主 NPC (schedule_self 模式): - -Player: "fix all tests" Player: "fix all tests" - ↓ ↓ -NPC: turn 1 — 修一个文件 NPC: turn 1 — 跑 pytest, 发现 3 个失败 - ↓ ↓ _schedule_self(ContinueWork("fix test_a")) -NPC: 回复 "done" NPC: turn 2 — 修 test_a.py - ↑ ↓ _schedule_self(ContinueWork("fix test_b")) -Player 必须再催一次 NPC: turn 3 — 修 test_b.py - ↓ _schedule_self(ContinueWork("fix test_c")) - NPC: turn 4 — 修 test_c.py - ↓ 工作链结束 → 回复 Player - NPC: 回复 "all done" -``` - -### 2.2 分层架构 - -``` -┌──────────────────────────────────────────────────────────┐ -│ Craft 层(薄) │ -│ │ -│ NPC 类 (@pul.remote) │ -│ ├── say(player, msg) → 启动工作链 │ -│ ├── whisper(npc, msg) → 同上 │ -│ ├── _schedule_self(item) → 给自己发消息,接力工作链 │ -│ ├── _process_work_loop() → 尾递归执行引擎 │ -│ ├── _run_one_turn(item) → 跑 LLM turn │ -│ ├── _tool_summon() → NPC.spawn() │ -│ ├── _tool_whisper() → pul.resolve() + .whisper()│ -│ └── who() → 身份卡 │ -│ │ -│ AsyncTurnRunner (LLM 大脑) │ -│ PermissionChecker (权限) SessionStore (对话存储) │ -│ BuddyState (宠物) FullToolWorker (隔离工具) │ -│ REPL (对话界面) │ -│ │ -├──────────────────────────────────────────────────────────┤ -│ Pulsing 层 │ -│ │ -│ Actor Mailbox 串行化所有消息 (say + self-message) │ -│ schedule_self — actor 给自己发消息,驱动自主行为链 │ -│ Remote Spawn / Resolve / RPC / Gossip │ -│ Process Isolation / Streaming / Supervision │ -└──────────────────────────────────────────────────────────┘ -``` - ---- - -## 3. NPC 类设计 - -### 3.0 Self-Messaging 工作链详解 - -``` -say("fix tests") ← Player 调用,进入 Pulsing mailbox - └─ _schedule_self(WorkItem(kind="player_say", content="fix tests")) - └─ 设置 _active_reply_future ← 工作链结束时要回复这个 future - -_process_work_loop 取出 WorkItem: - └─ _run_one_turn: - └─ runner.run_turn("fix tests") - └─ LLM: "我先跑 pytest 看看" - └─ Tool: Bash("pytest") - └─ LLM: "3 个失败,先修 test_a" - └─ Tool: Edit("test_a.py", ...) - └─ LLM: "修好了,继续修 test_b" - └─ _schedule_self(ContinueWork("fix test_b")) ← 给自己发消息! - -_process_work_loop 取出 ContinueWork: - └─ _run_one_turn: - └─ runner.run_turn("[continue] fix test_b") - └─ ...修 test_b... - └─ _schedule_self(ContinueWork("fix test_c")) - -_process_work_loop 取出 ContinueWork: - └─ _run_one_turn: - └─ ...修 test_c... - └─ LLM: "全部完成" - └─ 没有更多 self-message → _work_queue 空了 - └─ _maybe_reply(): 检查 _work_queue.empty() → 是 - └─ _active_reply_future.set_result(result) ← 回复最初调用 say() 的人 -``` - -### 3.1 WorkItem 定义 - -```python -# 文件: python/pulsing/craft/npc.py (新增,放在 NPC 类之前) - -from dataclasses import dataclass, field -import uuid - -@dataclass -class WorkItem: - """工作队列中的一项——可以来自外部 (say/whisper) 或内部 (self-message)。""" - kind: str # "player_say" | "npc_whisper" | "continue_work" | "summon_notification" - from_agent: str = "" - content: str = "" - id: str = field(default_factory=lambda: uuid.uuid4().hex[:12]) - - def user_text(self) -> str: - """转为 runner.run_turn() 的 user 文本。""" - if self.kind == "player_say": - return self.content - elif self.kind == "npc_whisper": - return f"[{self.from_agent} whispers] {self.content}" - elif self.kind == "continue_work": - return f"[continue] {self.content}" - elif self.kind == "summon_notification": - return self.content # XML - return self.content -``` - -### 3.2 NPC 完整代码 - -```python -# 文件: python/pulsing/craft/npc.py - -import asyncio, uuid, json, logging, os, xml.sax.saxutils as xml_esc -from typing import Any - -import pulsing as pul - -from pulsing.craft.npc_class import get_npc_class -from pulsing.craft.runtime.engine_async import AsyncTurnRunner -from pulsing.craft.runtime.permissions import PermissionChecker -from pulsing.craft.runtime.session_store import SessionStore -from pulsing.craft.runtime.companion_buddy import BuddyState -from pulsing.craft.runtime.constants import ISOLATED_TOOL_NAMES -from pulsing.craft.runtime.remote_tool import tool_result_from_worker_value -from pulsing.craft.payload.full_tool_worker import FullToolWorker -from pulsing.craft.cluster.constants import full_agent_name - -logger = logging.getLogger(__name__) -_ISOLATED_WORKER_NAME = "craft_isolated_tools" - - -@pul.remote -class NPC: - """ - Pulsing actor with LLM brain and self-messaging autonomy. - - Pulsing 提供: gossip 注册、mailbox 串行化、跨节点 RPC、进程隔离、流式响应 - Craft 提供: LLM turn loop、工具系统、权限、session、buddy、self-messaging 工作链 - """ - - def __init__( - self, *, - name: str, workspace_id: str, - npc_class: str = "artisan", personality: str = "", - model: str, provider: str = "anthropic", - api_key: str | None = None, base_url: str | None = None, - max_tokens: int = 8192, - max_summon_depth: int = 3, summon_depth: int = 0, - tool_denylist: list[str] | None = None, - auto_approve: bool = False, prompt_callback: Any | None = None, - sandbox_policy: str = "off", dangerously_disable_sandbox: bool = False, - cwd: str = ".", resume_id: str | None = None, cost_log: bool = True, - ) -> None: - # identity - self._name = name - self._workspace_id = workspace_id - self._cls = get_npc_class(npc_class) - self._personality = (personality or self._cls.default_personality).strip() - - # LLM - self._provider = provider; self._model = model - self._api_key = api_key or os.environ.get( - "OPENAI_API_KEY" if provider == "openai" else "ANTHROPIC_API_KEY") - self._base_url = base_url; self._max_tokens = max_tokens - - # summon - self._max_summon_depth = max_summon_depth - self._summon_depth = summon_depth - self._summoned: dict[str, str] = {} - - # tools - self._tools: dict[str, Any] = {} - self._tool_denylist = set(tool_denylist or ()) - if summon_depth >= max_summon_depth: - self._tool_denylist.add("Summon") - - # permissions - self._checker = PermissionChecker(auto_approve=auto_approve, prompt_callback=prompt_callback) - - # sandbox - self._sandbox_policy = sandbox_policy - self._dangerously_disable_sandbox = dangerously_disable_sandbox - - # session - self._cwd = cwd - if resume_id: - self._session = SessionStore(cwd=cwd, model=model, session_id=resume_id) - self._initial_messages = SessionStore.load_messages(resume_id, cwd) - else: - self._session = SessionStore(cwd=cwd, model=model) - self._initial_messages = [] - - # runner - self._runner: AsyncTurnRunner | None = None - - # === 工作队列 — self-messaging 的载体 === - # say()/whisper() 将任务放入队列,_process_work_loop() 逐条取出执行。 - # 每个 turn 结束后,LLM 可通过 _schedule_self(ContinueWork(...)) - # 向队列发消息触发下一个 turn——这就是"尾递归"模式。 - # summon 完成通知也通过 _schedule_self() 注入。 - self._work_queue: asyncio.Queue[WorkItem] = asyncio.Queue() - self._work_loop: asyncio.Task | None = None - - # === 当前工作链的 reply future === - # say()/whisper() 设置它。工作链最后一个 turn 通过它回复调用者。 - # 当 _work_queue 为空时,说明工作链结束,触发回复。 - self._active_reply_future: asyncio.Future | None = None - - # isolated worker - self._worker_lock = asyncio.Lock() - self._worker_handle: pul.IsolatedSpawnHandle | None = None - self._worker_proxy: pul.ActorProxy | None = None - - # buddy - self._buddy = BuddyState() - self._buddy.set_persona_name(self._name) - - # lifecycle - self._on_start_lock = asyncio.Lock() - self._on_start_done = False - - # prompt - self._system_prompt = self._build_prompt() - - # ═══════════════════════════════════════════ - # Lifecycle - # ═══════════════════════════════════════════ - - async def on_start(self, actor_id) -> None: - async with self._on_start_lock: - if self._on_start_done: return - self._tools = self._build_tools() - self._runner = self._create_runner() - await self._ensure_worker() - self._work_loop = asyncio.create_task(self._process_work_loop()) - self._on_start_done = True - logger.info("NPC %s [%s] awake depth=%s/%s tools=%s", - self._name, self._cls.name, self._summon_depth, - self._max_summon_depth, len(self._tools)) - - async def on_stop(self) -> None: - if self._work_loop: - self._work_loop.cancel() - try: await self._work_loop - except asyncio.CancelledError: pass - if self._worker_handle is not None: - proc = self._worker_handle.process - if proc.returncode is None: proc.terminate() - - # ═══════════════════════════════════════════ - # Self-Messaging — NPC 自主性的核心 - # ═══════════════════════════════════════════ - - async def _schedule_self(self, item: WorkItem) -> None: - """给自己发消息——Pulsing schedule_self 的 Python 等价实现。""" - await self._work_queue.put(item) - - async def _process_work_loop(self) -> None: - """尾递归执行引擎——逐条取出 WorkItem,跑 LLM turn。""" - while True: - item = await self._work_queue.get() - await self._run_one_turn(item) - - async def _run_one_turn(self, item: WorkItem) -> None: - """跑一个 LLM turn。完成后检查队列是否为空——空则回复调用者。""" - try: - result = await self._runner.run_turn(item.user_text()) - self._buddy.on_turn_finished( - ok=result.get("ok", True), - had_tool_calls=any(e.get("kind") == "tool_call" - for e in result.get("events", []))) - # 如果队列空了,说明工作链结束 - if self._work_queue.empty() and self._active_reply_future: - fut = self._active_reply_future - self._active_reply_future = None - if not fut.done(): fut.set_result(result) - except asyncio.CancelledError: - self._fail_reply(asyncio.CancelledError("work cancelled")) - except Exception as e: - logger.exception("NPC %s turn failed", self._name) - self._fail_reply(e) - - def _fail_reply(self, exc: BaseException) -> None: - if self._active_reply_future and not self._active_reply_future.done(): - self._active_reply_future.set_exception(exc) - self._active_reply_future = None - - # ═══════════════════════════════════════════ - # 公网 API — 入口点 - # ═══════════════════════════════════════════ - - async def say(self, from_name: str, message: str, *, - wait: bool = True, timeout: float = 600.0) -> dict[str, Any]: - """Player 对 NPC 说话。启动工作链。""" - body = (message or "").strip() - if not body: return {"ok": False, "error": "empty message"} - item = WorkItem(kind="player_say", from_agent=from_name, content=body) - if wait: - loop = asyncio.get_event_loop() - self._active_reply_future = loop.create_future() - await self._schedule_self(item) - try: return await asyncio.wait_for(self._active_reply_future, timeout=timeout) - except asyncio.TimeoutError: - self._active_reply_future = None - return {"ok": False, "error": f"{self._name} timeout"} - else: - await self._schedule_self(item) - return {"ok": True, "accepted": True} - - async def whisper(self, from_name: str, message: str, *, - wait: bool = True, timeout: float = 600.0) -> dict[str, Any]: - """其他 NPC 对此 NPC 私聊。启动工作链。""" - body = (message or "").strip() - if not body: return {"ok": False, "error": "empty message"} - item = WorkItem(kind="npc_whisper", from_agent=from_name, content=body) - if wait: - loop = asyncio.get_event_loop() - self._active_reply_future = loop.create_future() - await self._schedule_self(item) - try: return await asyncio.wait_for(self._active_reply_future, timeout=timeout) - except asyncio.TimeoutError: - self._active_reply_future = None - return {"ok": False, "error": f"{self._name} timeout"} - else: - await self._schedule_self(item) - return {"ok": True, "accepted": True} - - def who(self) -> dict[str, Any]: - return { - "name": self._name, - "full_name": full_agent_name(self._name, workspace_id=self._workspace_id), - "class": self._cls.name, "class_description": self._cls.description, - "personality": self._personality[:200], "workspace_id": self._workspace_id, - "summon_depth": self._summon_depth, "max_summon_depth": self._max_summon_depth, - "session_id": self._session.session_id, "cwd": self._cwd, - "model": self._model, "provider": self._provider, - "buddy": self._buddy.status_line(), - } - - def get_session_id(self) -> str: - return self._session.session_id - - # ═══════════════════════════════════════════ - # Tool Backend - # ═══════════════════════════════════════════ - - async def call_tool(self, name: str, kwargs: dict[str, Any]) -> Any: - if name == "Summon": return await self._tool_summon(**kwargs) - if name == "Whisper": return await self._tool_whisper(**kwargs) - if name == "ListNPCs": return await self._tool_list_npcs(**kwargs) - if name in ISOLATED_TOOL_NAMES: return await self._isolated_tool(name, kwargs) - tool = self._tools.get(name) - if tool is None: - from pulsing.craft.runtime.tool_base import ToolResult - return ToolResult(content=f"Unknown tool: {name}", is_error=True) - return await asyncio.to_thread(tool.execute, **kwargs) - - # ═══════════════════════════════════════════ - # Summon — 使用 Pulsing 原生 spawn - # ═══════════════════════════════════════════ - - async def _tool_summon(self, **kwargs: Any) -> Any: - from pulsing.craft.runtime.tool_base import ToolResult - goal = str(kwargs.get("goal") or kwargs.get("task") or "").strip() - if not goal: return ToolResult(content="Summon: goal required.", is_error=True) - npc_class = str(kwargs.get("npc_class") or "artisan").strip() - name = str(kwargs.get("name") or "").strip() or f"sub-{uuid.uuid4().hex[:6]}" - task_id = str(kwargs.get("task_id") or "").strip() or f"s-{uuid.uuid4().hex[:10]}" - - handle = await NPC.spawn( - name=name, workspace_id=self._workspace_id, - npc_class=npc_class, personality=kwargs.get("personality", ""), - model=kwargs.get("model") or self._model, provider=self._provider, - max_summon_depth=self._max_summon_depth, summon_depth=self._summon_depth + 1, - auto_approve=self._checker._auto_approve, sandbox_policy=self._sandbox_policy, - cwd=self._cwd, - ) - self._summoned[task_id] = full_agent_name(name, workspace_id=self._workspace_id) - proxy = pul.ActorProxy(handle.ref, NPC._methods, NPC._async_methods) - asyncio.create_task(self._await_summoned(task_id, goal, proxy, name)) - return ToolResult(content=json.dumps({ - "task_id": task_id, "npc": name, "class": npc_class, - "status": "summoned", "goal": goal, - }, ensure_ascii=False)) - - async def _await_summoned(self, task_id: str, goal: str, proxy: Any, name: str) -> None: - try: - result = await proxy.whisper(from_name=self._name, message=goal, wait=True) - status = "completed" if result.get("ok") else "failed" - text = result.get("assistant_text", "")[:8000] - # ★ 通过 self-message 注入通知,而不是直接修改消息历史 - notif = _format_summon_result(task_id, name, status, text[:2000], text) - await self._schedule_self(WorkItem(kind="summon_notification", content=notif)) - except Exception as e: - notif = _format_summon_result(task_id, name, "failed", str(e)[:2000], "") - await self._schedule_self(WorkItem(kind="summon_notification", content=notif)) - finally: - self._summoned.pop(task_id, None) - - # ═══════════════════════════════════════════ - # Whisper — 使用 Pulsing 原生 resolve + RPC - # ═══════════════════════════════════════════ - - async def _tool_whisper(self, **kwargs: Any) -> Any: - from pulsing.craft.runtime.tool_base import ToolResult - target = str(kwargs.get("to") or kwargs.get("npc") or "").strip() - message = str(kwargs.get("message") or "").strip() - if not target: return ToolResult(content="Whisper: to/npc required.", is_error=True) - if not message: return ToolResult(content="Whisper: message required.", is_error=True) - wait = bool(kwargs.get("wait", True)) - timeout = float(kwargs.get("timeout", 600.0)) - full = full_agent_name(target, workspace_id=self._workspace_id) - try: - peer = await pul.resolve(full, cls=NPC, timeout=min(timeout, 120.0)) - except Exception as e: - return ToolResult(content=f"Cannot find '{target}': {e}", is_error=True) - try: - result = await peer.whisper(from_name=self._name, message=message, - wait=wait, timeout=timeout) - except Exception as e: - return ToolResult(content=f"Whisper failed: {e}", is_error=True) - if wait and isinstance(result, dict): - text = result.get("assistant_text") or result.get("error") or str(result) - return ToolResult(content=text[:8000]) - return ToolResult(content=str(result)) - - async def _tool_list_npcs(self, **kwargs: Any) -> Any: - from pulsing.craft.runtime.tool_base import ToolResult - system = pul.get_system() - try: all_actors = await system.all_named_actors() - except Exception as e: return ToolResult(content=f"Failed: {e}", is_error=True) - ws_prefix = f"craft/ws/{self._workspace_id}/" - lines = [] - for info in all_actors: - path = str(info.get("path", "")) - if path.startswith("actors/"): path = path[7:] - if path.startswith(ws_prefix): - name = path[len(ws_prefix):] - node = str(info.get("node_id", "?"))[:12] - lines.append(f" {name} (node={node})") - if not lines: return ToolResult(content="(no other NPCs)") - return ToolResult(content="NPCs:\n" + "\n".join(lines)) - - # ═══════════════════════════════════════════ - # Isolated Worker - # ═══════════════════════════════════════════ - - async def _isolated_tool(self, name: str, kwargs: dict[str, Any]) -> Any: - from pulsing.craft.runtime.tool_base import ToolResult - last_exc = None - for attempt in range(2): - try: - await self._ensure_worker() - raw = await getattr(self._worker_proxy, name)(**kwargs) - return tool_result_from_worker_value(raw) - except BaseException as e: - last_exc = e - async with self._worker_lock: - await self._respawn_worker(f"recover after {name}") - return ToolResult(content=f"Tool failed: {last_exc!r}", is_error=True) - - async def _ensure_worker(self) -> None: - async with self._worker_lock: - if self._worker_handle is not None and self._worker_handle.process.returncode is None: - return - await self._respawn_worker("worker missing") - - async def _respawn_worker(self, reason: str) -> None: - if self._worker_handle is not None: - proc = self._worker_handle.process - if proc.returncode is None: - proc.terminate() - try: await asyncio.wait_for(proc.wait(), timeout=8.0) - except asyncio.TimeoutError: proc.kill(); await proc.wait() - self._worker_handle = None; self._worker_proxy = None - logger.info("NPC %s: spawning worker (%s)", self._name, reason) - h = await pul.spawn( - FullToolWorker(sandbox_policy=self._sandbox_policy, - dangerously_disable_sandbox=self._dangerously_disable_sandbox), - new_process=True, name=_ISOLATED_WORKER_NAME, public=False, restart_policy="never", - ) - if not isinstance(h, pul.IsolatedSpawnHandle): - raise TypeError("expected IsolatedSpawnHandle") - self._worker_handle = h - self._worker_proxy = pul.ActorProxy(h.ref, FullToolWorker._methods, FullToolWorker._async_methods) - - # ═══════════════════════════════════════════ - # Helpers - # ═══════════════════════════════════════════ - - def _build_prompt(self) -> str: - cls = self._cls - parts = [ - f"You are NPC '{self._name}' in world '{self._workspace_id}'.", - f"Class: {cls.name} — {cls.description}", - f"Personality: {self._personality}", - "", - "You live in a game-like dev world. The Player may /say things to you.", - "You can Summon NPCs to delegate work and Whisper to coordinate.", - "Use tools to work on tasks autonomously. When a task requires multiple steps,", - "complete each step, then the system will continue to the next automatically.", - "You don't need to finish everything in one turn — use tools step by step.", - "", - f"Working directory: {self._cwd}", - ] - if cls.prompt_extra: parts.append(f"\n{cls.prompt_extra}") - return "\n".join(parts) - - def _create_runner(self) -> AsyncTurnRunner: - runner = AsyncTurnRunner( - self, self._tools, self._checker, - provider=self._provider, model=self._model, - api_key=self._api_key, base_url=self._base_url, - system_prompt=self._system_prompt, - session_store=self._session, - stream_assistant=False, text_stream_callback=None, - usage_observer=self._on_usage if self._cost_log_enabled else None, - ) - if self._initial_messages: runner.set_messages(self._initial_messages) - return runner - - def _build_tools(self) -> dict[str, Any]: - from pulsing.craft.npc_tools import SummonTool, WhisperTool, ListNPCsTool - from pulsing.craft.runtime.tools_pkg import ( - ReadTool, GlobTool, GrepTool, EditTool, WriteTool, BashTool, - MemoryAppendTool, MemorySearchTool, SkillRunTool, SkillsListTool, - McpCatalogTool, FetchUrlTool, AskUserQuestionTool, BuddyStatusTool, - EnterDreamModeTool, ExitDreamModeTool, EnterPlanModeTool, ExitPlanModeTool, - ) - all_tools = { - "Read": ReadTool, "Glob": GlobTool, "Grep": GrepTool, - "Edit": EditTool, "Write": WriteTool, "Bash": BashTool, - "MemoryAppend": lambda: MemoryAppendTool(self._cwd), - "MemorySearch": lambda: MemorySearchTool(self._cwd), - "SkillRun": lambda: SkillRunTool(self._cwd), "SkillsList": SkillsListTool, - "McpCatalog": McpCatalogTool, "FetchUrl": FetchUrlTool, - "AskUserQuestion": AskUserQuestionTool, - "BuddyStatus": lambda: BuddyStatusTool(self._buddy), - "EnterDreamMode": lambda: EnterDreamModeTool(self._checker), - "ExitDreamMode": lambda: ExitDreamModeTool(self._checker), - "EnterPlanMode": lambda: EnterPlanModeTool(self._checker), - "ExitPlanMode": lambda: ExitPlanModeTool(self._checker), - "Summon": SummonTool, "Whisper": WhisperTool, - "ListNPCs": lambda: ListNPCsTool(self._workspace_id), - } - allow = set(self._cls.default_tools) - forbid = set(self._cls.forbidden_tools) | self._tool_denylist - tools = {} - for name, factory in all_tools.items(): - if name in forbid: continue - if allow and name not in allow: continue - tools[name] = factory() if callable(factory) else factory() - return tools - - def _on_usage(self, usage: dict[str, int]) -> None: - try: - from pulsing.craft.runtime.cost_log import append_usage - append_usage(self._session.session_dir, self._session.session_id, - model=self._model, usage=usage) - except Exception: pass - - @property - def _cost_log_enabled(self) -> bool: - return True # 后续可配置 - - -def _format_summon_result(task_id: str, npc_name: str, status: str, - summary: str, result: str) -> str: - e = xml_esc.escape - parts = [ - "", - f"{e(task_id)}", - f"{e(npc_name)}", - f"{e(status)}", - f"{e(summary)}", - ] - if result: parts.append(f"{e(result)}") - parts.append("") - return "\n".join(parts) -``` - ---- - -## 4. 支持文件 - -### 4.1 `npc_class.py` - -```python -from dataclasses import dataclass, field - -@dataclass -class NPCClass: - name: str; description: str - default_personality: str = "" - prompt_extra: str = "" - default_tools: list[str] = field(default_factory=list) - forbidden_tools: list[str] = field(default_factory=list) - -_registry: dict[str, NPCClass] = {} - -def register(cls): _registry[cls.name] = cls; return cls -def get_npc_class(name): return _registry.get(name, _registry["artisan"]) -def list_classes(): return sorted(_registry.keys()) - -register(NPCClass(name="artisan", - description="工匠 — 读写文件、执行命令。默认 NPC。", - default_personality="helpful and precise", - default_tools=["Read","Glob","Grep","Edit","Write","Bash", - "MemoryAppend","MemorySearch","SkillRun","SkillsList", - "McpCatalog","FetchUrl","AskUserQuestion","BuddyStatus", - "EnterDreamMode","ExitDreamMode","EnterPlanMode","ExitPlanMode"])) - -register(NPCClass(name="quest_giver", - description="任务发布者 — 召唤 NPC、分配任务、协调团队。", - default_personality="organized and strategic", - prompt_extra="You can Summon NPCs to delegate and Whisper to coordinate.", - default_tools=["Summon","Whisper","ListNPCs","Read","Glob","Grep", - "MemoryAppend","MemorySearch","AskUserQuestion","BuddyStatus", - "EnterPlanMode","ExitPlanMode","SkillsList","McpCatalog"])) - -register(NPCClass(name="scholar", - description="学者 — 只读工具,代码审查和分析。", - default_personality="critical and detail-oriented", - default_tools=["Read","Glob","Grep","MemoryAppend","MemorySearch", - "AskUserQuestion","BuddyStatus","SkillsList","McpCatalog","FetchUrl", - "EnterDreamMode","ExitDreamMode"], - forbidden_tools=["Edit","Write","Bash"])) - -register(NPCClass(name="oracle", - description="先知 — 信息收集,FetchUrl 和搜索。", - default_personality="curious and resourceful", - default_tools=["Read","Glob","Grep","FetchUrl","MemoryAppend","MemorySearch", - "AskUserQuestion","BuddyStatus","SkillsList","McpCatalog"], - forbidden_tools=["Edit","Write","Bash","Summon","Whisper"])) -``` - -### 4.2 `npc_tools.py` - -```python -from typing import Any -from pulsing.craft.runtime.tool_base import Tool, ToolResult -from pulsing.craft.runtime.tools_pkg import _json_schema_object - -class SummonTool(Tool): - @property - def name(self): return "Summon" - @property - def description(self): return "Summon another NPC to help." - @property - def input_schema(self): return _json_schema_object({ - "goal": {"type": "string"}, - "npc_class": {"type": "string", "enum": ["artisan","scholar","oracle","quest_giver"]}, - "name": {"type": "string"}, "personality": {"type": "string"}, - "task_id": {"type": "string"}, - }, ["goal"]) - def is_read_only(self): return True - def execute(self, **kw): raise RuntimeError("via NPC._tool_summon") - -class WhisperTool(Tool): - @property - def name(self): return "Whisper" - @property - def description(self): return "Send a message to another NPC." - @property - def input_schema(self): return _json_schema_object({ - "to": {"type": "string"}, "npc": {"type": "string"}, - "message": {"type": "string"}, - "wait": {"type": "boolean"}, "timeout": {"type": "number"}, - }, ["message"]) - def is_read_only(self): return True - def execute(self, **kw): raise RuntimeError("via NPC._tool_whisper") - -class ListNPCsTool(Tool): - def __init__(self, workspace_id): self._ws = workspace_id - @property - def name(self): return "ListNPCs" - @property - def description(self): return "List NPCs in this world." - @property - def input_schema(self): return _json_schema_object({}, []) - def is_read_only(self): return True - def execute(self, **kw): raise RuntimeError("via NPC._tool_list_npcs") -``` - ---- - -## 5. 与 HubActor 对比 - -| 维度 | HubActor | NPC | -|---|---|---| -| Actor 注册 | `HubActor.spawn(name=, public=True)` | `NPC.spawn(name=, public=True)` — **一样** | -| 消息串行化 | `turn_lock` | Pulsing mailbox + 内部 work queue | -| 跨节点通信 | `ClusterRuntime` → `pul.resolve` → `receive_agent_message` | `pul.resolve` → `peer.whisper()` — **直接 RPC** | -| 召唤 NPC | `CoordinatorRuntime` → asyncio.Task | `NPC.spawn()` — **Pulsing 原生** | -| **自主行为** | **Coordinator 150ms 轮询** | **`_schedule_self` 尾递归工作链** | -| summon 通知注入 | `enqueue_coordinator_notification` → 等 hub drain | `_schedule_self(WorkItem)` — 作为普通 turn 执行 | -| 进程隔离 | `pul.spawn(new_process=True)` | `pul.spawn(new_process=True)` — **一样** | -| 代码量 | ~600 行 + coordinator ~250 行 | ~300 行 | - ---- - -## 6. 文件变更 - -### 删除(Claude Code 遗留) -``` -runtime/hub_actor.py, runtime/coordinator.py, runtime/cluster_tools.py, -runtime/split_tools.py, runtime/run_hub.py, runtime/slash_hub.py, -runtime/tui_app.py, cluster/messaging.py, -cluster/run_agent.py, cluster/run_cluster.py, cluster/run_ctl.py, -cluster/controller_repl.py, cluster/cli_common.py -``` - -### 新增 -``` -npc.py ★ 核心 NPC 类 (~300 行) -npc_class.py ★ NPC 职业定义 -npc_tools.py ★ Summon/Whisper/ListNPCs 工具 schema -repl_npc.py ★ NPC 对话 REPL -``` - -### 保留(Pulsing 不提供的) -``` -runtime/engine_async.py, engine.py, tool_base.py, tools_impl.py, tools_pkg.py, -permissions.py, sandbox.py, sandbox_manager.py, -session_store.py, memory_kairos.py, companion_buddy.py, -compact.py, llm_client.py, cost_log.py, cost_estimate.py, -mcp_catalog.py, skills_registry.py, stubs_info.py, remote_tool.py, constants.py, -payload/full_tool_worker.py, payload/tool_actor.py, -cluster/constants.py, cluster/discovery.py, -workspace/, commands/ -``` - ---- - -## 7. 实现步骤 - -1. `npc_class.py` — 无依赖 -2. `npc_tools.py` — 依赖 tool_base + tools_pkg -3. `npc.py` + `WorkItem` — 核心,依赖以上 + engine_async 等 -4. `repl_npc.py` — NPC 对话 REPL -5. 更新 `helpers.py` — `spawn_npc` 改用 `NPC.spawn` -6. 更新 `commands/npc.py` — `run_say` 改用 `peer.say()` -7. 简化 `__main__.py` — 去掉 hub/cluster/agent/ctl -8. 删除遗留文件 + 更新测试 - ---- - -## 8. 验收标准 - -- [ ] `pcraft init && pcraft wake` — World 启动 -- [ ] `pcraft npc summon coder --class artisan` — summon NPC -- [ ] `pcraft npc who` — 列出 NPC(使用 `all_named_actors()`) -- [ ] `pcraft npc say guide "fix tests"` — Player 对 NPC 说话 -- [ ] NPC 使用 Summon 工具召唤其他 NPC(使用 `NPC.spawn()`) -- [ ] NPC 使用 Whisper 工具与其他 NPC 通信(使用 `pul.resolve()` + RPC) -- [ ] **NPC 通过 `_schedule_self` 自主驱动多 turn 工作链** -- [ ] summon 完成通知通过 `_schedule_self` 注入(而非 HubActor 的 enqueue + drain) -- [ ] Summon depth 限制生效 -- [ ] 不同 class 的 NPC 有不同的工具集 -- [ ] `pcraft sleep` — World 休眠 diff --git a/docs/design/forge-codex-parity.md b/docs/design/forge-codex-parity.md deleted file mode 100644 index a6f33fa24..000000000 --- a/docs/design/forge-codex-parity.md +++ /dev/null @@ -1,3 +0,0 @@ -# 已归档 - -该文档已从公开文档站移除。Forge 对外说明见 [`docs/src/forge/`](../src/forge/);工程细节见 [`docs/src/design/forge/engineering.zh.md`](../src/design/forge/engineering.zh.md)。 diff --git a/docs/design/forge-craft-architecture.md b/docs/design/forge-craft-architecture.md deleted file mode 100644 index 78b7d9c9c..000000000 --- a/docs/design/forge-craft-architecture.md +++ /dev/null @@ -1,3 +0,0 @@ -# 已迁移 - -→ [`docs/src/design/forge/craft-architecture.zh.md`](../src/design/forge/craft-architecture.zh.md) diff --git a/docs/design/forge-naming.md b/docs/design/forge-naming.md deleted file mode 100644 index cc76e84d0..000000000 --- a/docs/design/forge-naming.md +++ /dev/null @@ -1,3 +0,0 @@ -# 已迁移 - -→ [`docs/src/design/forge/naming.zh.md`](../src/design/forge/naming.zh.md) diff --git a/docs/design/forge-session-repl.md b/docs/design/forge-session-repl.md deleted file mode 100644 index 533d8fb49..000000000 --- a/docs/design/forge-session-repl.md +++ /dev/null @@ -1,3 +0,0 @@ -# 已迁移 - -→ [`docs/src/design/forge/session-repl.zh.md`](../src/design/forge/session-repl.zh.md) diff --git a/docs/design/pulsing-forge.md b/docs/design/pulsing-forge.md deleted file mode 100644 index c0302892a..000000000 --- a/docs/design/pulsing-forge.md +++ /dev/null @@ -1,3 +0,0 @@ -# 已迁移 - -→ [`docs/src/design/forge/engineering.zh.md`](../src/design/forge/engineering.zh.md) diff --git a/docs/forge/README.md b/docs/forge/README.md deleted file mode 100644 index 2fb269012..000000000 --- a/docs/forge/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# 文档已迁移 - -Forge 文档已并入 Pulsing 官方文档站点结构: - -| 内容 | 新路径 | -|------|--------| -| **用户指南(Forge 章节)** | [`docs/src/forge/`](../src/forge/) | -| **设计与实现** | [`docs/src/design/forge/`](../src/design/forge/) | -| **包内 README(API 速查)** | [`python/pulsing/forge/README.md`](../../python/pulsing/forge/README.md) | - -本地预览:`cd docs && uv run mkdocs serve` → 导航 **Pulsing Forge**。 diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 85462eb42..17d4fd482 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -97,7 +97,6 @@ plugins: User Guides: 用户指南 Architecture & Design: 架构与设计 Complete Reference: 完整参考 - LLM Inference: LLM 推理 Distributed Agents: 分布式 Agent Ray + Pulsing: Ray + Pulsing User Guide: 用户指南 @@ -133,23 +132,8 @@ plugins: HTTP2 Transport: HTTP2 传输 TensorMessage Transport: TensorMessage 快速传输 System Actors: System Actor 机制 - Load Sync: 负载同步 AS Actor Decorator: AS Actor 装饰器 Communication Evolution: 集群内通信技术演进 - Pulsing Forge: Pulsing Forge - Core Architecture: 核心架构 - Getting Started: 快速开始 - Concepts: 核心概念 - Abstractions: 抽象模型 - Tools (32): 工具清单 - Deployment: Pulsing 部署 - Pulsing Integration: Pulsing 集成 - Forge: Forge 设计 - Engineering: 工程说明 - Craft Architecture: Craft 一体化 - Testing: 测试体系 - Naming: 命名规范 - Session REPL: Session REPL - mkdocstrings: handlers: python: @@ -172,7 +156,6 @@ nav: - First Actor: quickstart/index.md - Actor Patterns: quickstart/patterns.md - Cluster Setup: quickstart/cluster_networking.md - - LLM Inference: quickstart/llm_inference.md - Distributed Agents: quickstart/agent.md - Ray + Pulsing: quickstart/migrate_from_ray.md - Core Concepts: @@ -197,14 +180,6 @@ nav: - Ping-Pong: examples/ping_pong.md - Distributed Counter: examples/distributed_counter.md - Subprocess: examples/subprocess.md - - Pulsing Forge: - - Overview: forge/index.md - - Getting Started: forge/getting-started.md - - Concepts: forge/concepts.md - - Abstractions: forge/abstractions.md - - Tools (32): forge/tools.md - - Deployment: forge/deployment.md - - Pulsing Integration: forge/pulsing-integration.md - API Reference: - API Overview: api/overview.md - Complete Reference: api_reference.md @@ -221,20 +196,12 @@ nav: - Node Discovery: design/node-discovery.md - HTTP2 Transport: design/http2-transport.md - Actor Addressing: design/actor-addressing.md - - Load Sync: design/load_sync.md - Implementation: - AS Actor Decorator: design/as-actor-decorator.md - TensorMessage Transport: design/tensor-message-transport.md - System Actors: design/system-actors.md - Communication Evolution: design/cluster-communication-evolution.md - Out-Cluster Connect: design/out-cluster-connect.md - - Forge: - - Core Architecture: design/forge/core-architecture.md - - Engineering: design/forge/engineering.md - - Craft Architecture: design/forge/craft-architecture.md - - Testing: design/forge/testing.md - - Naming: design/forge/naming.md - - Session REPL: design/forge/session-repl.md extra: generator: false diff --git a/docs/overrides/home.html b/docs/overrides/home.html index 2293663e1..989a69a81 100644 --- a/docs/overrides/home.html +++ b/docs/overrides/home.html @@ -1,936 +1,3 @@ {% extends "main.html" %} -{% block tabs %} - {{ super() }} - - - - - - -
-
-
- - {% if config.theme.language == "zh" %} -

分布式 AI 系统的通信骨干

-

Actor 运行时。流式优先。零依赖。内置发现。

- {% else %} -

Backbone for Distributed AI Systems

-

Actor runtime. Streaming-first. Zero dependencies. Built-in discovery.

- {% endif %} -
- -
-
-
- - -
-
- {% if config.theme.language == "zh" %} -

核心特性

-

构建分布式 AI 系统所需的一切,零外部依赖

- {% else %} -

Core Features

-

Everything you need to build distributed AI systems, with zero external dependencies

- {% endif %} -
-
- 🚀 - {% if config.theme.language == "zh" %} -

零外部依赖

-

纯 Rust + Tokio 实现,无需 etcd、NATS 或 Consul。随处部署,占用资源极少。

- {% else %} -

Zero External Dependencies

-

Pure Rust + Tokio implementation. No etcd, NATS, or Consul required. Deploy anywhere with minimal footprint.

- {% endif %} -
-
- 🔍 - {% if config.theme.language == "zh" %} -

SWIM 协议发现

-

内置基于 Gossip 的节点发现和故障检测。节点自动相互发现并组建集群。

- {% else %} -

SWIM Protocol Discovery

-

Built-in gossip-based node discovery and failure detection. Nodes automatically find each other and form clusters.

- {% endif %} -
-
- 🌐 - {% if config.theme.language == "zh" %} -

位置透明

-

ActorRef 支持统一访问本地和远程 Actor,无论 Actor 在哪里运行,API 保持一致。

- {% else %} -

Location Transparent

-

ActorRef supports unified access to local and remote actors. Same API regardless of where actors run.

- {% endif %} -
-
- 🔄 - {% if config.theme.language == "zh" %} -

流式消息

-

原生支持流式请求和响应,非常适合 LLM Token 生成和实时数据处理。

- {% else %} -

Streaming Messages

-

Native support for streaming requests and responses. Perfect for LLM token generation and real-time data processing.

- {% endif %} -
-
- 🐍 - {% if config.theme.language == "zh" %} -

Python 优先

-

通过 PyO3 提供完整的 Python API。使用 @remote 装饰器将任何类转换为分布式 Actor。

- {% else %} -

Python First

-

Full Python API via PyO3. Use the @remote decorator to turn any class into a distributed actor.

- {% endif %} -
-
- ⚡ - {% if config.theme.language == "zh" %} -

高性能

-

基于 Tokio 异步运行时和 HTTP/2 传输。高效处理数千个并发 Actor。

- {% else %} -

High Performance

-

Built on Tokio async runtime with HTTP/2 transport. Handle thousands of concurrent actors efficiently.

- {% endif %} -
-
-
-
- - -
-
-

{% if config.theme.language == "zh" %}快速开始{% else %}Quick Start{% endif %}

-
-
-
1
-
-

{% if config.theme.language == "zh" %}安装 Pulsing{% else %}Install Pulsing{% endif %}

-
-
# Install from source
-pip install maturin
-maturin develop
-
-# Or using uv
-uv pip install -e .
-
-
-
-
-
2
-
-

{% if config.theme.language == "zh" %}创建你的第一个 Actor{% else %}Create Your First Actor{% endif %}

-
-
import pulsing as pul
-
-@pul.remote
-class Calculator:
-    def __init__(self, initial: int = 0):
-        self.value = initial
-
-    def add(self, n: int) -> int:
-        self.value += n
-        return self.value
-
-    def get(self) -> int:
-        return self.value
-
-
-
-
-
3
-
-

{% if config.theme.language == "zh" %}运行它{% else %}Run It{% endif %}

-
-
import asyncio
-
-async def main():
-    await pul.init()
-
-    calc = await Calculator.spawn(initial=100)
-
-    result = await calc.add(50)   # 150
-    result = await calc.add(25)   # 175
-    value = await calc.get()      # 175
-
-    print(f"Final value: {value}")
-    await pul.shutdown()
-
-asyncio.run(main())
-
-
-
-
-
-
- - -
-
- {% if config.theme.language == "zh" %} -

性能表现

-

为高吞吐量分布式计算而生

- {% else %} -

Performance

-

Built for high-throughput distributed computing

- {% endif %} -
-
-
100K+
-
{% if config.theme.language == "zh" %}消息/秒 (本地){% else %}Messages/sec (local){% endif %}
-
-
-
<1ms
-
{% if config.theme.language == "zh" %}本地延迟 (P99){% else %}Local latency (P99){% endif %}
-
-
-
0
-
{% if config.theme.language == "zh" %}外部依赖{% else %}External dependencies{% endif %}
-
-
-
~10MB
-
{% if config.theme.language == "zh" %}内存占用{% else %}Memory footprint{% endif %}
-
-
-

{% if config.theme.language == "zh" %}* 基准测试在 Apple M2 MacBook Air 上进行。结果可能因工作负载和硬件而异。{% else %}* Benchmarks measured on Apple M2 MacBook Air. Results may vary based on workload and hardware.{% endif %}

-
-
- - -
-
-

{% if config.theme.language == "zh" %}应用场景{% else %}Use Cases{% endif %}

-
-
-
🤖
- {% if config.theme.language == "zh" %} -

LLM 推理服务

-

构建可扩展的 LLM 推理后端,支持流式 Token 生成。原生集成 Transformers、vLLM 和 MLX。

- {% else %} -

LLM Inference Services

-

Build scalable LLM inference backends with streaming token generation. Native integration with Transformers, vLLM, and MLX.

- {% endif %} -
-
-
🔀
- {% if config.theme.language == "zh" %} -

增强 Ray 通信

-

为 Ray Actor 增加流式、发现和跨集群通信能力。Ray 负责调度,Pulsing 负责通信。

- {% else %} -

Enhance Ray Communication

-

Add streaming, discovery, and cross-cluster calls to Ray actors. Ray handles scheduling, Pulsing handles communication.

- {% endif %} -
-
-
☸️
- {% if config.theme.language == "zh" %} -

Kubernetes 原生

-

专为云原生部署设计。服务发现与 K8s Service IP 和滚动更新无缝配合。

- {% else %} -

Kubernetes Native

-

Designed for cloud-native deployments. Service discovery works seamlessly with K8s Service IPs and rolling updates.

- {% endif %} -
-
-
-
- - -
-
-
- {% if config.theme.language == "zh" %} -

为什么选择 Pulsing?

-

- Pulsing 旨在填补重量级分布式系统(如 Ray)和简单异步编程之间的空白。 - 它提供了恰到好处的基础设施来构建分布式 AI 应用,而无需复杂的外部协调服务。 - Actor 模型让分布式状态推理变得简单,而 SWIM 协议确保了自动的集群管理。 -

- 学习 Actor 模型 → - {% else %} -

Why Pulsing?

-

- Pulsing was created to fill the gap between heavyweight distributed systems (like Ray) and simple async programming. - It provides just enough infrastructure for building distributed AI applications without the complexity of external coordination services. - The Actor model makes reasoning about distributed state simple, while the SWIM protocol ensures automatic cluster management. -

- Learn the Actor Model → - {% endif %} -
-
-
- - -
-
-
-
- {% if config.theme.language == "zh" %} -

位置透明的消息传递

-

- 无需知道 Actor 的物理位置即可发送消息。 - Pulsing 使用高效的 HTTP/2 传输自动在集群中路由消息。 -

-

- Actor 可以是本地或远程的 - 你的代码保持不变。从单节点扩展到分布式部署,无需更改任何应用逻辑。 -

- 了解更多 → - {% else %} -

Location Transparent Messaging

-

- Send messages to actors without knowing their physical location. - Pulsing automatically routes messages across the cluster using efficient HTTP/2 transport. -

-

- Actors can be local or remote - your code stays the same. Scale from single-node to distributed - deployment without changing a line of application logic. -

- Learn More → - {% endif %} -
-
-
-
# Node 1 - Start seed node with public actor
-config = SystemConfig.with_addr("0.0.0.0:8000")
-system = await create_actor_system(config)
-await system.spawn(Worker(), "worker", public=True)
-
-# Node 2 - Find and use remote actor
-config = SystemConfig.with_addr("0.0.0.0:8001") \
-    .with_seeds(["192.168.1.1:8000"])
-system = await create_actor_system(config)
-
-worker = await system.find("worker")
-result = await worker.process(data)  # Same API!
-
-
-
-
-
- - -
-
-
-
- {% if config.theme.language == "zh" %} -

自动集群发现

-

- 内置 SWIM 协议实现自动节点发现和故障检测。 - 无需外部协调服务 - 节点自动相互发现并组建集群。 -

-

- 基于 Gossip 的协议以最小的网络开销确保集群一致性。 - 节点优雅地加入和离开,自动进行状态协调。 -

- 了解更多 → - {% else %} -

Automatic Cluster Discovery

-

- Built-in SWIM protocol enables automatic node discovery and failure detection. - No external coordination service required - nodes find each other and form clusters automatically. -

-

- Gossip-based protocol ensures consistency across the cluster with minimal network overhead. - Nodes join and leave gracefully with automatic state reconciliation. -

- Learn More → - {% endif %} -
-
-
-
# Kubernetes deployment - just configure Service IP
-config = SystemConfig.with_addr("0.0.0.0:8080") \
-    .with_seeds(["actor-cluster.svc:8080"])
-
-# Nodes automatically discover each other
-# via K8s load balancing + SWIM protocol
-system = await create_actor_system(config)
-
-# Monitor cluster health
-members = await system.get_members()
-print(f"Cluster size: {len(members)}")
-
-
-
-
-
- - -
-
-
-
- {% if config.theme.language == "zh" %} -

LLM 推理就绪

-

- 原生流式支持逐 Token 生成。内置 OpenAI 兼容的 API 路由器, - 与现有工具无缝集成。 -

-

- 集成流行框架,包括 Transformers、vLLM 和 MLX(用于 Apple Silicon)。 - 一条命令即可部署生产级 LLM 服务。 -

- 了解更多 → - {% else %} -

LLM Inference Ready

-

- Native streaming support for token-by-token generation. Built-in OpenAI-compatible API router - for seamless integration with existing tooling. -

-

- Integrates with popular frameworks including Transformers, vLLM, and MLX (for Apple Silicon). - Deploy production LLM services with a single command. -

- Learn More → - {% endif %} -
-
-
-
# Start OpenAI-compatible Router
-pulsing actor pulsing.serving.Router \
-    --addr 0.0.0.0:8000 \
-    --http_port 8080 --model_name my-llm
-
-# Start vLLM Worker
-pulsing actor pulsing.serving.VllmWorker \
-    --model Qwen/Qwen2.5-0.5B \
-    --addr 0.0.0.0:8001 --seeds 127.0.0.1:8000
-
-# Test with curl
-curl http://localhost:8080/v1/chat/completions \
-  -H "Content-Type: application/json" \
-  -d '{"model": "my-llm", "messages": [...]}'
-
-
-
-
-
- - -
-
- {% if config.theme.language == "zh" %} -

加入社区

-

Pulsing 是开源的、社区驱动的项目。欢迎参与!

- {% else %} -

Join the Community

-

Pulsing is open source and community-driven. Get involved!

- {% endif %} - -
-
- -{% endblock %} - -{% block content %}{% endblock %} -{% block footer %} - {{ super() }} -{% endblock %} +{# Render the documented actor API rather than a separate product landing page. #} diff --git a/docs/src/agent/index.md b/docs/src/agent/index.md index cf92b295c..841099b88 100644 --- a/docs/src/agent/index.md +++ b/docs/src/agent/index.md @@ -24,13 +24,12 @@ For building multi-agent applications from scratch, use Pulsing's native `@agent ```python import pulsing as pul -from pulsing.agent import agent, llm, list_agents +from pulsing.agent import agent, list_agents @agent(role="Researcher", goal="Deep analysis") class Researcher: async def analyze(self, topic: str) -> str: - client = await llm() - return await client.ainvoke(f"Analyze: {topic}") + return f"Received topic: {topic}" await pul.init() try: diff --git a/docs/src/agent/index.zh.md b/docs/src/agent/index.zh.md index 68a0d711d..63f37a812 100644 --- a/docs/src/agent/index.zh.md +++ b/docs/src/agent/index.zh.md @@ -24,13 +24,12 @@ Pulsing 原生支持主流 Agent 框架,让您的应用轻松从单进程扩 ```python import pulsing as pul -from pulsing.agent import agent, llm, list_agents +from pulsing.agent import agent, list_agents @agent(role="研究员", goal="深入分析") class Researcher: async def analyze(self, topic: str) -> str: - client = await llm() - return await client.ainvoke(f"分析: {topic}") + return f"收到主题: {topic}" await pul.init() try: diff --git a/docs/src/agent/native.md b/docs/src/agent/native.md index fc49091d3..32f18d38a 100644 --- a/docs/src/agent/native.md +++ b/docs/src/agent/native.md @@ -1,236 +1,42 @@ -# Pulsing Native Agent +# Actor Metadata Helpers -Pulsing provides a lightweight native agent toolkit for building multi-agent applications, fully compatible with the Actor model. +`pulsing.agent` retains a small set of actor helpers: -## Design Philosophy - -**Simple and transparent.** - -- `@agent` = `@remote` + metadata (no magic) -- Metadata for visualization/debugging, not auto-prompt injection -- Full control over LLM calls and conversation flow - -## Core API - -### `@agent` Decorator - -The `@agent` decorator is equivalent to `@remote`, but attaches metadata for visualization and debugging: - -```python -import pulsing as pul -from pulsing.agent import agent, llm, get_agent_meta, list_agents - -# @pul.remote: Basic Actor -@pul.remote -class Worker: - async def work(self): - return "done" - -# @agent: Actor with metadata -@agent(role="Researcher", goal="Deep analysis", domain="AI") -class Researcher: - async def analyze(self, topic: str) -> str: - client = await llm() - resp = await client.ainvoke(f"Analyze: {topic}") - return resp.content -``` - -### Metadata Access - -```python -await pul.init() -try: - r = await Researcher.spawn(name="researcher") - - # Get metadata by name - meta = get_agent_meta("researcher") - print(meta.role) # "Researcher" - print(meta.goal) # "Deep analysis" - print(meta.tags) # {"domain": "AI"} - - # List all agents - for name, meta in list_agents().items(): - print(f"{name}: {meta.role}") -finally: - await pul.shutdown() -``` - -### `@pul.remote` vs `@agent` - -| Feature | `@pul.remote` | `@agent` | -|---------|---------------|----------| -| Function | Actor wrapper | Actor wrapper + metadata | -| Use case | General purpose | Visualization / debugging | -| Metadata | None | `role`, `goal`, `backstory`, `tags` | -| Performance | Baseline | Nearly identical | - -## Runtime Management - -```python -import pulsing as pul - -await pul.init() -try: - # Create and use agents - agent = await MyAgent.spawn(name="agent") - await agent.work() -finally: - await pul.shutdown() -``` - -`runtime()` is still available as a convenience context manager. This page uses explicit `await pul.init()` / `await pul.shutdown()`. - -### Distributed Mode - -```python -# Node A -await pul.init(addr="0.0.0.0:8001") -try: - await JudgeActor.spawn(name="judge") -finally: - await pul.shutdown() - -# Node B (auto-discovers Node A) -await pul.init(addr="0.0.0.0:8002", seeds=["node_a:8001"]) -try: - judge = await JudgeActor.resolve("judge") # Cross-node transparent call - await judge.submit(idea) -finally: - await pul.shutdown() -``` - -## LLM Integration - -```python -from pulsing.agent import llm - -async def analyze(topic: str): - # Get LLM client (lazy-loaded singleton) - client = await llm(temperature=0.8) - resp = await client.ainvoke(f"Analyze: {topic}") - return resp.content -``` - -**Environment Variables:** - -- `OPENAI_API_KEY`: API key (required) -- `OPENAI_BASE_URL`: Custom API endpoint (optional) -- `LLM_MODEL`: Default model name (optional, defaults to `gpt-4o-mini`) - -## Utility Functions - -### JSON Parsing - -```python -from pulsing.agent import parse_json, extract_field - -# Safe JSON parsing with fallback -data = parse_json('{"key": "value"}', default={}) - -# Extract specific field -value = extract_field(response, "answer", default="unknown") -``` - -## Complete Example +- `agent`: `@remote` with role/goal metadata for inspection. +- `runtime`: an async context manager for actor system initialization/shutdown. +- `get_agent_meta`, `list_agents`, and `cleanup`: metadata management. +- `parse_json` and `extract_field`: parsing utilities. ```python import asyncio -import pulsing as pul -from pulsing.agent import agent, llm, parse_json, get_agent_meta, list_agents - -@pul.remote -class Moderator: - """Coordinator using @pul.remote (basic Actor)""" - - def __init__(self, topic: str): - self.topic = topic - self.opinions = [] - - async def collect_opinion(self, agent_name: str, opinion: str): - self.opinions.append({"agent": agent_name, "opinion": opinion}) - return {"received": True} +from pulsing.agent import agent, cleanup, get_agent_meta, runtime - async def summarize(self): - return {"topic": self.topic, "opinions": self.opinions} -@agent(role="Analyst", goal="Provide insights", domain="tech") -class Analyst: - """Analyst using @agent (Actor with metadata)""" +@agent(role="Worker", goal="Count messages") +class Counter: + def __init__(self): + self.value = 0 - def __init__(self, name: str, moderator: str, mock: bool = True): - self.name = name - self.moderator_name = moderator - self.mock = mock + def inc(self): + self.value += 1 + return self.value - async def analyze(self, topic: str): - if self.mock: - opinion = f"[{self.name}] Analysis of {topic}: looks promising" - else: - client = await llm() - resp = await client.ainvoke(f"Brief analysis of: {topic}") - opinion = resp.content - - # Submit to moderator - moderator = await Moderator.resolve(self.moderator_name) - await moderator.collect_opinion(self.name, opinion) - return opinion async def main(): - await pul.init() try: - # Create moderator - moderator = await Moderator.spawn(topic="AI Trends", name="moderator") - - # Create analysts - for i in range(3): - name = f"analyst_{i}" - await Analyst.spawn( - name=name, - moderator="moderator", - mock=True, - name=name, - ) - - # Show agent metadata - print("Registered agents:") - for name, meta in list_agents().items(): - print(f" {name}: {meta.role}") - - # Run analysis - for i in range(3): - analyst = await Analyst.resolve(f"analyst_{i}") - await analyst.analyze("AI Trends") - - # Get summary - result = await moderator.summarize() - print(f"Summary: {result}") + async with runtime(): + counter = await Counter.spawn(name="counter") + print(await counter.inc()) + print(get_agent_meta("counter").role) finally: - await pul.shutdown() - -if __name__ == "__main__": - asyncio.run(main()) -``` - -## Examples - -See `examples/agent/pulsing/` for complete examples: - -| Example | Description | -|---------|-------------| -| `mbti_discussion.py` | Multi-agent discussion with MBTI personalities | -| `parallel_ideas_async.py` | Parallel idea generation with competitive submission | -| `runtime_lifecycle_example.py` | Runtime lifecycle management | + cleanup() -```bash -# Run MBTI discussion (mock mode) -python examples/agent/pulsing/mbti_discussion.py --mock --group-size 6 -# Run parallel ideas (mock mode) -python examples/agent/pulsing/parallel_ideas_async.py --mock --n-ideas 5 +asyncio.run(main()) ``` -## What's Next? +These helpers do not provide an LLM client, prompts, tool execution, or a coding +agent loop. Use application-owned libraries for those capabilities. -- [AutoGen Integration](autogen.md) — Use Pulsing with AutoGen -- [LangGraph Integration](langgraph.md) — Use Pulsing with LangGraph -- [Remote Actors](../guide/remote_actors.md) — Cluster setup +See [Remote Actors](../guide/remote_actors.md) for cluster setup and +`examples/agent/pulsing/runtime_lifecycle_example.py` for lifecycle examples. diff --git a/docs/src/agent/native.zh.md b/docs/src/agent/native.zh.md index 5abb8db64..cb9546bc9 100644 --- a/docs/src/agent/native.zh.md +++ b/docs/src/agent/native.zh.md @@ -1,236 +1,42 @@ -# Pulsing 原生 Agent +# Actor 元信息辅助工具 -Pulsing 提供轻量的原生 Agent 工具箱,用于构建多智能体应用,与 Actor 模型完全兼容。 +`pulsing.agent` 保留少量 actor 辅助功能: -## 设计理念 - -**简单透明。** - -- `@agent` = `@remote` + 元信息(无魔法) -- 元信息用于可视化/调试,不会自动注入 prompt -- 完全掌控 LLM 调用和对话流程 - -## 核心 API - -### `@agent` 装饰器 - -`@agent` 装饰器等同于 `@pul.remote`,但附加元信息用于可视化和调试: - -```python -import pulsing as pul -from pulsing.agent import agent, llm, get_agent_meta, list_agents - -# @pul.remote: 基础 Actor -@pul.remote -class Worker: - async def work(self): - return "done" - -# @agent: 带元信息的 Actor -@agent(role="研究员", goal="深入分析", domain="AI") -class Researcher: - async def analyze(self, topic: str) -> str: - client = await llm() - resp = await client.ainvoke(f"分析: {topic}") - return resp.content -``` - -### 元信息访问 - -```python -await pul.init() -try: - r = await Researcher.spawn(name="researcher") - - # 通过名称获取元信息 - meta = get_agent_meta("researcher") - print(meta.role) # "研究员" - print(meta.goal) # "深入分析" - print(meta.tags) # {"domain": "AI"} - - # 列出所有 Agent - for name, meta in list_agents().items(): - print(f"{name}: {meta.role}") -finally: - await pul.shutdown() -``` - -### `@pul.remote` vs `@agent` - -| 特性 | `@pul.remote` | `@agent` | -|------|---------------|----------| -| 功能 | Actor 化 | Actor 化 + 元信息 | -| 用途 | 通用 | 可视化/调试 | -| 元信息 | 无 | `role`, `goal`, `backstory`, `tags` | -| 性能 | 基准 | 几乎一致 | - -## 运行时管理 - -```python -import pulsing as pul - -await pul.init() -try: - # 创建和使用 Agent - agent = await MyAgent.spawn(name="agent") - await agent.work() -finally: - await pul.shutdown() -``` - -`runtime()` 仍可作为便捷 context manager 使用。本文统一使用显式 `await pul.init()` / `await pul.shutdown()`。 - -### 分布式模式 - -```python -# 节点 A -await pul.init(addr="0.0.0.0:8001") -try: - await JudgeActor.spawn(name="judge") -finally: - await pul.shutdown() - -# 节点 B(自动发现节点 A) -await pul.init(addr="0.0.0.0:8002", seeds=["node_a:8001"]) -try: - judge = await JudgeActor.resolve("judge") # 跨节点透明调用 - await judge.submit(idea) -finally: - await pul.shutdown() -``` - -## LLM 集成 - -```python -from pulsing.agent import llm - -async def analyze(topic: str): - # 获取 LLM 客户端(懒加载单例) - client = await llm(temperature=0.8) - resp = await client.ainvoke(f"分析: {topic}") - return resp.content -``` - -**环境变量:** - -- `OPENAI_API_KEY`: API 密钥(必需) -- `OPENAI_BASE_URL`: 自定义 API 地址(可选) -- `LLM_MODEL`: 默认模型名(可选,默认 `gpt-4o-mini`) - -## 工具函数 - -### JSON 解析 - -```python -from pulsing.agent import parse_json, extract_field - -# 安全 JSON 解析,带默认值 -data = parse_json('{"key": "value"}', default={}) - -# 提取特定字段 -value = extract_field(response, "answer", default="unknown") -``` - -## 完整示例 +- `agent`:在 `@remote` 基础上附加 role/goal 等元信息。 +- `runtime`:初始化和关闭 actor system 的异步上下文管理器。 +- `get_agent_meta`、`list_agents`、`cleanup`:管理元信息。 +- `parse_json` 和 `extract_field`:解析工具。 ```python import asyncio -import pulsing as pul -from pulsing.agent import agent, llm, parse_json, list_agents - -@pul.remote -class Moderator: - """使用 @pul.remote 的协调者(基础 Actor)""" - - def __init__(self, topic: str): - self.topic = topic - self.opinions = [] - - async def collect_opinion(self, agent_name: str, opinion: str): - self.opinions.append({"agent": agent_name, "opinion": opinion}) - return {"received": True} +from pulsing.agent import agent, cleanup, get_agent_meta, runtime - async def summarize(self): - return {"topic": self.topic, "opinions": self.opinions} -@agent(role="分析师", goal="提供洞见", domain="tech") -class Analyst: - """使用 @agent 的分析师(带元信息的 Actor)""" +@agent(role="Worker", goal="Count messages") +class Counter: + def __init__(self): + self.value = 0 - def __init__(self, name: str, moderator: str, mock: bool = True): - self.name = name - self.moderator_name = moderator - self.mock = mock + def inc(self): + self.value += 1 + return self.value - async def analyze(self, topic: str): - if self.mock: - opinion = f"[{self.name}] 对 {topic} 的分析:前景看好" - else: - client = await llm() - resp = await client.ainvoke(f"简要分析: {topic}") - opinion = resp.content - - # 提交给协调者 - moderator = await Moderator.resolve(self.moderator_name) - await moderator.collect_opinion(self.name, opinion) - return opinion async def main(): - await pul.init() try: - # 创建协调者 - moderator = await Moderator.spawn(topic="AI 趋势", name="moderator") - - # 创建分析师 - for i in range(3): - name = f"analyst_{i}" - await Analyst.spawn( - name=name, - moderator="moderator", - mock=True, - name=name, - ) - - # 显示 Agent 元信息 - print("已注册的 Agent:") - for name, meta in list_agents().items(): - print(f" {name}: {meta.role}") - - # 运行分析 - for i in range(3): - analyst = await Analyst.resolve(f"analyst_{i}") - await analyst.analyze("AI 趋势") - - # 获取总结 - result = await moderator.summarize() - print(f"总结: {result}") + async with runtime(): + counter = await Counter.spawn(name="counter") + print(await counter.inc()) + print(get_agent_meta("counter").role) finally: - await pul.shutdown() - -if __name__ == "__main__": - asyncio.run(main()) -``` - -## 示例 - -参见 `examples/agent/pulsing/` 目录的完整示例: - -| 示例 | 说明 | -|------|------| -| `mbti_discussion.py` | 基于 MBTI 人格的多智能体讨论 | -| `parallel_ideas_async.py` | 并行创意生成与竞争提交 | -| `runtime_lifecycle_example.py` | 运行时生命周期管理 | + cleanup() -```bash -# 运行 MBTI 讨论(模拟模式) -python examples/agent/pulsing/mbti_discussion.py --mock --group-size 6 -# 运行并行创意(模拟模式) -python examples/agent/pulsing/parallel_ideas_async.py --mock --n-ideas 5 +asyncio.run(main()) ``` -## 下一步 +这些工具不提供 LLM 客户端、prompt、工具执行或 coding-agent 循环。 +这些能力由上层应用自行选择和实现。 -- [AutoGen 集成](autogen.zh.md) — 在 Pulsing 中使用 AutoGen -- [LangGraph 集成](langgraph.zh.md) — 在 Pulsing 中使用 LangGraph -- [远程 Actor](../guide/remote_actors.zh.md) — 集群部署 +集群配置见 [远程 Actor](../guide/remote_actors.zh.md),生命周期示例见 +`examples/agent/pulsing/runtime_lifecycle_example.py`。 diff --git a/docs/src/design/forge/core-architecture.md b/docs/src/design/forge/core-architecture.md deleted file mode 100644 index 6cc640e3c..000000000 --- a/docs/src/design/forge/core-architecture.md +++ /dev/null @@ -1,505 +0,0 @@ -# Forge Core Architecture and Evolution Protocol - -> **Status**: Accepted Target Architecture -> -> **Version**: 1.0 (2026-07-26) -> -> **Authority**: This document defines Forge's target product boundary, domain model, and protocols. It supersedes conflicting target-state statements in older Forge, Craft, Agent, and GUI design documents. -> **Implementation status**: Target design. Capability claims must continue to follow code and tests. - -Normative terms are **MUST**, **SHOULD**, and **MAY**. - ---- - -## 1. Decision - -Pulsing has one infrastructure core: the **Actor Runtime**. Forge, the App Protocol, GUI, CLI, and Python SDK are built above it. - -```mermaid -flowchart TB - Actor["Pulsing Actor Runtime
mailbox · lifecycle · stream · cluster · transport"] - App["App Protocol
declaration and deployment"] - Forge["Forge
self-evolving Agent Runtime"] - CLI["CLI / Headless"] - GUI["GUI"] - PySDK["Python SDK"] - RustExec["Rust Executors"] - PyExec["Python Worker"] - ActorExec["Actor Workers"] - - Actor --> App - Actor --> Forge - CLI & GUI & PySDK --> Forge - Forge --> RustExec & PyExec & ActorExec - ActorExec --> Actor -``` - -Decisions: - -1. The Actor Runtime is the only infrastructure core and knows nothing about Forge, LLMs, workspaces, or UI. -2. The App Protocol compiles high-level declarations into Actor Runtime operations; it is not a second actor model. -3. Forge owns persistent sessions, the agent loop, events, governed tool execution, workspace versions, evaluation, promotion, and rollback. -4. Rust Forge is the control plane and normative implementation. Python is an SDK, adapter ecosystem, and governed execution backend. -5. GUI, CLI, Python SDK, and remote integrations are clients of one Forge API. -6. Forge is local-first and uses Actors at process, resource, or failure-domain boundaries—not for every internal object. - -### 1.1 Implementation progress - -As of 2026-07-26, the first local vertical slice is implemented: - -| Capability | Status | -|------------|--------| -| Rust IDs and versioned Command/Event types | Initial implementation | -| Session/Turn reducer, one active Turn, contiguous sequence | Implemented | -| Command idempotency, in-memory EventStore, replay/subscription | Implemented | -| Persistent `ForgeAgent` conversation state | Connected to local Sessions | -| `LocalForgeClient` | Implemented | -| CLI reuses one Forge Session | Migrated | -| GUI routes by Session and sends `CancelTurn` | Initial migration | -| Turn-owned cancellation, Tool/Model resource tracking, shell/UnifiedExec/PTY process-tree cleanup | Initial implementation | -| File EventStore and restart recovery | Not implemented | -| Python `ForgeClient` and default `ForgeAgent` client projection | Initial implementation | -| Python Tool/Provider worker protocol | Not implemented | -| Evolution lifecycle | Not implemented | - -This table reports implementation progress; it does not weaken the invariants below. - ---- - -## 2. Product boundaries - -### Actor Runtime - -The Actor Runtime owns identity, mailbox, lifecycle, supervision, ask/tell/stream, backpressure, spawn, resolve, placement, membership, failure detection, transport, and observability. - -It MUST NOT depend on Forge types, LLM providers, clients, or `.pulsing` workspace semantics. - -### App Protocol - -The App Protocol validates versioned `ApplicationSpec` / `ActorSpec` declarations and translates them to spawn, resolve, route, and expose operations. - -It MUST NOT reimplement mailboxes, registries, placement, or cluster scheduling. Public terminology SHOULD use `App Protocol`, `ApplicationSpec`, or `ServiceSpec` to avoid confusion with the Actor Runtime. - -### Forge - -Forge owns: - -- persistent `Session`, `Turn`, and agent-loop state; -- model orchestration contracts without binding to one provider; -- tool registry, capabilities, approval, sandbox, and execution; -- workspace revisions, immutable candidates, and audit events; -- evaluation, promotion, observation, and rollback; -- common semantics across local, Python, and Actor workers. - -Forge MUST NOT use UI state as execution state, require a cluster for local use, or call unmeasured mutation “evolution.” - -### Dependency rule - -Allowed: - -```text -client → forge → actor-runtime -app-protocol → actor-runtime -python-sdk → forge binding -python-worker → language-neutral Forge protocol -``` - -Forbidden: - -```text -actor-runtime → forge -forge-core → gui or concrete CLI -Python-only object → control-plane source of truth -GUI state → execution ownership -``` - ---- - -## 3. Domain model - -IDs are opaque and never reused. - -| Entity | Purpose | Invariant | -|--------|---------|-----------| -| `Session` | Durable agent context | Own event sequence and policy snapshot | -| `Turn` | One goal-to-result execution | Belongs to one Session; one active Turn by default | -| `Event` | An observed fact | Append-only; monotonic Session sequence | -| `ToolCall` | Governed tool execution | Capability plus terminal result | -| `WorkspaceRevision` | Verifiable workspace state | Complete hash manifest or content address | -| `Candidate` | Immutable proposed change | Baseline, artifact, target, and policy | -| `EvaluationRun` | One controlled candidate evaluation | Auditable inputs, environment, and output | -| `EvaluationReport` | Aggregated verdict | Immutable evidence and thresholds | -| `Promotion` | Activation of a qualified candidate | Policy and approval constrained | -| `Rollback` | Restore a known-safe active version | Adds history; never rewrites it | -| `ClientCursor` | Projection position | Never controls execution | - -Commands and events carry applicable `session_id`, `turn_id`, `candidate_id`, `command_id`, `correlation_id`, and `causation_id`. `command_id` is the idempotency key. - ---- - -## 4. Versioned Session protocol - -```mermaid -stateDiagram-v2 - [*] --> Active: CreateSession - Active --> Running: StartTurn - Running --> WaitingInput: InputRequired - WaitingInput --> Running: ProvideInput - Running --> WaitingApproval: ApprovalRequired - WaitingApproval --> Running: ResolveApproval - Running --> Active: TurnCompleted - Running --> Cancelling: CancelTurn - Cancelling --> Active: TurnCancelled - Active --> Closed: CloseSession -``` - -Session and Turn state are separate. Client disconnect, GUI navigation, or loss of a subscriber MUST NOT change execution state. - -Required commands: - -- `CreateSession` -- `StartTurn` -- `CancelTurn` -- `ProvideInput` -- `ResolveApproval` -- `UpdateSessionPolicy` -- `CloseSession` -- `GetSessionSnapshot` -- `SubscribeEvents` - -State-changing commands use a versioned envelope: - -```json -{ - "protocol": "forge.session", - "version": {"major": 1, "minor": 0}, - "command_id": "opaque", - "session_id": "opaque", - "expected_seq": 42, - "payload": {} -} -``` - -Session invariants: - -1. A Session has at most one active Turn by default. -2. Retrying a `command_id` returns an equivalent result without repeating side effects. -3. `TurnStarted` is durable before model or tool side effects begin. -4. Tool intent is durable before dispatch; every call receives a terminal event. -5. `CancelTurn` is a request. Only `TurnCancelled` means execution has stopped. -6. A backend that cannot stop immediately remains `cancellation_pending`. -7. Recovery uses snapshot plus events, never client memory. - ---- - -## 5. Versioned Event protocol - -```json -{ - "protocol": "forge.event", - "version": {"major": 1, "minor": 0}, - "event_id": "opaque", - "session_id": "opaque", - "seq": 43, - "occurred_at": "RFC3339", - "kind": "tool.completed", - "turn_id": "opaque", - "correlation_id": "opaque", - "causation_id": "opaque", - "payload": {}, - "redaction": {"class": "public"} -} -``` - -Guarantees: - -- `seq` is strictly monotonic within one Session. -- There is no global cross-Session order. -- Subscriptions are at-least-once; clients deduplicate by `event_id` or `(session_id, seq)`. -- `SubscribeEvents(after_seq=N)` replays and then follows events with `seq > N`. -- Events become visible only after persistence. -- A sequence gap triggers replay, not inferred state. - -Minimum event domains: - -| Domain | Required events | -|--------|-----------------| -| Session | created, policy_updated, closed | -| Turn | started, output_delta, completed, failed, cancel_requested, cancelled | -| Model | requested, completed, failed, usage_recorded | -| Tool | requested, approval_required, started, output_delta, completed, failed, cancelled | -| Workspace | revision_created, restored | -| Evolution | candidate.created/prepared/qualified/rejected/promoted/rolled_back, evaluation.started/completed, promotion.requested | - -Compatibility: - -- A major change is breaking and unsupported majors are rejected. -- A minor change only adds optional fields or event kinds. -- Clients ignore unknown optional fields. -- Projection clients preserve and advance past unknown events. -- Command handlers never silently ignore unknown commands. -- Persisted history is not rewritten in place. - -Events MUST NOT store plaintext secrets or unrestricted credentials. Large or binary values go to the artifact store; events carry hashes and controlled references. - ---- - -## 6. Evolution protocol - -A change is evolution only when it has: - -1. an explicit baseline; -2. an immutable candidate; -3. a predeclared evaluation suite; -4. a policy comparison against the baseline; -5. independent approval and atomic promotion; -6. post-promotion observation and rollback. - -Unmeasured modification is mutation, not evolution. - -### Risk levels - -| Level | Target | Default | -|-------|--------|---------| -| L0 | Prompt, Skill content, Workflow config | Automatic evaluation; configurable promotion | -| L1 | Tool schema, provider parameters, routing | Regression evaluation; human approval | -| L2 | User workspace code and deployment config | Sandbox, tests, human approval | -| L3 | Forge or evaluator code | Independent controller and dual approval | - -The first implementation MUST be L0-only. L3 requires a separate security review. - -An immutable Candidate records its target, baseline, artifact hash, producer Session/Turn, declared goal, evaluation suite version, promotion policy version, risk level, and timestamp. Any content change creates a new Candidate ID. - ---- - -## 7. Candidate lifecycle - -```mermaid -stateDiagram-v2 - [*] --> Draft: CreateCandidate - Draft --> Prepared: Validate artifact - Prepared --> Evaluating: StartEvaluation - Evaluating --> Qualified: Policy passed - Evaluating --> Rejected: Policy failed - Qualified --> AwaitingApproval: RequestPromotion - AwaitingApproval --> Promoted: Approve + atomic switch - AwaitingApproval --> Rejected: Deny / expire - Promoted --> Observing: Start guards - Observing --> Accepted: Window passed - Promoted --> RolledBack: Guard/manual rollback - Observing --> RolledBack: Regression -``` - -Transitions occur only through commands and durable events. - -Every EvaluationRun records immutable candidate and baseline references, suite/runner versions, dependency lock, sandbox profile, dataset, seed, resource budget, raw artifact, metrics, thresholds, and verdict. - -Candidate and baseline SHOULD run in equivalent environments. Non-reproducible external judgments are labeled and cannot independently trigger automatic promotion unless policy explicitly allows it. - -A Promotion policy is frozen before evaluation and defines hard gates, minimum baseline improvement, allowed regressions, cost/latency/security limits, run count, aggregation, automatic-promotion permission, approvers, observation window, and rollback guards. - -Promotion MUST: - -1. verify Qualified state, approval, policy, artifact hash, and current baseline; -2. switch the active reference atomically; -3. retain the old active version as rollback target; -4. enter an observation phase; -5. never overwrite an artifact. - -Rollback is a new audited operation. It restores and verifies a complete known-safe state, cancels or isolates affected executions, records its cause, and enters an explicit degraded state if restoration fails. - -The Evolution Controller, policy, artifact verifier, and rollback implementation MUST be outside the Candidate's mutation boundary. A Forge process being replaced cannot certify its own replacement. - ---- - -## 8. Rust control plane and Python execution plane - -Rust owns: - -- Session/Turn reducers; -- command idempotency and optimistic concurrency; -- event ordering and persistence interfaces; -- tool registry and capability gate; -- sandbox policy contract; -- workspace manifest and hash verification; -- Candidate/Evaluation/Promotion reducers; -- cancellation ownership. - -Python owns: - -- SDK bindings; -- model-provider adapters; -- governed Python-tool adapters; -- evaluator and dataset adapters; -- framework integrations; -- user extensions. - -Python MUST change state through Forge commands and MUST NOT become the Session or Event source of truth. - -Rust types are the normative implementation, but schemas are language-neutral. PyO3, direct calls, and Actor RPC may use different encodings while preserving command, event, cancellation, and error semantics. - -Production Python providers and tools SHOULD run behind cancellable worker boundaries. Workers handshake protocol versions and capabilities, accept deadlines and cancellation, never write the Session store, return large values through artifacts, and produce terminal events when they crash. - ---- - -## 9. Unified clients - -Every client uses the same logical API: - -```text -ForgeClient - create_session(...) - start_turn(session_id, input, command_id) - cancel_turn(session_id, turn_id, command_id) - provide_input(...) - resolve_approval(...) - get_snapshot(session_id) - subscribe(session_id, after_seq) -``` - -Implementations: - -- `LocalForgeClient`: typed in-process Rust service; -- `ActorForgeClient`: Pulsing ask/tell/stream; -- `RemoteForgeClient`: future authenticated network transport. - -All implementations pass the same contract suite. - -GUI is a projection plus command sender. It does not spawn detached agent owners, treat a receiver as ownership, route events by the active tab, or report stopped before `TurnCancelled`. - -CLI creates or attaches to Sessions. Terminal exit explicitly chooses detach, cancel, or wait. - -Python SDK no longer owns a stateful `HybridForgeRuntime`; it drives Rust Forge through `ForgeClient` and registers Python execution adapters. - -In the current implementation, `pulsing.forge.ForgeAgent` is that client projection: Rust owns Session, Turn, the agent loop, tool runtime, event sequencing, and cancellation. The former Python loop remains only as the explicit `LegacyPythonForgeAgent` compatibility entry point, while `HybridForgeRuntime` is a transitional mixed-tool adapter. Default entry points and new code MUST NOT select either implicitly. The Python Tool/Provider worker protocol remains Phase 3 work. - ---- - -## 10. Deployment, persistence, and security - -Forge is local by default: - -```text -GUI/CLI/Python → Local Forge control plane → Rust executor / Python worker -``` - -Isolation or distribution uses Actor boundaries: - -```text -Forge control plane → Actor Runtime → ToolExecutorActor / EvaluatorActor / ProviderActor -``` - -Only components needing a separate lifecycle, failure domain, or remote resource become Actors. - -Forge depends on `EventStore`, `SnapshotStore`, `ArtifactStore`, `WorkspaceRevisionStore`, and `ActiveVersionStore`. A local-file implementation is acceptable only with atomic writes, path confinement, hash verification, and crash recovery. - -Every ToolCall and evolution action binds a capability decision to subject, resource scope, argument digest, Session/Turn, expiry, and decision source. Python fallback cannot bypass the Rust capability gate. - -Recovery loads a snapshot, replays events, marks unterminated external calls unknown, reconciles supported executors, and never silently retries non-idempotent effects. - ---- - -## 11. Errors and cancellation - -Structured errors contain `code`, `message`, `retryable`, `origin`, related IDs, and details. - -Categories include validation, conflict, unsupported_version, permission_denied, sandbox_violation, deadline_exceeded, cancelled, worker_lost, provider_error, storage_error, and internal. - -Only explicitly idempotent operations are automatically retried. Model requests, shell commands, and external writes are not silently retried by default. - -Cancellation propagates through model requests, tools, Python workers, Actor workers, and subprocesses. Resources that cannot be confirmed stopped remain cancelling or unknown. - ---- - -## 12. Migration - -### Phase 0 — Freeze boundaries - -- Make this document the target-state authority. -- Label existing Forge docs as the current tool runtime. -- Stop defining independent Session semantics in Craft, Agent, and GUI docs. -- Add protocol compatibility tests. - -### Phase 1 — Rust Session and Event - -- Implement Session/Turn reducers and versioned envelopes. -- Add local EventStore, snapshot, and replay. -- Preserve state across prompts. -- Implement real cancellation ownership. (Initial local process and in-process future ownership is complete; Python and Actor workers remain.) - -### Phase 2 — Unified clients - -- Move CLI and GUI to `ForgeClient`. -- Expose the client through Python. -- Remove GUI detached workers and global event receivers. - -### Phase 3 — Python execution adapters - -- Move Hybrid routing decisions into the Rust registry. -- Run Python-only tools/providers through workers. -- Move duplicate Agent loop, permission, and sandbox state into Forge. -- Reduce `pulsing.agent` to compatibility APIs or a reference application. - -### Phase 4 — L0 evolution - -- Implement Candidate, Evaluation, Promotion, and stores. -- Support Prompt/Skill/Workflow only. -- Require fixed suites, auditable evidence, atomic active pointers, and complete rollback. - -### Phase 5 — Code evolution - -- Add L1/L2 after hermetic evaluation and observation guards. -- Require a separate design review before L3 self-hosting. - ---- - -## 13. Acceptance criteria - -Session/Event: - -- Replaying a command does not duplicate a Turn or Tool side effect. -- A client can disconnect at any event and recover without state loss. -- Stop tests detect surviving subprocesses. -- Rust, Python, GUI, and CLI pass one protocol contract suite. - -Evolution: - -- Candidate content changes create new IDs. -- Evaluation policy cannot change after a run starts. -- Environment drift between baseline and candidate is detected. -- Failed atomic promotion leaves the active version unchanged. -- Rollback restores complete hash-verified state. -- Candidate code cannot modify the Controller, policy, or verifier. -- L0 automatic promotion is fully replayable and auditable. - -Language boundary: - -- Disabling Python fallback does not change Rust-tool semantics. -- Python-worker failure produces a terminal event. -- Unsupported majors are rejected. -- Unknown minor events do not crash clients. - ---- - -## 14. Non-goals and open ADRs - -Non-goals: - -- automatic self-modification of Forge code in the first release; -- mandatory clustering; -- GUI layout in the core protocol; -- global event ordering; -- exactly-once external effects; -- Python-memory control state; -- calling overlay copy a complete rollback. - -Open ADRs: - -1. EventStore format and compaction; -2. ArtifactStore addressing; -3. explicit parallel Turns; -4. provider streaming and usage accounting; -5. statistical evaluation method; -6. default L0 auto-promotion policy; -7. ActorForgeClient leases and recovery; -8. independent trust root for L3 self-hosting. diff --git a/docs/src/design/forge/core-architecture.zh.md b/docs/src/design/forge/core-architecture.zh.md deleted file mode 100644 index b40ff0ce8..000000000 --- a/docs/src/design/forge/core-architecture.zh.md +++ /dev/null @@ -1,718 +0,0 @@ -# Forge 核心架构与演化协议 - -> **状态**:Accepted Target Architecture -> -> **版本**:1.0(2026-07-26) -> -> **规范源**:本文件定义 Forge 的目标产品边界、领域模型和协议。与旧 Forge、Craft、Agent、GUI 文档冲突时,以本文件为准。 -> **实现状态**:目标设计,不能据此宣称功能已经落地;公开能力仍以代码和测试为准。 - -本文使用以下规范词: - -- **必须(MUST)**:违反即破坏协议或产品边界。 -- **应该(SHOULD)**:默认遵循;偏离时必须记录理由。 -- **可以(MAY)**:兼容协议的可选实现。 - ---- - -## 1. 决策摘要 - -Pulsing 只有一个核心:**Actor Runtime**。Forge、应用协议、GUI、CLI 和 Python SDK 都建立在它之上。 - -```mermaid -flowchart TB - subgraph Core["Pulsing Core"] - Actor["Actor Runtime
mailbox · lifecycle · stream · cluster · transport"] - end - - subgraph Product["上层产品与协议"] - App["App Protocol
快速声明与部署"] - Forge["Forge
自进化 Agent Runtime"] - end - - subgraph Clients["Forge 客户端"] - CLI["CLI / Headless"] - GUI["GUI"] - PySDK["Python SDK"] - API["Remote API"] - end - - subgraph Exec["执行后端"] - RustExec["Rust Executors"] - PyExec["Python Worker"] - ActorExec["Actor Workers"] - end - - Actor --> App - Actor --> Forge - CLI & GUI & PySDK & API --> Forge - Forge --> RustExec & PyExec & ActorExec - ActorExec --> Actor -``` - -核心决策: - -1. **Actor Runtime 是唯一基础设施核心**,不知道 Forge、LLM、GUI 或工作区。 -2. **App Protocol 是快捷部署协议**,把高级应用声明编译为 Actor Runtime 操作,不形成第二套 Actor 模型。 -3. **Forge 是自进化 Agent Runtime**,拥有会话、Agent loop、事件、工具治理、工作区版本、评估与晋升语义。 -4. **Rust Forge 是控制面和规范实现**;Python 是 SDK、Provider/Tool 适配器和受控执行后端。 -5. **GUI、CLI、Python SDK 是同一 Forge API 的客户端**,不得各自拥有另一套 Agent 状态机。 -6. **本地优先、按边界 Actor 化**;不是每个 Forge 内部对象都必须成为 Actor。 - -### 1.1 实现进度 - -截至 2026-07-26,第一条本地垂直链路已经落地: - -| 能力 | 状态 | -|------|------| -| Rust `SessionId` / `TurnId` / `CommandId` 与版本化 Command/Event | 已实现初版 | -| Session/Turn reducer、单活跃 Turn、连续事件序号 | 已实现 | -| `command_id` 幂等、in-memory EventStore、replay/subscription | 已实现 | -| 持久 `ForgeAgent` 对话状态 | 已接入本地 Session | -| `LocalForgeClient` | 已实现 | -| CLI 复用同一个 Forge Session | 已迁移 | -| GUI 按 Session 路由事件并通过 `CancelTurn` 停止 | 已迁移首版 | -| Turn 级取消所有权、Tool/Model 资源登记、shell/UnifiedExec/PTY 进程树回收 | 已实现首版 | -| 文件 EventStore、snapshot/restart recovery | 未实现 | -| Python `ForgeClient` + 默认 `ForgeAgent` 客户端投影 | 已实现初版 | -| Python Tool/Provider worker protocol | 未实现 | -| Candidate/Evaluation/Promotion/Rollback | 未实现 | - -该表只描述实现进度,不降低本文其余不变量。 - ---- - -## 2. 产品边界与依赖规则 - -### 2.1 Actor Runtime - -Actor Runtime 负责: - -- Actor 身份、邮箱、生命周期和 supervision; -- `ask`、`tell`、stream 与背压; -- spawn、resolve、placement、集群成员和故障检测; -- Message/Tensor 传输; -- 可观测性和 Rust/Python 绑定。 - -Actor Runtime **不得**依赖: - -- Forge Session、Tool 或 Evolution 类型; -- LLM Provider; -- GUI/CLI; -- `.pulsing` 工作区产品语义。 - -### 2.2 App Protocol - -App Protocol 负责把用户声明转换为版本化 `ApplicationSpec` / `ActorSpec`: - -```text -decorator / YAML / CLI - → validate ApplicationSpec - → derive ActorSpec + routes + resources - → spawn / resolve / expose -``` - -App Protocol **不得**重新实现 mailbox、registry、placement 或 cluster scheduler。对外命名应该使用 `App Protocol`、`ApplicationSpec` 或 `ServiceSpec`,避免与底层 Actor Runtime 混淆。 - -### 2.3 Forge - -Forge 负责: - -- 持久 `Session`、`Turn` 和 Agent loop; -- 模型调用的编排协议,但不强绑定某家 Provider; -- Tool registry、capability、审批、sandbox 和执行; -- 工作区 revision、candidate artifact 和审计事件; -- Evaluation、Promotion、Observation 和 Rollback; -- 本地、Python worker 与 Actor worker 的统一执行语义。 - -Forge **不得**把 UI 状态作为执行状态,不得要求集群才能本地运行,也不得把未经评估的“自动修改”称为“演化”。 - -### 2.4 依赖方向 - -允许: - -```text -client → forge → actor-runtime -app-protocol → actor-runtime -python-sdk → forge binding -python-worker → language-neutral Forge protocol -``` - -禁止: - -```text -actor-runtime → forge -forge-core → gui -forge-core → concrete CLI -rust control state → Python-only source of truth -gui state → execution ownership -``` - ---- - -## 3. Forge 领域模型 - -所有 ID 都是不可复用的 opaque identifier。调用方不得从字符串格式推导语义。 - -| 对象 | 作用 | 不变量 | -|------|------|--------| -| `Session` | 持久 Agent 工作上下文 | 独立事件序列和策略快照 | -| `Turn` | 一次用户目标到最终结果的执行 | 属于一个 Session;默认同 Session 单活跃 Turn | -| `Event` | 已发生事实 | append-only;Session 内单调序号 | -| `ToolCall` | 一次受治理的工具调用 | 有 capability、输入摘要、结果或终止原因 | -| `WorkspaceRevision` | 可验证的工作区状态 | 内容寻址或包含完整 hash manifest | -| `Candidate` | 待评估的不可变变更提案 | 指向 baseline、artifact 和 evolution target | -| `EvaluationRun` | Candidate 在固定条件下的一次评估 | 输入、环境、结果可审计 | -| `EvaluationReport` | 多个评估运行的归并结论 | 不可变;包含通过条件和证据 | -| `Promotion` | 将 Qualified Candidate 设为活动版本 | 受 policy 和 approval 约束 | -| `Rollback` | 从已晋升版本恢复到已知安全版本 | 产生新事件,不改写历史 | -| `ClientCursor` | 客户端的消费位置 | 只影响投影,不影响执行状态 | - -### 3.1 标识与关联 - -每个命令和事件必须携带以下关联字段中的适用部分: - -```text -session_id -turn_id -candidate_id -command_id -correlation_id -causation_id -``` - -`command_id` 是幂等键;`correlation_id` 串起一次用户操作;`causation_id` 指向直接导致当前事件的命令或事件。 - ---- - -## 4. 版本化 Session 协议 - -### 4.1 Session 状态 - -```mermaid -stateDiagram-v2 - [*] --> Active: CreateSession - Active --> Running: StartTurn - Running --> WaitingInput: InputRequired - WaitingInput --> Running: ProvideInput - Running --> WaitingApproval: ApprovalRequired - WaitingApproval --> Running: Grant - WaitingApproval --> Running: Deny and continue - Running --> Active: TurnCompleted - Running --> Cancelling: CancelTurn - Cancelling --> Active: TurnCancelled - Active --> Closed: CloseSession - Closed --> [*] -``` - -Session 状态与 Turn 状态必须分开存储。客户端断开、GUI 切换页面或订阅者消失不得改变这两个状态。 - -### 4.2 命令 - -协议至少定义: - -| 命令 | 语义 | -|------|------| -| `CreateSession` | 创建 Session,并冻结初始 policy/provider/workspace 引用 | -| `StartTurn` | 在 Session 中开始一个 Turn | -| `CancelTurn` | 请求取消指定 Turn | -| `ProvideInput` | 响应结构化用户输入请求 | -| `ResolveApproval` | 批准或拒绝 capability 请求 | -| `UpdateSessionPolicy` | 对后续操作更新策略;不能追溯修改历史 | -| `CloseSession` | 不再接受新 Turn;按策略取消或等待当前 Turn | -| `GetSessionSnapshot` | 获取当前投影和最后事件序号 | -| `SubscribeEvents` | 从指定 `after_seq` 订阅事件 | - -所有改变状态的命令必须包含: - -```json -{ - "protocol": "forge.session", - "version": {"major": 1, "minor": 0}, - "command_id": "opaque", - "session_id": "opaque", - "expected_seq": 42, - "payload": {} -} -``` - -`expected_seq` 用于乐观并发控制;不需要强一致检查的幂等命令可以省略。 - -### 4.3 Session 不变量 - -1. 默认每个 Session 最多一个 Running/Waiting/Cancelling Turn。 -2. 同一 `command_id` 重试必须返回等价结果,不能重复产生副作用。 -3. `StartTurn` 被接受后必须先持久化 `TurnStarted`,再发起模型或工具副作用。 -4. 工具调用必须先记录 intent,再 dispatch;完成、失败和取消都必须有终止事件。 -5. `CancelTurn` 是请求,不是假定完成;只有 `TurnCancelled` 才表示执行已停止。 -6. 无法立即终止的后端必须标记 `cancellation_pending`,禁止向客户端报告已停止。 -7. Session 恢复必须从 snapshot + events 重建,不能依赖 GUI/CLI 内存。 - ---- - -## 5. 版本化 Event 协议 - -### 5.1 Event envelope - -```json -{ - "protocol": "forge.event", - "version": {"major": 1, "minor": 0}, - "event_id": "opaque", - "session_id": "opaque", - "seq": 43, - "occurred_at": "RFC3339", - "kind": "tool.completed", - "turn_id": "opaque", - "correlation_id": "opaque", - "causation_id": "opaque", - "payload": {}, - "redaction": {"class": "public"} -} -``` - -### 5.2 顺序与投递保证 - -- Forge 保证 **单 Session 内** `seq` 严格单调且无重复。 -- Forge 不保证跨 Session 全局顺序。 -- 订阅采用 **at-least-once delivery**;客户端必须按 `event_id` 或 `(session_id, seq)` 去重。 -- `SubscribeEvents(after_seq=N)` 返回 `seq > N` 的历史和实时事件。 -- 事件持久化后才能对订阅者可见。 -- 客户端发现序号缺口时必须重新读取,不得自行猜测缺失状态。 - -### 5.3 最小事件集合 - -| 域 | 事件 | -|----|------| -| Session | `session.created`, `session.policy_updated`, `session.closed` | -| Turn | `turn.started`, `turn.output_delta`, `turn.completed`, `turn.failed`, `turn.cancel_requested`, `turn.cancelled` | -| Model | `model.requested`, `model.completed`, `model.failed`, `model.usage_recorded` | -| Tool | `tool.requested`, `tool.approval_required`, `tool.started`, `tool.output_delta`, `tool.completed`, `tool.failed`, `tool.cancelled` | -| Workspace | `workspace.revision_created`, `workspace.restored` | -| Evolution | `candidate.created`, `candidate.prepared`, `evaluation.started`, `evaluation.completed`, `candidate.qualified`, `candidate.rejected`, `promotion.requested`, `candidate.promoted`, `candidate.rolled_back` | - -### 5.4 兼容性 - -- `major` 变化表示破坏兼容;不支持时必须明确拒绝。 -- `minor` 变化只能增加 optional field 或新 event kind。 -- 客户端必须忽略未知 optional field。 -- 投影客户端可以忽略未知 event kind,但必须推进 cursor 并保留原始 envelope。 -- 命令处理器不得静默忽略未知命令。 -- 持久事件不得原地迁移;升级通过新 projector 或显式 migration event 完成。 - -### 5.5 敏感数据 - -事件默认不得保存明文 secret、完整环境变量或未经限制的模型凭据。大输出和二进制内容应进入 artifact store,事件只记录 hash、size、media type 和受控引用。 - ---- - -## 6. Evolution 协议 - -### 6.1 什么是演化 - -只有满足以下条件的变更才称为 Evolution: - -1. 有明确 baseline; -2. 产生不可变 candidate; -3. 在预先声明的 evaluation suite 上运行; -4. 根据 promotion policy 比较 candidate 与 baseline; -5. 有独立的批准和原子晋升; -6. 晋升后持续观察并可以回滚。 - -不经过评估的代码、Prompt 或 Tool 修改只是 mutation,不是 evolution。 - -### 6.2 Evolution target 风险级别 - -| 级别 | Target | 默认策略 | -|------|--------|----------| -| L0 | Prompt、Skill 内容、Workflow 配置 | 可自动评估;满足 policy 后可配置自动晋升 | -| L1 | Tool schema、Provider 参数、路由策略 | 需要回归评估;默认人工批准 | -| L2 | 用户工作区代码、依赖和部署配置 | 必须 sandbox + 测试;人工批准 | -| L3 | Forge 或评估器自身代码 | 独立控制器、双重批准、禁止直接原地替换 | - -第一阶段必须只支持 L0。L2 稳定后才可以设计 L3 self-hosting。 - -### 6.3 Candidate - -Candidate 创建后必须不可变,至少包含: - -```text -candidate_id -target_kind -target_ref -baseline_ref -artifact_ref + content_hash -producer_session_id + producer_turn_id -declared_goal -evaluation_suite_ref + version -promotion_policy_ref + version -risk_level -created_at -``` - -任何内容变化都必须产生新 `candidate_id`,不能覆盖旧 Candidate。 - ---- - -## 7. Candidate → Evaluation → Promotion → Rollback - -### 7.1 状态机 - -```mermaid -stateDiagram-v2 - [*] --> Draft: CreateCandidate - Draft --> Prepared: Materialize + validate artifact - Prepared --> Evaluating: StartEvaluation - Evaluating --> Qualified: Policy passed - Evaluating --> Rejected: Policy failed / invalid - Qualified --> AwaitingApproval: Promotion requested - AwaitingApproval --> Promoted: Approved + atomic switch - AwaitingApproval --> Rejected: Denied / expired - Promoted --> Observing: Post-promotion checks - Observing --> Accepted: Observation window passed - Promoted --> RolledBack: Guard triggered / manual rollback - Observing --> RolledBack: Regression detected - Draft --> Archived: Abandon - Prepared --> Archived: Abandon - Rejected --> Archived - Accepted --> Archived: Superseded - RolledBack --> Archived -``` - -状态只能通过命令和持久事件转换。状态字段不能被客户端直接修改。 - -### 7.2 Evaluation - -每次 EvaluationRun 必须记录: - -- candidate 与 baseline 的不可变引用; -- suite 名称、版本和 hash; -- runner 版本、依赖锁和 sandbox profile; -- 输入数据集或样本版本; -- 随机种子; -- wall time、成本和资源上限; -- 原始结果 artifact; -- 指标、阈值和最终 verdict。 - -Candidate 与 baseline 应该在等价环境运行。无法重现的外部评价必须标记 `non_reproducible`,promotion policy 可以禁止其单独触发自动晋升。 - -### 7.3 Promotion policy - -Policy 必须在 Evaluation 开始前冻结,至少定义: - -- 必须通过的 hard gates; -- 相对 baseline 的最低提升; -- 允许退化的指标和最大幅度; -- 最大成本、延迟和安全违规; -- 最少运行次数和统计聚合方式; -- 是否允许自动晋升; -- 所需批准角色; -- observation window 和 rollback guards。 - -评估完成后修改阈值不能让同一份报告变为通过;必须创建新的 Evaluation。 - -### 7.4 Promotion - -Promotion 必须: - -1. 验证 Candidate 为 `Qualified`; -2. 验证 approval、policy、artifact hash 和当前 baseline; -3. 使用 compare-and-swap 或等价原子操作切换活动引用; -4. 记录旧活动版本,作为 rollback target; -5. 发出 `candidate.promoted` 后进入 observation; -6. 不得直接覆盖 artifact。 - -### 7.5 Rollback - -Rollback 是一次新的受审计操作,不删除 Promotion 历史。它必须: - -- 指向明确的已知安全 revision; -- 验证恢复 artifact 的 hash; -- 恢复完整状态,而不是只覆盖旧文件; -- 取消或隔离仍在使用被回滚版本的执行; -- 记录触发原因、操作者和受影响 Session; -- 在恢复失败时进入显式 degraded state,不能报告成功。 - -### 7.6 信任边界 - -Evolution Controller、Evaluation policy、artifact verifier 和 rollback implementation 必须位于 Candidate 不能修改的信任边界。 - -L3 自修改必须通过独立 Forge Controller 或外部 supervisor 完成。正在被 Candidate 替换的 Forge 进程不能自行证明替换成功。 - ---- - -## 8. Rust 控制面与 Python 执行面 - -### 8.1 Rust 必须拥有 - -| 能力 | 原因 | -|------|------| -| Session/Turn 状态机 | 唯一执行语义 | -| Event envelope、排序、持久化接口 | 所有客户端一致 | -| Command 幂等和并发控制 | 防止重复副作用 | -| Tool registry 与 capability gate | 安全决策不能由 fallback 绕过 | -| Sandbox policy 解析和 enforcement contract | 跨语言同一策略 | -| Workspace revision manifest 和 hash 验证 | Promotion/Rollback 基础 | -| Candidate/Evaluation/Promotion 状态机 | 演化控制面 | -| Cancellation ownership | GUI/CLI 不得伪造停止 | - -### 8.2 Python 可以拥有 - -| 能力 | 约束 | -|------|------| -| Python SDK | 只能通过 ForgeClient 命令和事件协议改变状态 | -| Model Provider adapter | 返回版本化响应;不得持有 Session 真相 | -| Python Tool adapter | 在声明 capability 和 sandbox profile 后注册 | -| 数据集/Evaluator adapter | 必须输出可审计 EvaluationRun | -| Framework integration | LangChain 等只做映射,不复制 Forge loop | -| 用户扩展 | 默认在 worker 进程;进程内仅用于显式开发模式 | - -### 8.3 绑定协议 - -Rust 类型是规范实现,但协议 schema 必须语言中立。PyO3、本地 direct call 和 Actor RPC 可以使用不同编码,必须保持相同命令、事件和错误语义。 - -Python callback 抛出的异常必须转换成结构化 Forge error 和终止事件,不能穿过边界后让 Session 留在 Running。 - -### 8.4 Python worker - -生产环境中的 Python Tool/Provider 应运行在可取消、可回收的 worker 边界。Worker 必须: - -- 进行 protocol handshake; -- 声明支持的 major/minor 和 capabilities; -- 接受 deadline/cancellation; -- 不直接写 Session/Event store; -- 通过 artifact API 返回大结果; -- 崩溃后由 Forge 记录明确终止事件。 - ---- - -## 9. 统一客户端模型 - -GUI、CLI、Python SDK 和 Remote API 必须只依赖同一个逻辑接口: - -```text -ForgeClient - create_session(...) - start_turn(session_id, input, command_id) - cancel_turn(session_id, turn_id, command_id) - provide_input(...) - resolve_approval(...) - get_snapshot(session_id) - subscribe(session_id, after_seq) -``` - -实现可以是: - -- `LocalForgeClient`:同进程调用 Rust service; -- `ActorForgeClient`:通过 Pulsing ask/tell/stream; -- `RemoteForgeClient`:未来的受认证网络接口。 - -三者必须通过同一 contract test。 - -### 9.1 GUI - -GUI 是事件投影和命令发送器: - -- 不创建 detached Agent worker; -- 不把 `event_rx` 当成任务所有权; -- 不因切换 tab 改变事件路由; -- Stop 必须发送 `CancelTurn`,并等待取消完成事件; -- 重启后通过 snapshot + `after_seq` 恢复; -- Session/Turn busy 状态来自 Forge 投影。 - -### 9.2 CLI - -CLI 的交互模式和一次性模式都创建或附着 Forge Session。退出终端不等于取消;CLI 必须明确选择 detach、cancel 或 wait。 - -### 9.3 Python SDK - -Python SDK 不再构造独立 `HybridForgeRuntime` 作为状态所有者。它通过 `ForgeClient` 操作 Rust Forge,并把 Python Provider/Tool 注册为执行适配器。 - -当前实现中,`pulsing.forge.ForgeAgent` 已经是上述客户端投影:Session、Turn、Agent loop、Tool runtime、事件序号与取消所有权都在 Rust。原 Python loop 仅以显式的 `LegacyPythonForgeAgent` 兼容入口保留,`HybridForgeRuntime` 仅作为待迁移的混合 Tool adapter;两者不得被默认入口或新代码隐式选择。Python Tool/Provider worker protocol 仍属于 Phase 3,不能把兼容入口的存在误记为该阶段已经完成。 - ---- - -## 10. 部署模型 - -Forge 默认本地运行,不要求集群: - -```text -GUI/CLI/Python - → Local Forge Control Plane - → local Rust executor / Python worker -``` - -需要隔离或分布式时: - -```text -Forge Control Plane - → Actor Runtime - → ToolExecutorActor / EvaluatorActor / ProviderActor -``` - -只有跨故障域、需要独立生命周期或需要远程资源的组件应该 Actor 化。领域值对象和控制面内部 reducer 保持普通 Rust 对象。 - ---- - -## 11. 持久化、安全与恢复 - -### 11.1 Stores - -Forge 通过接口依赖以下 stores: - -- `EventStore` -- `SnapshotStore` -- `ArtifactStore` -- `WorkspaceRevisionStore` -- `ActiveVersionStore` - -首个实现可以是本地文件,但必须满足原子写、hash 校验、路径约束和崩溃恢复。GUI 目录或内存 channel 不是 store。 - -### 11.2 Capability - -每个 ToolCall 和 Evolution action 必须绑定 capability。审批决定包含: - -```text -subject -capability -resource scope -argument digest -session/turn -expiry -decision source -``` - -审批不能只按工具名无限复用。Python fallback 不得绕过 Rust capability gate。 - -### 11.3 恢复 - -进程重启后: - -1. 加载最近 snapshot; -2. replay 后续事件; -3. 将没有终止事件的外部调用标记为 `unknown`; -4. 查询支持 reconciliation 的执行器; -5. 无法确认时安全失败,不自动重复非幂等操作。 - ---- - -## 12. 错误、重试与取消 - -统一错误至少包含: - -```text -code -message -retryable -origin -session_id / turn_id / tool_call_id -details -``` - -错误类别包括 validation、conflict、unsupported_version、permission_denied、sandbox_violation、deadline_exceeded、cancelled、worker_lost、provider_error、storage_error 和 internal。 - -只有明确标记幂等或携带执行幂等键的操作可以自动重试。模型调用、shell 和外部写操作默认不得静默重试。 - -取消必须从 Session 传播到模型调用、tool call、Python worker、Actor worker 和子进程。不能终止的资源必须继续显示为 cancelling/unknown,直到 reconciliation 完成。 - ---- - -## 13. 迁移计划 - -### Phase 0:冻结边界 - -- 本文成为目标架构规范源; -- 旧 Forge 文档标记为 Current Tool Runtime; -- Craft/Agent/GUI 文档不再定义独立 Session 语义; -- 建立 protocol compatibility 测试目录。 - -### Phase 1:Rust Session + Event - -- 在 `pulsing-forge` 实现 Session/Turn reducer; -- 实现版本化 Command/Event envelope; -- 本地 EventStore、snapshot、replay; -- ForgeAgent 不再每个 prompt 清空状态; -- 实现真实 cancellation ownership。(首版本地进程与 in-process future 已完成;Python/Actor worker 待后续阶段接入) - -### Phase 2:统一客户端 - -- CLI 迁移到 `LocalForgeClient`; -- GUI 迁移到 snapshot/subscription; -- Python 暴露 `ForgeClient`; -- 删除 GUI detached worker 和全局 event receiver。 - -### Phase 3:Python 执行适配器 - -- 把 Hybrid routing 决策移入 Rust registry; -- Python-only Tool/Provider 使用 worker protocol; -- Agent 包中的 loop、permission、sandbox 状态迁入 Forge; -- `pulsing.agent` 收敛为兼容 API 或参考应用。 - -### Phase 4:L0 Evolution - -- Candidate、Evaluation、Promotion stores; -- 只支持 Prompt/Skill/Workflow; -- 固定 suite、人工批准、原子 active pointer、完整 rollback; -- GUI 展示 Candidate 与评估证据,但不拥有状态。 - -### Phase 5:代码演化 - -- 支持 L1/L2; -- hermetic evaluator、资源预算和 observation guards; -- L3 必须另立安全设计评审,不自动继承 L2 能力。 - ---- - -## 14. 验收条件 - -### Session/Event - -- 同一命令重放不会重复启动 Turn 或 Tool; -- GUI 在任意事件点断开后能够无损恢复; -- 同 Session 事件顺序稳定,跨 Session 不做虚假保证; -- Stop 后仍运行的子进程会被测试捕获; -- Rust、Python、GUI、CLI 通过同一协议 contract suite。 - -### Evolution - -- Candidate 内容修改会得到新 ID; -- Evaluation policy 在运行开始后不可改变; -- baseline 与 candidate 的环境差异可被检测; -- promotion 原子失败时 active version 不改变; -- rollback 恢复完整状态并校验 hash; -- Candidate 无法修改 Controller、policy 或 verifier; -- L0 自动晋升可全程 replay 和审计。 - -### 语言边界 - -- 关闭 Python fallback 不影响 Rust 支持工具的语义; -- Python worker 崩溃会产生终止事件,Session 不会永久 Running; -- 不支持的 major version 被明确拒绝; -- 未知 minor event 不会导致 GUI/CLI 崩溃。 - ---- - -## 15. 非目标 - -- 第一阶段不实现 Forge 自身代码的自动自修改; -- 不要求所有 Forge 部署都使用集群; -- 不把 GUI 布局写入核心协议; -- 不保证跨 Session 全局事件顺序; -- 不承诺任意外部副作用 exactly-once; -- 不用 Python 内存对象作为持久控制状态; -- 不将工作区 overlay copy 称为完整 rollback。 - ---- - -## 16. 尚待 ADR 决定 - -以下问题不得由实现代码偶然决定: - -1. EventStore 初始格式和 compaction 策略; -2. ArtifactStore 的本地与远程寻址格式; -3. Session 是否允许显式并行 Turn; -4. Model Provider 的流式协议和 usage 计费模型; -5. Evaluation 的统计比较方法; -6. L0 自动晋升的默认 policy; -7. ActorForgeClient 的命名、租约和故障恢复协议; -8. L3 self-hosting 的独立信任根。 diff --git a/docs/src/design/forge/craft-architecture.md b/docs/src/design/forge/craft-architecture.md deleted file mode 100644 index e0a04e62f..000000000 --- a/docs/src/design/forge/craft-architecture.md +++ /dev/null @@ -1,43 +0,0 @@ -# Forge × Craft Architecture - -> **User docs**: [Forge deployment](../../forge/deployment.md) · [Pulsing integration](../../forge/pulsing-integration.md) -> **Status**: Legacy/reference-host integration. The target architecture is [Forge Core Architecture](core-architecture.md), where Forge owns Session and Agent-loop semantics and clients own presentation. - -Review-grade architecture for how Craft (reference Host) consumes Forge on Pulsing Actors. - ---- - -## Layering - -```text -CraftAgent LLM, permissions UI, tool routing -ForgeBackend Host + isolated worker unified entry -Forge 32 tools, sandbox, MCP, events -Pulsing ask/tell, spawn, resolve, gossip -``` - -**Principles** - -- Host owns LLM and product UI; Forge owns workspace execution -- Events via P2P `tell` (not in-process queues) -- Isolated tools in `ToolWorkerActor` child process - ---- - -## Key actors (named) - -| Actor | Name pattern | -|-------|----------------| -| CraftAgent | `craft/ws/{id}/{short}` | -| ForgeEventInbox | `{host}/events` | -| McpHubActor | `craft/ws/{id}/_mcp_hub` | -| CodeCellRegistryActor | `{host}/code_cells` | -| Shared ToolWorkerActor | `craft/ws/{id}/_tools` | - ---- - -## Further reading - -Detailed diagrams, event kinds, and review notes: **`craft-architecture.zh.md`** (Chinese, primary). - -Related: [Engineering](engineering.md) · [Craft architecture](craft-architecture.md) diff --git a/docs/src/design/forge/craft-architecture.zh.md b/docs/src/design/forge/craft-architecture.zh.md deleted file mode 100644 index 4012522d9..000000000 --- a/docs/src/design/forge/craft-architecture.zh.md +++ /dev/null @@ -1,441 +0,0 @@ -# Forge × Craft 一体化架构设计 - -> **状态**:历史实现 / 参考 Host 集成(2026-05) -> **读者**:架构 review、贡献者、Craft / Forge 集成开发 -> **关联**:[engineering.md](./engineering.md) · [../../forge/index.md](../../forge/index.md) · [do../../forge/abstractions.md](../../forge/abstractions.md) -> **目标架构**:[Forge 核心架构](core-architecture.zh.md)。其中 Forge 拥有 Session、Agent loop 与 Evolution 语义,Craft/Agent 不再作为独立状态所有者。 - ---- - -## 1. 摘要 - -Pulsing Forge 提供 Agent **工具与环境运行时**;Craft 是消费 Forge 的 **Multi-Agent 参考应用**。当前架构目标: - -1. **执行下沉 Rust**:工具 handler、PTY、tree-sitter bash、流式 exec 在 `pulsing-forge`;Python 仅薄绑定与 fallback。 -2. **传输统一 Pulsing Actor**:RPC(`ask`/`tell`)、隔离 spawn、gossip 命名解析 — 整条链路在 Pulsing 体系内。 -3. **事件统一 P2P tell**:Forge 生命周期与 exec 流式输出经 `tell("on_forge_event", …)` 投递,同进程与跨进程语义一致(替代进程内直调 `schedule_forge_event`)。 - -**设计原则**:Host 管 LLM / UI / 产品工具;Forge 管 sandbox 内执行;Pulsing 管消息与部署边界。 - ---- - -## 2. 生态分层 - -```mermaid -flowchart TB - subgraph Host["Host 层(产品 / Agent loop)"] - Craft["CraftAgent
LLM · 权限 · TUI · 集群 NPC"] - Other["其他 Host
LangChain / 自研 loop"] - end - - subgraph Transport["Pulsing 传输层(Rust Actor System)"] - RPC["ask / tell / resolve"] - Spawn["spawn · isolated spawn · gossip"] - MB["Actor Mailbox(串行)"] - end - - subgraph ForgePy["Forge Python 绑定"] - Adapter["RustForgeAdapter
pulsing._core.ForgeRuntime"] - Worker["ToolWorkerActor"] - Events["tell_forge_event · ForgeEventPump"] - Fallback["LocalToolRuntime
(无 Rust 时 fallback)"] - end - - subgraph ForgeRust["Forge Rust 核心(pulsing-forge)"] - RT["ToolRuntime"] - Handlers["Handlers
Execution · FS · Session"] - PTY["PTY · UnifiedExec · tree-sitter"] - Sandbox["Sandbox policy"] - end - - Craft --> RPC - Other --> ForgePy - RPC --> Worker - RPC --> Craft - Worker --> Adapter - Craft --> Adapter - Adapter --> RT - Fallback --> Handlers - RT --> Handlers - Handlers --> PTY - Handlers --> Sandbox - Worker --> Events - Adapter --> Events - Events --> RPC -``` - -| 层 | 包 / Crate | 职责 | 不应包含 | -|----|------------|------|----------| -| **Pulsing** | `pulsing-actor`, `pulsing-py` | 分布式 Actor、mailbox、集群 | 工具实现、LLM | -| **Forge** | `pulsing-forge`, `pulsing.forge` | 工具执行、沙箱、ToolSession 协议 | LLM、对话 UI | -| **Craft** | `pulsing.craft` | NPC、Workspace、LLM 编排、产品向工具 | 重复实现 shell/patch | - ---- - -## 3. 整体架构图 - -```mermaid -flowchart LR - subgraph Client["调用方"] - User["用户 / CLI / TUI"] - Peer["其他 NPC / 集群 Agent"] - end - - subgraph CraftAgent["CraftAgent(@pul.remote)"] - direction TB - LLM["LlmChat · tool loop"] - Router["tool_host.call_tool
工具路由"] - ForgeHost["RustForgeAdapter / ForgeHostLink
Host 工具"] - Handler["on_forge_event
handle_forge_event"] - Session["CraftForgeSession
plan · 权限 callback"] - end - - subgraph Worker["ToolWorkerActor(隔离)"] - direction TB - WRust["RustForgeAdapter(默认)"] - WPump["ForgeEventPump"] - WPy["LocalToolRuntime(fallback)"] - end - - subgraph Rust["pulsing-forge + pulsing-py"] - FR["ForgeRuntime.call_tool"] - end - - User --> LLM - Peer -->|deliver_message| LLM - LLM --> Router - Router -->|FORGE_ISOLATED| Worker - Router -->|FORGE_HOST| ForgeHost - Router -->|Craft 本地| Router - Worker --> WRust - WRust --> FR - ForgeHost --> FR - WPump -->|tell| Handler - ForgeHost -->|emit → tell| Handler - Router -->|emit_forge_event → tell| Handler - Handler --> Session - Handler -->|stream chunks| TUI["chat_stream / dashboard"] -``` - -**命名约定(Workspace Agent)**: - -- Agent gossip 名:`craft/ws//` -- 事件 sink(`_event_sink_name`):与 Agent 全名相同 -- 共享工具 worker:`tools/ws//_tools`(可选) - ---- - -## 4. 工具路由矩阵 - -Craft 将所有 LLM 暴露的工具按执行位置分为四类: - -| 类别 | 工具名 | 执行位置 | 运行时 | -|------|--------|----------|--------| -| **Forge 隔离** | `Read`, `Glob`, `Grep`, `Edit`, `Write`, `Bash`, `shell_command`, `exec_command`, `write_stdin`, `apply_patch`, `view_image` | `ToolWorkerActor`(子进程 / 共享 worker) | `RustForgeAdapter` → `ForgeRuntime` | -| **Forge Host** | `update_plan`, `new_context`, `get_context_remaining`, `request_user_input` | CraftAgent 进程内 | `RustForgeAdapter` + `PyForgeSession` | -| **Craft 本地** | `FetchUrl`, `Summon`, `QuestReport`, … | CraftAgent 进程内 | Python `Tool.execute` | -| **集群** | `ListClusterAgents`, `MessageClusterAgent` | 跨 Agent RPC | `dispatch_cluster_tool` | - -定义来源:`python/pulsing/forge/integrated.py`、`python/pulsing/craft/runtime/constants.py`。 - -```mermaid -flowchart TD - TC["LLM tool_call"] --> R{"tool_host.call_tool"} - R -->|CLUSTER| C["dispatch_cluster_tool"] - R -->|NPC| S["tool_summon"] - R -->|QUEST| Q["tool_quest_report"] - R -->|FORGE_HOST| H["RustForgeAdapter.call_tool"] - R -->|FORGE_ISOLATED| I["ToolWorkerActor.call_tool"] - R -->|Craft 本地| L["local Tool.execute"] - I --> Rust["pulsing-forge"] - H --> Rust - L --> E["emit_forge_event → tell"] - H --> E - I --> E -``` - ---- - -## 5. 执行路径(Rust 优先) - -### 5.1 Rust 栈 - -``` -pulsing._core.ForgeRuntime # PyO3,crates/pulsing-py/src/forge.rs - └── pulsing_forge::ToolRuntime - ├── handlers/ # execution, filesystem, session, plan - ├── unified_exec/ # exec_command 会话 + 流式 - ├── pty_session/ # portable-pty - └── patch/heredoc/ # tree-sitter bash -``` - -### 5.2 Python 适配 - -| 组件 | 文件 | 行为 | -|------|------|------| -| `RustForgeAdapter` | `python/pulsing/forge/rust_runtime.py` | 包装 `ForgeRuntime`;`event_callback` 转发为 `ForgeEvent` | -| `ToolWorkerActor` | `python/pulsing/forge/worker.py` | `on_start` 初始化 Rust;`call_tool` 优先 Rust | -| `ForgeHostLink` | `python/pulsing/forge/integrated.py` | 无 Rust 时的 Python Host fallback | -| `init_forge_host` | `python/pulsing/craft/agent/forge_runtime.py` | Craft 启动时挂 Host runtime | - -### 5.3 Fallback 策略 - -``` -if RUST_FORGE_AVAILABLE: - 使用 RustForgeAdapter -else: - LocalToolRuntime + Python handlers(开发 / 未 maturin 构建) -``` - -构建要求:`uv run maturin develop` 安装含 `ForgeRuntime` 的 `pulsing._core`。 - ---- - -## 6. 事件架构(P2P tell) - -Forge 不使用中心事件总线;所有通知走 **点对点 Actor tell**,绑定 Pulsing 语义。 - -### 6.1 事件信封 - -```python -@dataclass -class ForgeEvent: - kind: str # tool_begin | tool_end | exec_output_delta | plan_updated | ... - payload: dict - source: str | None # 通常为 tool 名 - ts: float -``` - -### 6.2 投递路径(统一) - -```mermaid -sequenceDiagram - participant W as ToolWorkerActor - participant P as ForgeEventPump - participant R as pul.resolve(sink) - participant A as CraftAgent - participant H as handle_forge_event - - Note over W,A: 跨 Actor(exec 流式、隔离工具) - W->>P: emit_sync(ForgeEvent) - P->>R: tell_forge_event(sink, event) - R->>A: tell("on_forge_event", payload) - A->>H: await handle_forge_event - - Note over A: Host / Craft 本地工具(同 sink) - A->>R: emit_forge_event → tell_forge_event - R->>A: tell("on_forge_event", payload) - A->>H: await handle_forge_event -``` - -**核心 API**(`python/pulsing/forge/p2p_transport.py`): - -```python -async def tell_forge_event(sink_name: str, event: ForgeEvent) -> None: - proxy = await pul.resolve(sink_name) - await proxy.as_any().tell("on_forge_event", event.to_dict()) -``` - -**Host 侧 emit**(`python/pulsing/craft/agent/forge_events.py`): - -- `emit_forge_event` / `emit_forge_event_sync` → 内部调用 `tell_forge_event` -- `make_host_emit(agent)` → 供 Rust `PyForgeSession` 回调使用 -- ~~`schedule_forge_event`~~ 已移除(进程内直调) - -### 6.3 事件种类与消费 - -| kind | 来源 | Host 行为 | -|------|------|-----------| -| `tool_begin` / `tool_end` | Runtime 包装 | 记录 `_forge_events`;可选转发 TUI stream | -| `exec_output_delta` | UnifiedExec / PTY | 更新 activity;`forge_exec_delta` stream chunk | -| `plan_updated` | Session 工具 | 同步 `CraftForgeSession.plan` | -| `new_context` | Session 工具 | 置 `new_context_requested` | -| `user_input_request` | Session 工具 | 触发权限 / prompt callback | - -### 6.4 Mailbox 串行性(Review 注意点) - -CraftAgent mailbox **串行**:在 `call_tool` 处理完成前,tell 到自身的 `on_forge_event` 会排队。 - -| 场景 | 影响 | -|------|------| -| Worker → Host exec 流式 | ✅ 不同 Actor,实时 | -| Host 工具 `tool_begin/end` | ⚠️ 可能延迟到 call 结束 | -| Host 侧 exec(不应走 Host 路径) | N/A — exec 在隔离 worker | - -若未来需要 Host 进程内实时 exec 流,可选方案:**独立 ForgeEventInbox Actor**(`{agent_name}/events`)。 - ---- - -## 7. 部署拓扑 - -### 7.1 单节点开发 - -```mermaid -flowchart TB - subgraph Process["同一 Pulsing 节点"] - CA["CraftAgent"] - TW["ToolWorkerActor
new_process=True"] - end - CA -->|ask call_tool| TW - TW -->|tell on_forge_event| CA -``` - -### 7.2 Workspace 共享 Worker - -```mermaid -flowchart TB - subgraph WS["Workspace cluster_id = X"] - A1["CraftAgent / alice"] - A2["CraftAgent / bob"] - SW["ToolWorkerActor
tools/ws/X/_tools"] - end - A1 -->|ask| SW - A2 -->|ask| SW - SW -->|tell| A1 - SW -->|tell| A2 -``` - -配置:`NpcConfig.shared_tool_worker=True` → `resolve_shared_tool_worker(workspace_id)`。 - -### 7.3 多节点(Gossip) - -- 命名 Actor 通过 SWIM/gossip 注册与解析 -- `tell_forge_event` 与本地 `ask` 使用相同 `pul.resolve(name)` 路径 -- 工具执行在 worker 所在节点;事件 tell 路由到 host 注册节点 - ---- - -## 8. 关键模块索引 - -| 模块 | 路径 | 说明 | -|------|------|------| -| Rust handlers | `crates/pulsing-forge/src/` | 工具实现 | -| PyO3 Forge | `crates/pulsing-py/src/forge.rs` | `ForgeRuntime` | -| Forge Python API | `python/pulsing/forge/` | 环境、worker、事件、Rust 适配 | -| Craft 工具路由 | `python/pulsing/craft/agent/tool_host.py` | `call_tool` 分发 | -| Craft Forge 集成 | `python/pulsing/craft/agent/forge_*.py` | Host runtime、事件处理 | -| 工具 Schema | `python/pulsing/craft/runtime/forge_tools.py` | LLM 工具定义 | -| 测试 | `tests/python/test_pulsing_forge.py`, `test_forge_*.py`, `craft/test_forge_events.py` | | - ---- - -## 9. 设计取舍 - -| 能力 | 常见 agent runtime | Pulsing Forge + Craft | -|------|-------------------|------------------------| -| 工具执行 | 单进程 Rust core | `pulsing-forge` + PyO3 + 可选 Actor worker | -| 事件 | 进程内 event bus | **Actor tell(P2P)** | -| 隔离 | OS sandbox / 容器 | Sandbox policy + `ToolWorkerActor` spawn | -| 仍在推进 | 完整 hosted search、MCP 产品 UI | 见 §10 | - ---- - -## 10. 路线图 - -| 阶段 | 内容 | 状态 | -|------|------|------| -| **P0** | Rust handlers MVP + Python 镜像 | ✅ | -| **P1** | PTY、exec 流式、`ExecOutputDelta` | ✅ | -| **P2** | PyO3 `ForgeRuntime` + Worker/Host 切 Rust | ✅ | -| **P3** | 事件统一 `tell_forge_event` | ✅ | -| **P4** | 移除 Python 双实现(仅 fallback) | 待做 | -| **P5** | Craft 本地工具注册进 Forge / Rust | 待做 | -| **P6** | TUI 接 `forge_exec_delta` / plan stream | 待做 | -| **P7** | OS 级 sandbox 集成测试(seatbelt/bwrap) | 待做 | -| **P8** | MCP、execpolicy、VirtualNamedActor | 待做 | - ---- - -## 11. Review 检查清单 - -### 架构 - -- [ ] Host / Forge / Pulsing 边界是否清晰?产品逻辑是否只在 Craft? -- [ ] 隔离工具是否都在 Worker,Session 工具是否都在 Host? -- [ ] 事件是否全部可经 `tell_forge_event` 追踪(无隐藏直调)? - -### 正确性 - -- [ ] Rust fallback 路径是否与 Rust 路径行为一致(测试覆盖)? -- [ ] 共享 worker 下 `_event_sink` per-call 覆盖是否正确? -- [ ] `request_user_input` 在 Rust 路径是否调到 Craft `prompt_callback`? - -### 性能与 UX - -- [ ] exec 流式是否仅依赖 Worker→Host tell(不阻塞 Host mailbox)? -- [ ] Host 工具 begin/end 延迟是否可接受? - -### 安全 - -- [ ] PTY / exec 是否 bypass sandbox?文档是否说明? -- [ ] 隔离 spawn 是否默认用于不可信代码路径? - -### 运维 - -- [ ] `maturin develop` 是否为 Craft 开发文档中的必需步骤? -- [ ] 多节点 resolve 超时与 worker 重试策略是否足够? - ---- - -## 12. 相关文档 - -| 文档 | 说明 | -|------|------| -| [../../forge/index.md](../../forge/index.md) | Forge 产品介绍 | -| [do../../forge/abstractions.md](../../forge/abstractions.md) | Environment / Session 抽象 | -| [design/engineering.md](./engineering.md) | Forge 工程说明与 vendor | -| [design/naming.md](./naming.md) | 包命名 | -| [design/craft-npc-refactor.md](./craft-npc-refactor.md) | Craft NPC 重构 | -| [包内 README](https://github.com/DeepLink-org/pulsing/blob/main/python/pulsing/forge/README.md) | API 速查 | -| [python/pulsing/craft/README.md](../../python/pulsing/craft/README.md) | Craft 使用说明 | - ---- - -## 附录 A:端到端时序(隔离工具 + 流式 exec) - -```mermaid -sequenceDiagram - participant LLM as LlmChat - participant CA as CraftAgent - participant TW as ToolWorkerActor - participant Rust as ForgeRuntime - participant Shell as PTY / subprocess - - LLM->>CA: tool_call exec_command - CA->>TW: ask call_tool("exec_command", ...) - TW->>Rust: call_tool (Rust) - Rust->>Shell: UnifiedExec - loop stdout/stderr chunks - Shell-->>Rust: output delta - Rust-->>TW: PyForgeSession.on_exec_output_delta - TW->>CA: tell on_forge_event (exec_output_delta) - CA->>CA: handle_forge_event → stream / activity - end - Rust-->>TW: ToolResult - TW->>CA: tell tool_end - TW-->>CA: ask response (ToolResult dict) - CA-->>LLM: tool result text -``` - ---- - -## 附录 B:目录结构(精简) - -``` -crates/ - pulsing-forge/ # Rust 工具运行时 - pulsing-py/src/forge.rs # PyO3 绑定 - -python/pulsing/ - forge/ - worker.py # ToolWorkerActor - rust_runtime.py # RustForgeAdapter - p2p_transport.py # tell_forge_event - events.py # ForgeEvent - integrated.py # 工具分区 + ForgeHostLink - craft/agent/ - tool_host.py # 工具路由 - forge_events.py # emit_forge_event - forge_runtime.py # init_forge_host - forge_session.py # CraftForgeSession -``` diff --git a/docs/src/design/forge/engineering.md b/docs/src/design/forge/engineering.md deleted file mode 100644 index db80a5add..000000000 --- a/docs/src/design/forge/engineering.md +++ /dev/null @@ -1,43 +0,0 @@ -# Forge Engineering Notes - -> **User docs**: [Forge chapter](../../forge/index.md) · [Abstractions](../../forge/abstractions.md) -> **Package API**: [python/pulsing/forge/README.md](https://github.com/DeepLink-org/pulsing/blob/main/python/pulsing/forge/README.md) -> **Target architecture**: [Forge Core Architecture](core-architecture.md). This page describes the current implementation. - -Implementation-focused notes for `pulsing-forge` (Rust) and `pulsing.forge` (Python). - ---- - -## Crates and modules - -| Layer | Path | -|-------|------| -| Rust handlers | `crates/pulsing-forge/` | -| PyO3 binding | `crates/pulsing-py/src/forge.rs` → `pulsing._core.ForgeRuntime` | -| Python API | `python/pulsing/forge/` | -| Craft Host | `python/pulsing/craft/agent/forge_*.py` | - ---- - -## Architecture - -```text -Host (LLM + ToolSession) - → HybridForgeRuntime / ToolWorkerActor - → pulsing-forge ToolRuntime - → handlers + sandbox + MCP - → tell_forge_event → ForgeEventInbox → Host -``` - ---- - -## Related design docs - -| Doc | Topic | -|-----|-------| -| [Core architecture](core-architecture.md) | Target boundaries and versioned protocols | -| [Craft architecture](craft-architecture.md) | Forge × Craft integration | -| [Naming](naming.md) | Package and gossip names | -| [Session REPL](session-repl.md) | `pulsing forge repl` trace/replay | - -Full Chinese engineering detail: see `engineering.zh.md` in this directory. diff --git a/docs/src/design/forge/engineering.zh.md b/docs/src/design/forge/engineering.zh.md deleted file mode 100644 index 1fea2be83..000000000 --- a/docs/src/design/forge/engineering.zh.md +++ /dev/null @@ -1,159 +0,0 @@ -# Pulsing Forge 工程说明(`pulsing-forge`) - -> **产品文档**(面向用户):[../../forge/index.md](../../forge/index.md) · [abstractions.md](../../forge/abstractions.md) -> -> **API 速查**:[python/pulsing/forge/README.md](https://github.com/DeepLink-org/pulsing/blob/main/python/pulsing/forge/README.md) -> -> **范围**:本文描述当前实现。目标产品边界、版本化 Session/Event/Evolution 协议以 [Forge 核心架构](core-architecture.zh.md) 为准。 - ---- - -## 1. 是什么 - -**Pulsing Forge** 提供 AI Agent 的**通用工具与环境运行时**: - -- 在指定 **workspace** 里执行 shell、应用 patch、读写文件 -- 通过 **sandbox** 约束权限(off / restricted / bwrap) -- 通过 **ToolSession** 把 plan、用户输入、token 预算交还给 Host(Forge 不做 UI) - -Forge 是 **库**,不是完整 Agent 产品:不包含 LLM 调用、对话管理、登录或云同步。 - ---- - -## 2. 命名与生态 - -| 品牌 | 代码 | -|------|------| -| **Pulsing Forge** | `pulsing.forge` · crate `pulsing-forge` | -| **Pulsing** | Actor 集群与 RPC | -| **Craft** | Multi-Agent 参考应用 | - -```text -Pulsing → 通信与部署 -Pulsing Forge → 工具与环境 -Craft → 产品级 Multi-Agent(消费 Forge) -``` - -命名定案:[naming.md](./naming.md) - ---- - -## 3. 抽象(实现映射) - -| 概念 | Python | Rust | -|------|--------|------| -| Environment | `ForgeEnvironment` | `ToolRuntimeConfig` / `ToolCallContext` | -| Runtime | `LocalToolRuntime` | `ToolRuntime` | -| Host hooks | `ToolSession` | `trait ToolSession` | -| Result | `ToolResult` | `ToolResult` | -| 远程 worker | `ToolWorkerActor` | Rust `ForgeRuntime`(PyO3);Python fallback | -| PyO3 绑定 | `RustForgeAdapter` | `pulsing._core.ForgeRuntime` | - -详见 [abstractions.md](../../forge/abstractions.md)。 - ---- - -## 4. 架构 - -``` -Host(Agent loop / Craft / CLI) - │ LLM + UI + ToolSession impl - ▼ -RustForgeAdapter / ForgeEnvironment / ToolWorkerActor - ▼ -pulsing._core.ForgeRuntime → pulsing-forge ToolRuntime - ▼ -handlers + sandbox + PTY + UnifiedExec - │ - └─► tell_forge_event → Host.on_forge_event(P2P 事件) -``` - -**边界**: - -- Handler + sandbox = Forge 库(无 Actor、无 UI) -- Session 副作用 = `ToolSession` 回调 -- 隔离与 gossip = Pulsing `ToolWorkerActor` -- 事件 = Actor `tell`(见 [craft-architecture.md](./craft-architecture.md)) - -**一体化架构(Review)**:[craft-architecture.md](./craft-architecture.md) - ---- - -## 5. 工具域(当前 MVP) - -| 域 | 工具 | 状态 | -|----|------|------| -| Execution | `shell_command`, `exec_command`, `write_stdin`, `Bash` | 标准 wire 参数 + patch 拦截 + UnifiedExec 会话 | -| Filesystem | `apply_patch`, `view_image`, `Read/Glob/Grep/Edit/Write` | patch 验证 + 结构化 image 输出 | -| Session | `update_plan`, `new_context`, `get_context_remaining`, `request_user_input` | 经 `ToolSession` | - ---- - -## 6. 仓库布局 - -``` -crates/pulsing-forge/ # Rust handlers + sandbox -python/pulsing/forge/ # Python API + ToolWorkerActor -docs/src/forge/ # 产品介绍与抽象 -``` - ---- - -## 7. Actor API(Python) - -```python -@pul.remote -class ToolWorkerActor: - def call_tool(self, name: str, arguments: dict) -> dict: ... -``` - -| 模式 | 用法 | -|------|------| -| 进程内 | `ForgeEnvironment(...).runtime()` | -| 隔离子进程 | `ToolWorkerActor.spawn(..., new_process=True)` | -| 共享 worker | `name="craft/ws/{id}/_tools", public=True` | - ---- - -## 8. 路线图 - -| Phase | 内容 | 状态 | -|-------|------|------| -| 0 | 文档 + crate 空壳 + vendor | ✅ | -| 1 | Environment 抽象 + 三域工具 MVP | ✅ | -| 2 | UnifiedExec、PTY、tree-sitter、PyO3 ForgeRuntime | ✅ | -| 3 | Craft 集成:Rust worker/host + P2P tell 事件 | ✅ | -| 4 | 移除 Python 双实现、TUI stream、OS sandbox 测试 | 待做 | -| 5 | MCP、execpolicy、VirtualNamedActor | 待做 | - ---- - -## 9. 参考实现(贡献者) - -部分 handler(patch 解析、沙箱策略等)在开发阶段参考了业界开源 agent-tool 实践。**产品文档不展开对照表**;贡献者维护 vendor 与 sync 脚本时见仓库内 `vendor/` 与 `scripts/sync-codex-forge.sh`。 - -禁止引入完整 agent CLI / 登录 / TUI 等产品层 crate。 - ---- - -## 10. 相关文档 - -- [../../forge/index.md](../../forge/index.md) — **主介绍** -- [craft-architecture.md](./craft-architecture.md) — **Forge × Craft 一体化架构(Review)** -- [../../forge/abstractions.md](../../forge/abstractions.md) — 抽象详解 -- [testing.md](./testing.md) — **测试体系(L0–L4)** -- [naming.md](./naming.md) — 包名与路径 -- [craft-npc-refactor.md](./craft-npc-refactor.md) — Craft 集成(后续) - ---- - -## 11. 验收 - -- [x] `cargo test -p pulsing-forge` -- [x] `pytest tests/python/test_pulsing_forge.py` -- [x] `ForgeEnvironment` 公开 API -- [x] 产品文档 `docs/forge/` -- [ ] sandbox 集成测试(seatbelt / bwrap) -- [x] Craft 默认 Rust backend(`RustForgeAdapter`) -- [x] Forge 事件统一 `tell_forge_event` -- [ ] 移除 Python handler 双实现(仅 fallback) diff --git a/docs/src/design/forge/naming.md b/docs/src/design/forge/naming.md deleted file mode 100644 index a5c203e65..000000000 --- a/docs/src/design/forge/naming.md +++ /dev/null @@ -1,21 +0,0 @@ -# Forge Naming - -| Symbol | Package / path | -|--------|----------------| -| **Pulsing Forge** | `pulsing.forge` · crate `pulsing-forge` | -| **Pulsing** | Actor runtime | -| **Craft** | Reference Multi-Agent app | - -## Gossip names - -| Resource | Pattern | -|----------|---------| -| Craft agent | `craft/ws/{workspace_id}/{short_name}` | -| Shared tool worker | `craft/ws/{workspace_id}/_tools` | -| Forge event inbox | `{host}/events` | -| MCP hub | `craft/ws/{workspace_id}/_mcp_hub` | -| Code cell registry | `{host}/code_cells` | - -Implementation: `python/pulsing/forge/naming.py` - -Details: **`naming.zh.md`** (Chinese, primary). diff --git a/docs/src/design/forge/naming.zh.md b/docs/src/design/forge/naming.zh.md deleted file mode 100644 index c393f2cbd..000000000 --- a/docs/src/design/forge/naming.zh.md +++ /dev/null @@ -1,58 +0,0 @@ -# Pulsing Forge — 命名定案 - -> **对外品牌**:**Pulsing Forge** -> -> **代码包名**:Rust `pulsing-forge`,Python `pulsing.forge` - ---- - -## 1. 定案 - -| 层级 | 名称 | -|------|------| -| **产品 / 文档** | **Pulsing Forge** | -| **Python import** | `pulsing.forge` | -| **Rust crate** | `pulsing-forge`(lib:`pulsing_forge`) | -| **pip extra** | `pulsing[forge]`(计划;当前可用 `pip install pulsing`) | -| **兼容** | `pulsing.tools` → 已废弃,re-export `pulsing.forge` | - ---- - -## 2. 路径对照(rename 后) - -| 旧路径 | 新路径 | -|--------|--------| -| `crates/pulsing-tools/` | `crates/pulsing-forge/` | -| `python/pulsing/tools/` | `python/pulsing/forge/` | -| `docs/design/pulsing-tools.md` | `do../design/forge/engineering.md` | -| `scripts/sync-codex-tools.sh` | `scripts/sync-codex-forge.sh` | -| `tests/python/test_pulsing_tools.py` | `tests/python/test_pulsing_forge.py` | -| `examples/python/tools_minimal.py` | `examples/python/forge_minimal.py` | - ---- - -## 3. 生态名称 - -```text -Pulsing → pulsing Actor 运行时 -Pulsing Forge → pulsing.forge Tool + Sandbox -Craft → pulsing.craft Multi-Agent 应用 -``` - ---- - -## 4. 文档 - -- [../../forge/index.md](../../forge/index.md) — 产品介绍 -- [do../../forge/abstractions.md](../../forge/abstractions.md) — 抽象模型 - ---- - -## 5. Checklist - -- [x] 品牌:**Pulsing Forge** -- [x] Rust crate / Python 包路径 rename -- [x] `pulsing.tools` 兼容 shim(DeprecationWarning) -- [x] 主仓 README.zh 增加 Pulsing Forge 小节 -- [x] `pyproject.toml` 增加 `pulsing[forge]` extra -- [x] 产品文档 `docs/forge/` diff --git a/docs/src/design/forge/session-repl.md b/docs/src/design/forge/session-repl.md deleted file mode 100644 index 176307d60..000000000 --- a/docs/src/design/forge/session-repl.md +++ /dev/null @@ -1,24 +0,0 @@ -# Forge Session REPL - -Interactive REPL for driving Forge tools without an LLM — trace record/replay for debugging and regression. - ---- - -## Entry points - -```bash -pulsing forge repl --cwd . -python -m pulsing.forge.repl # Python-only -cargo run -p pulsing-forge --bin pulsing-forge-repl -- --cwd . # dev: Rust only -``` - -Examples: `Read --file_path README.md` · `/tools` · `/approve ask` - ---- - -## Purpose - -- JSONL trace save/replay (`--trace`, `--record`, `--replay-all --verify`) -- Complements pytest for integration and regression tests - -Full spec (Rust vs Python, slash commands): **`session-repl.zh.md`** (Chinese, primary). diff --git a/docs/src/design/forge/session-repl.zh.md b/docs/src/design/forge/session-repl.zh.md deleted file mode 100644 index 42779294b..000000000 --- a/docs/src/design/forge/session-repl.zh.md +++ /dev/null @@ -1,153 +0,0 @@ -# Forge Session REPL - -> **状态**:MVP 已实现 · **入口**:`pulsing forge repl`(优先 Rust `pulsing-forge-repl`,否则 Python fallback) -> **关联**:[craft-architecture.md](./craft-architecture.md) - -## 快速开始 - -```bash -pulsing forge repl --cwd . -pulsing forge repl --trace tests/fixtures/forge_traces/read_sample.jsonl --replay-all --verify -pulsing forge repl --record /tmp/session.jsonl -``` - -Nushell 风格:`Read --file_path README.md` · `/tools` · `/approve ask` · Tab 补全 · 行内灰色 hint - -**Shell UX(Rust `pulsing-forge-repl`)** - -| 能力 | 说明 | -|------|------| -| Tab 补全 | `/` slash(含 alias)、`@` 文件 mention、meta、工具名、`--flag` | -| Slash 内置 | `/ps` `/stop`(`/clean`) `/diff` `/review` `/fork N` `/compact` `/mcp` `/plugins` `/rollout` `/copy` `/clear` | -| 常用别名 | `/status`→session · `/permissions`/`/approve`→审批 · `/clean`→stop · `/exit`→quit | -| Mention | `@path` 或 `/mention path` → Read 预览 | -| 审批 | `/permissions auto\|ask` 接通 ReplToolSession | - ---- - -## Rust-first vs Python fallback - -| | **Rust(经 `pulsing forge repl`)** | **Python(`--python` 或 fallback)** | -|--|-------------------|----------------------------------| -| 主循环 / 终端 | `reedline`(Tab 补全 + hint + ColumnarMenu)+ `comfy-table` | 裸 `input()` | -| 工具 runtime | `ToolRuntime`(22 个 Rust handler) | `LocalToolRuntime`(32 工具全可用) | -| 依赖 | 无 Python 环境冲突 | 需项目 venv / maturin | -| 适用 | 日常调试、CI replay、终端体验 | Extension / exec / Code Mode 等 Python-only 工具 | - -**方向**:Shell 主循环与渲染放 Rust(类似 Nushell 思路);Python REPL 保留作 hybrid dispatch 完成前的 fallback 与全工具覆盖。 - ---- - -## 结论 - -**值得做。** 在 Forge 层提供 **Session REPL**,直接绑定 `ToolSession` + `ToolRuntime`(而非 Craft 全量 Agent loop),同时服务: - -1. **Replay** — 按序重放某次 Agent 轨迹里的 tool call + forge event,用于调试与回归 -2. **Manual drive** — 人工逐步调用工具、改 session 状态、模拟审批,干预或替代 LLM 决策 - -Forge REPL 是 **headless、可脚本化** 的 session 控制台(类似 gdb/lldb 对 runtime,而不是聊天 UI)。 - ---- - -## 放哪一层 - -| 层 | 职责 | -|----|------| -| **Forge REPL** | 绑定 `ToolCallContext` / `ToolSession`;执行 `call_tool`;记录/回放 **trace**;Host 回调可插拔(自动审批 / 交互式 y/n) | -| **Craft** | 从 `CraftAgent` **导出 trace**;可选「调试暂停 → 附着 Forge REPL」;不负责重复实现 shell/patch | -| **Pulsing** | 可选:REPL 附着远程 `ToolWorkerActor`(同一 trace 格式) | - -``` -Agent 轨迹 (Craft) Forge Session REPL - │ │ - ├─ export trace.jsonl ────────►│ replay / fork - │ │ - └─ pause & attach ─────────────►│ manual :call / :approve - │ - ToolRuntime + Session - (Local / Rust / Worker RPC) -``` - ---- - -## Trace 格式(单一事实源) - -每条记录一行 JSON(JSONL),便于 diff 与 CI: - -```json -{"seq": 1, "kind": "tool_call", "tool": "Read", "arguments": {"file_path": "a.py"}, "result": {"content": "...", "is_error": false}} -{"seq": 2, "kind": "forge_event", "event": {"kind": "tool_begin", "source": "Read", ...}} -{"seq": 3, "kind": "tool_call", "tool": "shell_command", "arguments": {...}, "result": {...}} -{"seq": 4, "kind": "session", "plan": [...], "tokens_remaining": 120000} -``` - -**来源**: - -- Craft:`tool_host.call_tool` 前后 + `_forge_events` 合并导出 -- 未来:第三方会话导出适配器(仅 tool 层,不含 LLM messages) - -**Replay 语义**: - -| 模式 | 行为 | -|------|------| -| `--dry-run` | 只打印将执行的 call,不改 workspace | -| `--verify` | 重跑并对比 result / event(集成回归) | -| `--from N` | 从第 N 步继续 | -| `--fork N` | 加载 0..N 步 session 快照,之后进入 **interactive**(人工干预) | - ---- - -## REPL 能力(MVP → 完整) - -### MVP - -- 启动:`pulsing forge repl [--cwd] [--sandbox] [--trace file.jsonl]` -- 命令: - - `call ` — 调 `runtime.call_tool` - - `replay [step]` — 逐步重放 trace - - `plan` / `session` — 看 `ToolSession` 状态 - - `events` — 最近 `ForgeEvent` - - `approve auto|ask` — 切换 exec/permissions 回调 -- 实现:`ForgeReplSession` 包装 `ForgeHostLink` 或 `LocalToolRuntime` + `LocalToolSession` - -### 二期 - -- 附着 **UnifiedExec** / **Code Mode cell**(`:exec attach `) -- 附着 **CraftAgent**(debug 模式,暂停 LLM turn) -- Worker RPC 模式(REPL 远程调 `ToolWorkerActor`) -- `replay --verify` 接入 CI(集成回归 fixture) - ---- - -## 回归与验证 - -| 场景 | REPL 作用 | -|------|-----------| -| 集成回归 | `replay --verify trace/fixtures/*.jsonl` 证明端到端 | -| 人工 sign-off | 专家用 REPL 逐步验证工具行为 | -| 故障复现 | Agent 失败轨迹导出 → 最小复现 → 修 Forge → replay 绿 | - ---- - -## 不做的事 - -- 不做 Craft 完整对话 TUI(已有/将有的产品 UI 层) -- 不在 REPL 里跑 LLM turn(只驱动 **Forge 工具面**) -- 不默认做 filesystem 时间旅行(replay 默认在同一 cwd;需要时可接 snapshot 插件) - ---- - -## 建议落地顺序 - -1. **`ForgeReplSession` + JSONL trace 读写**(Forge 内,`python/pulsing/forge/repl/`) -2. **Craft `trace export`**(从现有 `_forge_events` + tool loop 钩子) -3. **`replay --verify`** + 1–2 条 fixture(patch、shell 审批) -4. CLI 入口 + 文档 - -**前置依赖**:Hybrid dispatch(Rust 路径下 Host 工具可调用),否则 replay 在 maturin 默认构建下会卡在 Python-only 工具。 - ---- - -## 维护 - -改 REPL / trace 格式时同步更新 Craft export 与 `tests/fixtures/forge_traces/`(待建)。 diff --git a/docs/src/design/forge/testing.md b/docs/src/design/forge/testing.md deleted file mode 100644 index ebdc05f0e..000000000 --- a/docs/src/design/forge/testing.md +++ /dev/null @@ -1,20 +0,0 @@ -# Forge Testing - -> **Audience**: Forge contributors, CI maintainers -> **See also**: [engineering.md](./engineering.md) · [session-repl.md](./session-repl.md) - -Forge tests are organized in **L0–L4** layers. We reuse portable fixture layouts from the agent-tool ecosystem (notably `apply_patch` scenario directories) while asserting **Pulsing Forge** behavior. - -Full detail: **`testing.zh.md`** (Chinese, primary). - ---- - -## Quick commands - -```bash -pytest tests/python/forge/ -m forge -q -cargo test -p pulsing-forge apply_patch_scenarios -maturin develop # required for Hybrid L1/L2 -``` - -Shared harness: `python/pulsing/testing/forge_harness.py` diff --git a/docs/src/design/forge/testing.zh.md b/docs/src/design/forge/testing.zh.md deleted file mode 100644 index 1f38c9e50..000000000 --- a/docs/src/design/forge/testing.zh.md +++ /dev/null @@ -1,107 +0,0 @@ -# Forge 测试体系 - -> **读者**:Forge 贡献者、CI 维护者 -> **关联**:[engineering.md](./engineering.md) · [session-repl.md](./session-repl.md) - -Forge 测试按 **L0 → L4** 分层,借鉴了业界 agent-tool 生态的 fixture 思路(尤其是 `apply_patch` 场景目录),但断言的是 **Pulsing Forge 自身行为**,不对外做产品级「迁移对照」宣传。 - ---- - -## 分层(Test Pyramid) - -| 层 | 含义 | 位置 | -|----|------|------| -| **L0** | 32 工具已注册、Host/隔离分区正确 | `tests/python/forge/test_gates.py` | -| **L1** | 每个工具默认可调用(无 `Unknown tool`) | 同上 + `test_hybrid_forge_callable.py` | -| **L2** | Wire 形状与关键副作用(Read 内容、patch 落盘、session plan) | `tests/python/forge/test_wire.py` | -| **L3** | 场景 fixture、JSONL trace replay | `tests/python/forge/test_integration.py`、Rust patch scenarios | -| **L4** | Pulsing Actor(inbox、MCP hub、worker) | `test_forge_p0_actors.py` 等 | - -共享基础设施:`python/pulsing/testing/forge_harness.py`(minimal args、smoke runner、wire check 注册表)。 - -内部 conformance 分数:`python/pulsing/forge/codex_parity.py`(CI 用,文档站不链出)。 - ---- - -## 怎么跑 - -```bash -# Forge 全部分层(推荐 CI) -pytest tests/python/forge/ -m forge -q - -# 仅注册 + callable -pytest tests/python/forge/ -m "forge_l0 or forge_l1" -q - -# Rust:apply_patch 场景(复用 vendor codex-rs fixtures) -cargo test -p pulsing-forge apply_patch_scenarios - -# Rust crate 单元测试 -cargo test -p pulsing-forge - -# 与 Craft 交叉 -pytest tests/python/craft/test_forge_events.py tests/python/craft/test_tools.py -q -``` - -需要 Hybrid 路径时先 `maturin develop`。 - ---- - -## apply_patch 场景 fixture - -Rust 集成测试读取: - -```text -vendor/codex-rs/apply-patch/tests/fixtures/scenarios/ - 001_add_file/ - input/ - expected/ - patch.txt -``` - -每个场景:复制 `input/` → 在临时目录执行 patch → 对比 `expected/` 文件树快照。布局与 codex-apply-patch 一致,便于跨语言复用。 - -实现:`crates/pulsing-forge/tests/apply_patch_scenarios.rs` - ---- - -## 扩展 L2 wire check - -在 `forge_harness.py` 中: - -```python -from pulsing.testing.forge_harness import register_wire_check - -def _check_my_tool(rt, tmp_path, out): - assert not out.is_error - ... - -register_wire_check("my_tool", _check_my_tool) -``` - -`test_wire.py` 会自动 parametrized 跑所有已注册工具。 - ---- - -## Trace replay(L3 / L4) - -JSONL 格式见 [session-repl.md](./session-repl.md)。Fixture:`tests/fixtures/forge_traces/`。 - -`replay --verify` 语义:重跑 tool call 并对比 recorded result — 用于 Agent 失败轨迹的最小复现。 - ---- - -## 新增工具时的清单 - -1. 加入 `integrated.py` 的 `FORGE_*_TOOL_NAMES` -2. 在 `forge_harness.minimal_tool_args` 补最小参数 -3. L0 registry 自动覆盖;跑 L1 smoke -4. 若有 structured 输出,注册 L2 wire check -5. 复杂行为补 domain 测试(`test_forge_mcp.py` 等)或场景 fixture - ---- - -## 与 Codex 参考实现的关系 - -- **可以**复用其 **fixture 布局**与 **场景数据**(如 apply_patch) -- **不必**在公开文档中强调「parity 等级」;`codex_parity.py` 仅供贡献者与 CI 追踪缺口 -- 行为分歧时以 Forge 设计文档 §设计取舍 为准,测试应断言 Forge 承诺的行为 diff --git a/docs/src/design/load_sync.md b/docs/src/design/load_sync.md deleted file mode 100644 index a8596f654..000000000 --- a/docs/src/design/load_sync.md +++ /dev/null @@ -1,130 +0,0 @@ -# Pulsing 负载信息同步设计 - -## 概述 - -Pulsing Actor System 使用基于 **StreamMessage 的流式订阅** 机制实现 Worker 负载信息的实时同步。 - -## 架构 - -```mermaid -sequenceDiagram - participant R as Router - participant W as Worker - - R->>W: SubscribeLoad - W-->>R: StreamMessage {load: 5} - W-->>R: StreamMessage {load: 3} - W-->>R: StreamMessage {load: 7} - - Note over R,W: 连接断开 = 自动清理 -``` - -## 核心组件 - -### Worker 端 (`TransformersWorker`) - -```python -class TransformersWorker(Actor): - async def receive(self, msg): - if msg.msg_type == "SubscribeLoad": - return self._handle_subscribe_load() - # ... - - def _handle_subscribe_load(self) -> StreamMessage: - """返回持续推送负载的流""" - stream_msg, writer = StreamMessage.create("LoadStream") - self._load_subscribers.append(writer) - - async def produce(): - while True: - await writer.write(self._get_load_snapshot()) - await asyncio.sleep(1.0) - - asyncio.create_task(produce()) - return stream_msg -``` - -### Router 端 (`StreamLoadScheduler`) - -```python -scheduler = StreamLoadScheduler(actor_system, "worker") -await scheduler.start() # 发现 Worker + 订阅负载流 - -worker_ref = await scheduler.select_worker() # 选择负载最低的 -``` - -## 使用方式 - -### 启动 Router (默认使用 StreamLoadScheduler) - -```python -from pulsing.serving import start_router - -runner = await start_router( - system, - http_port=8080, - model_name="my-model", - scheduler_type="stream_load", # 默认值;也支持 scheduler=... 实例。不支持 scheduler_class。 -) -``` - -### 可选的调度器类型 - -| 类型 | 说明 | 负载感知 | -|------|------|----------| -| `stream_load` | 流式负载订阅 (默认) | ✅ 实时 | -| `random` | 随机选择 | ❌ | -| `round_robin` | 轮询选择 | ❌ | -| `power_of_two` | Power-of-Two (Rust) | ✅ 本地计数 | -| `cache_aware` | 缓存感知 (Rust) | ✅ 本地计数 | - -## 信息流 - -```mermaid -flowchart TB - subgraph Step1["1. Router 启动"] - A1[StreamLoadScheduler.start] --> A2[Gossip 发现所有 Worker] - A2 --> A3[向每个 Worker 发送 SubscribeLoad] - end - - subgraph Step2["2. Worker 返回 StreamMessage"] - B1[启动异步任务] --> B2[持续推送负载] - end - - subgraph Step3["3. Router 接收流"] - C1[更新本地负载缓存] - end - - subgraph Step4["4. 路由请求"] - D1[scheduler.select_worker] --> D2[返回负载最低的 Worker] - end - - subgraph Step5["5. Worker 下线"] - E1[Stream 断开] --> E2[Router 自动清理] - end - - Step1 --> Step2 --> Step3 --> Step4 - Step3 -.-> Step5 - - style Step1 fill:#e3f2fd,stroke:#1976d2 - style Step2 fill:#fff3e0,stroke:#f57c00 - style Step3 fill:#e8f5e9,stroke:#388e3c - style Step4 fill:#f3e5f5,stroke:#7b1fa2 - style Step5 fill:#ffebee,stroke:#c62828 -``` - -## 与 Gossip 的配合 - -| 机制 | 职责 | -|------|------| -| Gossip | 服务发现、成员管理 | -| StreamMessage | 实时状态同步 | - -```python -# Gossip: 发现 Worker -workers = await gossip.get_named_actor_instances("worker") - -# StreamMessage: 订阅负载 -for worker in workers: - await consumer.subscribe(worker) -``` diff --git a/docs/src/design/load_sync.zh.md b/docs/src/design/load_sync.zh.md deleted file mode 100644 index a8596f654..000000000 --- a/docs/src/design/load_sync.zh.md +++ /dev/null @@ -1,130 +0,0 @@ -# Pulsing 负载信息同步设计 - -## 概述 - -Pulsing Actor System 使用基于 **StreamMessage 的流式订阅** 机制实现 Worker 负载信息的实时同步。 - -## 架构 - -```mermaid -sequenceDiagram - participant R as Router - participant W as Worker - - R->>W: SubscribeLoad - W-->>R: StreamMessage {load: 5} - W-->>R: StreamMessage {load: 3} - W-->>R: StreamMessage {load: 7} - - Note over R,W: 连接断开 = 自动清理 -``` - -## 核心组件 - -### Worker 端 (`TransformersWorker`) - -```python -class TransformersWorker(Actor): - async def receive(self, msg): - if msg.msg_type == "SubscribeLoad": - return self._handle_subscribe_load() - # ... - - def _handle_subscribe_load(self) -> StreamMessage: - """返回持续推送负载的流""" - stream_msg, writer = StreamMessage.create("LoadStream") - self._load_subscribers.append(writer) - - async def produce(): - while True: - await writer.write(self._get_load_snapshot()) - await asyncio.sleep(1.0) - - asyncio.create_task(produce()) - return stream_msg -``` - -### Router 端 (`StreamLoadScheduler`) - -```python -scheduler = StreamLoadScheduler(actor_system, "worker") -await scheduler.start() # 发现 Worker + 订阅负载流 - -worker_ref = await scheduler.select_worker() # 选择负载最低的 -``` - -## 使用方式 - -### 启动 Router (默认使用 StreamLoadScheduler) - -```python -from pulsing.serving import start_router - -runner = await start_router( - system, - http_port=8080, - model_name="my-model", - scheduler_type="stream_load", # 默认值;也支持 scheduler=... 实例。不支持 scheduler_class。 -) -``` - -### 可选的调度器类型 - -| 类型 | 说明 | 负载感知 | -|------|------|----------| -| `stream_load` | 流式负载订阅 (默认) | ✅ 实时 | -| `random` | 随机选择 | ❌ | -| `round_robin` | 轮询选择 | ❌ | -| `power_of_two` | Power-of-Two (Rust) | ✅ 本地计数 | -| `cache_aware` | 缓存感知 (Rust) | ✅ 本地计数 | - -## 信息流 - -```mermaid -flowchart TB - subgraph Step1["1. Router 启动"] - A1[StreamLoadScheduler.start] --> A2[Gossip 发现所有 Worker] - A2 --> A3[向每个 Worker 发送 SubscribeLoad] - end - - subgraph Step2["2. Worker 返回 StreamMessage"] - B1[启动异步任务] --> B2[持续推送负载] - end - - subgraph Step3["3. Router 接收流"] - C1[更新本地负载缓存] - end - - subgraph Step4["4. 路由请求"] - D1[scheduler.select_worker] --> D2[返回负载最低的 Worker] - end - - subgraph Step5["5. Worker 下线"] - E1[Stream 断开] --> E2[Router 自动清理] - end - - Step1 --> Step2 --> Step3 --> Step4 - Step3 -.-> Step5 - - style Step1 fill:#e3f2fd,stroke:#1976d2 - style Step2 fill:#fff3e0,stroke:#f57c00 - style Step3 fill:#e8f5e9,stroke:#388e3c - style Step4 fill:#f3e5f5,stroke:#7b1fa2 - style Step5 fill:#ffebee,stroke:#c62828 -``` - -## 与 Gossip 的配合 - -| 机制 | 职责 | -|------|------| -| Gossip | 服务发现、成员管理 | -| StreamMessage | 实时状态同步 | - -```python -# Gossip: 发现 Worker -workers = await gossip.get_named_actor_instances("worker") - -# StreamMessage: 订阅负载 -for worker in workers: - await consumer.subscribe(worker) -``` diff --git a/docs/src/design/pulsing-cli.md b/docs/src/design/pulsing-cli.md index 8522d688d..b3608f6fb 100644 --- a/docs/src/design/pulsing-cli.md +++ b/docs/src/design/pulsing-cli.md @@ -1,379 +1,28 @@ -# Pulsing CLI 设计 +# Pulsing CLI -## 概述 +Pulsing 的命令行聚焦 actor 运行时和 workspace 文件管理。 -Pulsing 提供一组命令行入口,覆盖 Actor 运行时运维、推理压测、示例浏览,以及基于 workspace 的 **Agent** 交互。各入口共享同一 Python 包 `pulsing`,通过 `pyproject.toml` 注册多个 script。 - -> **迁移说明**:Workspace Agent CLI 已统一为 `pulsing agent`(实现于 `python/pulsing/cli/agent/`)。`pcraft`、`pulsing craft`、`pulsing.craft` 仍可用但已弃用,会打印警告并转发至 `pulsing agent`。详见 [agent-craft-migration.md](../../design/agent-craft-migration.md)。 - -本文档描述**全部** CLI 入口、命令树、行为约定与代码布局。Workspace 持久化见 [Workspace 持久化](./npc-workspace-world-persistence.md)。 - -**实现位置**: - -| 区域 | 路径 | +| 命令 | 职责 | |------|------| -| 主 CLI | `python/pulsing/cli/` | -| Agent CLI | `python/pulsing/cli/agent/` | -| Agent SDK | `python/pulsing/agent/`(actors、loop、workspace、cluster) | -| Craft shim(弃用) | `python/pulsing/craft/` | - ---- - -## 设计目标 - -1. **职责分离** — `pulsing` 承载运行时与集群运维;Workspace Agent 子命令集中在 `pulsing agent`。 -2. **稳定主路径** — 生产与文档以 `pulsing agent` 为准;`pcraft` / `pulsing craft` 为弃用 shim。 -3. **参数约定** — `pulsing actor` 使用 `--` 分隔进程级参数与 Actor 构造参数;Agent CLI 使用 `argparse` 子命令树。 -4. **Observer 与 Member 分离** — `pulsing inspect` 仅 HTTP 观察,不加入 gossip;`pulsing agent wake` 与 `pulsing actor` 启动完整节点。 -5. **向后兼容** — 旧 `npc` / `puzzle` 子命令通过 shim 映射至 `spawn` / `say` / `task`。 - ---- - -## 入口注册 - -`pyproject.toml` → `[project.scripts]`: - -| 命令 | 入口 | 说明 | -|------|------|------| -| `pulsing` | `pulsing.cli.__main__:main` | 主 CLI | -| `pulsing-agent` | `pulsing.cli.agent.main:main` | Agent workspace CLI(推荐) | -| `pcraft` | `pulsing.craft.cli:main` | **弃用**;转发至 `pulsing agent` | - -`pulsing` 在 `main()` 中对 `argv[1] == "craft"`、`argv[1] == "forge"` 做 early dispatch,其余子命令由 `hyperparameter` 解析。 - ---- - -## 4. 总命令树 - -```text -pulsing -├─ actor TYPE [--addr …] [--seeds …] [--name …] [-- …] -├─ inspect {cluster|actors|metrics|watch} … -├─ bench MODEL … -├─ examples [NAME] -├─ craft … → 见 §9;与 pcraft 相同 -└─ forge repl … → Forge session REPL(Rust 优先) - -pcraft … → §9 - -python -m pulsing.craft … → §10(调试) -``` - ---- - -## 5. `pulsing actor` - -启动一个 Actor 服务进程并加入(或组建)集群。 - -### 命令形式 - -```text -pulsing actor [--addr ADDR] [--seeds SEEDS] [--name NAME] [-- …] -``` - -- **`actor_type`**( positional):完整类路径,必须含 `.`。 -- **`--addr`**:本节点绑定地址,如 `0.0.0.0:8000`。 -- **`--seeds`**:逗号分隔的 seed 节点,用于加入已有集群。 -- **`--name`**:Actor 注册名(默认 `worker`)。 -- **`--` 之后**:Actor 构造函数 kwargs,经 `_actor_argv_rewrite` 注入 `extra_kwargs`。 - -### 行为 - -- 调用 `pulsing.cli.actors.start_generic_actor`。 -- `pulsing actor list` 已移除;提示改用 `pulsing inspect actors`。 - -### 示例 +| `pulsing actor TYPE` | 启动用户提供的 actor | +| `pulsing inspect cluster/actors/metrics/watch` | 通过 HTTP 观察集群,不加入集群 | +| `pulsing examples [NAME]` | 浏览内置示例 | +| `pulsing init` | 创建 minimal workspace | +| `pulsing history` | 列出 checkpoint | +| `pulsing checkpoint` | 保存文件快照 | +| `pulsing rollback` | 恢复文件快照 | +| `pulsing run [SCRIPT]` | Rust CLI:执行一次 Python workflow | + +Actor 启动参数使用 `--` 分隔:之前为节点和 actor 注册参数, +之后为用户 actor 的构造参数。例如: ```bash -pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 --name my-llm -- \ - --http_port 8080 --model_name my-llm - -pulsing actor pulsing.serving.TransformersWorker --seeds 127.0.0.1:8000 -- \ - --model_name gpt2 --device cpu -``` - ---- - -## 6. `pulsing inspect` - -通过 HTTP **观察者模式**查看集群状态,**不**加入 gossip。 - -### 子命令 - -```text -pulsing inspect cluster --seeds SEEDS [--timeout …] [--best_effort] -pulsing inspect actors (--seeds SEEDS | --endpoint ADDR) [--top N] [--filter …] - [--json] [--detailed] [--all_actors] -pulsing inspect metrics --seeds SEEDS [--raw …] -pulsing inspect watch --seeds SEEDS [--interval …] [--kind …] [--max_rounds …] +pulsing actor my_app.Counter --addr 0.0.0.0:8000 --name counter -- --initial 10 +pulsing inspect actors --endpoint 127.0.0.1:8000 ``` -| 子命令 | 作用 | -|--------|------| -| `cluster` | 成员列表 | -| `actors` | Actor 分布;`--endpoint` 与 `--seeds` 互斥 | -| `metrics` | 节点 metrics | -| `watch` | 周期性刷新;`kind`: cluster / actors / metrics / all | - -公共选项:`--timeout`(默认 10s)、`--best_effort`。 - ---- - -## 7. `pulsing bench` +Python 入口为 `pulsing.cli.__main__:main`。Rust CLI 通过 RustPython +运行 Python 命令,workspace 初始化和 journal 则使用 `pulsing-workspace`。 -对 LLM 推理端点做压测,内部使用 Actor 架构采集指标。 - -### 命令形式 - -```text -pulsing bench MODEL [--url URL] [--max_vus N] [--duration …] [--warmup …] - [--benchmark_kind …] [--num_workers …] … -``` - -| 参数 | 默认 | 说明 | -|------|------|------| -| `MODEL` | — | 模型名( positional) | -| `--url` | `http://localhost:8000` | 后端 URL | -| `--max_vus` | 128 | 最大并发 | -| `--duration` | `120s` | 压测时长 | -| `--warmup` | `30s` | 预热 | -| `--benchmark_kind` | `throughput` | throughput / sweep / csweep / rate | -| `--num_workers` | 4 | worker Actor 数 | -| `--tokenizer` | 同 MODEL | HF tokenizer | -| `--rates` | — | rate 模式下的速率列表 | - ---- - -## 8. `pulsing examples` - -列出或查看内置示例。 - -```text -pulsing examples -pulsing examples NAME -``` - -无 `NAME` 时打印列表;有 `NAME` 时打印 docstring 与 `python -m pulsing.examples.{name}` 运行方式。 -`pulsing examples foo` 在 `main()` 中 rewrite 为 `--name foo`。 - ---- - -## 9. Craft(`pulsing craft` / `pcraft`) - -Craft 在项目目录内管理 workspace(`.pulsing/`)、启动本地节点、spawn 命名 Agent(NPC),并通过 shell 与 Puzzle 配置交互。 - -### 9.1 术语 - -| 术语 | 含义 | -|------|------| -| **Workspace** | 项目根 + `.pulsing/`;`cluster_id` 由根路径导出 | -| **Operator** | CLI 操作者;显示名 `PLAYER` / `HERO` / `USER` | -| **NPC** | gossip 命名 Agent(如 `guide`);实现为 `HubActor` | -| **Puzzle** | `cluster.json` 内任务项 | -| **Node record** | `.pulsing/node.json`:当前 `wake` 的 addr、pid | - -### 9.2 等价入口 - -```text -pcraft ARGS… ≡ pulsing craft ARGS… -``` - -### 9.3 命令树 - -```text -pcraft [ -h | --help ] - -├─ (default) → look - -├─ init 写入 .pulsing/cluster.json -│ -├─ wake 启动节点并 spawn NPC(阻塞至信号) -│ ├─ --agents AGENTS -│ ├─ --addr ADDR 默认 127.0.0.1:0 -│ ├─ --auto-approve -│ ├─ --provider {anthropic,openai} -│ └─ --model MODEL -│ -├─ look 打印 workspace 摘要 -│ -├─ sleep [未实现] 快照后停止 node -│ -├─ npc -│ ├─ who -│ ├─ summon NAME [--role …] [--provider …] [--model …] -│ └─ say NAME MESSAGE… [--puzzle ID 未实现] -│ -└─ puzzle - ├─ list - ├─ show ID - └─ mark ID --status … [未实现] -``` - -### 9.4 命令分层 - -| 层级 | 命令 | 作用对象 | -|------|------|----------| -| Workspace | `init` `wake` `look` `sleep` | 整个 workspace / 本地 node | -| NPC | `npc who` `say` `summon` | 已注册 Agent | -| Puzzle | `puzzle list` `show` `mark` | 配置与进度 | - -无参数 → `look`。未 init → 提示 `pcraft init`;需在线 node → 提示 `pcraft wake`。 - -### 9.5 Legacy 映射(`npc` 入口) - -| 输入 | 解析结果 | -|------|----------| -| _(empty)_ | `look` | -| `seed` | `init` | -| `puzzles` | `puzzle list` | -| `who` / `say` / `summon` | `npc …` | - -### 9.6 Workspace 布局 - -```text -.pulsing/ - cluster.json 静态配置 - node.json 当前 wake(临时) - puzzle_state.json [未实现] - snapshot/ [未实现] 见持久化文档 -``` - -### 9.7 命令与运行时 - -| 命令 | 连接集群 | 启动 node | 副作用 | -|------|----------|-----------|--------| -| `init` | 否 | 否 | 写 `cluster.json` | -| `look` | 可选 | 否 | 只读 | -| `wake` | 是 | 是 | spawn NPC;写 `node.json` | -| `npc *` | 是 | 否 | RPC | -| `puzzle list/show` | 否 | 否 | 读配置 | -| `sleep` | 是 | 否 | [未实现] 快照 | - -NPC gossip 全名:`craft/ws//`;CLI 使用短名。 - -### 9.8 子命令行为(摘要) - -- **`init`**:创建 workspace;已存在则 exit 0 并提示。 -- **`wake`**:`workspace_session` → spawn → 阻塞 → `clear_node_record`。 -- **`look`**:`render_look`;含 operator、路径、node、puzzle、NPC 列表。 -- **`npc say`**:`resolve_cluster_agent` → `receive_agent_message`。 -- **`puzzle show`**:未知 id 时 exit 2。 - -`look` 输出格式为稳定契约,见 `pulsing.craft.workspace.world_view.render_look`。 - -### 9.9 Craft 示例 - -```bash -pcraft init -pcraft wake --agents guide # terminal 1 -pcraft look -pcraft npc say guide "run tests" -pcraft puzzle list -``` - ---- - -## 10. 调试入口(`python -m pulsing.craft`) - -不在主 CLI 稳定面内;供开发与回归。 - -```text -python -m pulsing.craft {session|minimal|hub|cluster|agent|ctl|legacy} … -``` - -| 子命令 | 说明 | -|--------|------| -| `session` / `minimal` | 最小 REPL,无 LLM | -| `hub` | 完整 craft hub + REPL/TUI | -| `cluster` | 本地 agent 集群 + 控制 REPL | -| `agent` | spawn 单个命名 cluster agent | -| `ctl` | 已有集群的控制 REPL | -| `legacy` | 进程内 sync Engine | - -首参数以 `-` 开头时默认 `hub`。 - ---- - -## 11. 模块结构 - -```text -python/pulsing/ - cli/ - __main__.py pulsing 入口;craft dispatch;top-level help - actor_argv.py pulsing actor ``--`` rewrite - help_text.py grouped ``pulsing`` help - actors.py pulsing actor 启动 - inspect.py pulsing inspect - bench.py pulsing bench - craft/ - cli.py entry: pcraft / pulsing craft / deprecated npc - parser.py argparse - normalize.py legacy argv mapping - dispatch.py route parsed args to handlers - helpers.py shared session/spawn helpers - commands/ - world.py init, wake, look, sleep - npc.py who, say, summon - puzzle.py list, show, mark - runtime/ hub, engine, tools - workspace/ config, session, world_view - cluster/ discovery, messaging - payload/ isolated workers - __main__.py debug: hub, cluster, session - examples/ pulsing examples 数据源 -``` - ---- - -## 12. 环境变量 - -| 变量 | 适用 | 说明 | -|------|------|------| -| `PLAYER` / `HERO` / `USER` | Craft | Operator 显示名 | -| `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` | Craft | LLM | -| `HF_TOKEN` | bench | HuggingFace 私有模型 | - ---- - -## 13. 测试 - -| 目录 / 文件 | 覆盖 | -|-------------|------| -| `tests/python/craft/test_cli.py` | parser、normalize、init/look | -| `tests/python/craft/test_world.py` | look、puzzle 视图 | -| `tests/python/craft/test_workspace.py` | workspace config、scoped discovery | -| `tests/python/craft/test_agent.py` | CraftAgent spawn、RPC、mailbox handoff | -| `tests/python/craft/test_npc.py` | `spawn_npc`、say/whisper、class 注册 | -| `tests/python/craft/test_cluster.py` | 集群命名、gossip discovery | -| `tests/python/craft/test_tools.py` | 隔离 worker、split_tools | -| `tests/python/craft/test_coordinator.py` | delegate 通知 XML | -| `test_pulsing_cli_helpers.py` | actor argv rewrite | - ---- - -## 14. 实现阶段 - -| 阶段 | 范围 | 状态 | -|------|------|------| -| P0 | `pulsing` 子命令 + `pcraft` / `pulsing craft` 现有 Craft 树;`npc` deprecated | 已完成 | -| P0.5 | Craft 拆包;`pulsing --help` 分组展示 | 已完成 | -| P1 | Craft `sleep`、快照;`wake --detach` | 未开始 | -| P2 | Craft puzzle 闭环(`say --puzzle`、`puzzle mark`) | 未开始 | -| P3 | 移除 `npc` script;收敛 `python -m pulsing.craft` 调试面 | 未开始 | - ---- - -## 15. 非目标 - -- Craft 不以 TUI/REPL 为主路径(`pulsing.craft hub` 除外)。 -- `pulsing actor` 不自动管理 workspace / `.pulsing/`。 -- `inspect` 不作为 cluster 成员运行。 -- Craft 不支持跨 workspace 全局命令;workspace 由 cwd 向上解析。 - ---- - -## 16. 变更记录 - -| 日期 | 说明 | -|------|------| -| 2026-05 | 初稿:全 CLI 结构;Craft 为 §9;`seed`→`init` | +Workflow 执行成功后直接退出,不进入交互式 agent 会话。 +推理压测、LLM 引导初始化、coding-agent 命令、工具 REPL 和桌面界面已移除。 diff --git a/docs/src/examples/index.md b/docs/src/examples/index.md index 3919bfe14..abb5acba4 100644 --- a/docs/src/examples/index.md +++ b/docs/src/examples/index.md @@ -302,7 +302,6 @@ cd examples/agent/langgraph && ./run_distributed.sh - [Ping-Pong](ping_pong.md) - Basic actor communication - [Distributed Counter](distributed_counter.md) - Shared state across nodes - [Subprocess](subprocess.md) - Subprocess-compatible command execution -- [LLM Inference](llm_inference.md) - Building inference services - [AutoGen Integration](../agent/autogen.md) - Distributed AutoGen agents - [LangGraph Integration](../agent/langgraph.md) - Distributed LangGraph workflows diff --git a/docs/src/examples/index.zh.md b/docs/src/examples/index.zh.md index d1c97d944..9e4d6c845 100644 --- a/docs/src/examples/index.zh.md +++ b/docs/src/examples/index.zh.md @@ -265,7 +265,6 @@ cd examples/agent/langgraph && ./run_distributed.sh - [Ping-Pong](ping_pong.zh.md) - 基本 Actor 通信 - [分布式计数器](distributed_counter.zh.md) - 跨节点共享状态 - [子进程](subprocess.zh.md) - 兼容 `subprocess` 的命令执行 -- [LLM 推理](llm_inference.zh.md) - 构建推理服务 - [AutoGen 集成](../agent/autogen.zh.md) - 分布式 AutoGen Agent - [LangGraph 集成](../agent/langgraph.zh.md) - 分布式 LangGraph 工作流 diff --git a/docs/src/examples/llm_inference.md b/docs/src/examples/llm_inference.md deleted file mode 100644 index 4a7ce687f..000000000 --- a/docs/src/examples/llm_inference.md +++ /dev/null @@ -1,100 +0,0 @@ -# LLM Inference (runnable) - -This guide shows how to run a **router + worker** LLM service with Pulsing, and expose an **OpenAI-compatible HTTP API**. - -## Architecture - -- **Router**: accepts HTTP requests, selects a worker, forwards `GenerateRequest` / `GenerateStreamRequest` -- **Workers**: host model replicas - -## 0) Prerequisites - -- `pip install pulsing` -- Choose one backend: - - **Transformers**: install `torch` + `transformers` - - **vLLM**: install `vllm` - -## 1) Start the Router (Terminal A) - -The router needs an **actor system address** so workers can join the same cluster: - -```bash -pulsing actor pulsing.serving.Router \ - --addr 0.0.0.0:8000 \ - --name my-llm \ - -- \ - --http_port 8080 \ - --model_name gpt2 \ - --worker_name worker -``` - -## 2) Start workers - -You can run **one or more** workers. Each worker should join the router node via `--seeds`. - -### Option A: Transformers worker (Terminal B) - -```bash -pulsing actor pulsing.serving.TransformersWorker \ - --addr 0.0.0.0:8001 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model_name gpt2 -``` - -### Option B: vLLM worker (Terminal C) - -```bash -pulsing actor pulsing.serving.vllm.VllmWorker \ - --addr 0.0.0.0:8002 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model Qwen/Qwen2.5-0.5B -``` - -## 3) Verify cluster + workers - -### List actors (observer mode) - -```bash -pulsing inspect actors --endpoint 127.0.0.1:8000 -``` - -### Inspect cluster - -```bash -pulsing inspect cluster --seeds 127.0.0.1:8000 -``` - -## 4) Call the OpenAI-compatible API - -### Non-streaming - -```bash -curl -X POST http://localhost:8080/v1/chat/completions \ - -H "Content-Type: application/json" \ - -d '{"model": "gpt2", "messages": [{"role": "user", "content": "Hello"}], "stream": false}' -``` - -### Streaming (SSE) - -```bash -curl -X POST http://localhost:8080/v1/chat/completions \ - -H "Content-Type: application/json" \ - -d '{"model": "gpt2", "messages": [{"role": "user", "content": "Tell me a joke"}], "stream": true}' -``` - -## Troubleshooting - -- If you see `No available workers`, ensure: - - router is started with `--addr` and workers join via `--seeds ` - - the worker actor **name** matches: workers started with `--name worker` (before `--`), or start the router with `--worker_name ` (after `--`) to match your worker name - - check: `pulsing inspect actors --seeds 127.0.0.1:8000` — you should see an actor with the name the router is looking for (default `worker`) - -See also: - -- [Operations (CLI)](../guide/operations.md) -- [HTTP2 Transport (design)](../design/http2-transport.md) -- [Load Sync (design)](../design/load_sync.md) diff --git a/docs/src/examples/llm_inference.zh.md b/docs/src/examples/llm_inference.zh.md deleted file mode 100644 index 59e6f08ad..000000000 --- a/docs/src/examples/llm_inference.zh.md +++ /dev/null @@ -1,100 +0,0 @@ -# LLM 推理(可运行) - -本指南展示如何用 Pulsing 跑通 **router + worker** 架构,并对外暴露 **OpenAI 兼容 HTTP API**。 - -## 推荐架构 - -- **Router**:接入 HTTP 请求,选择 worker,转发 `GenerateRequest` / `GenerateStreamRequest` -- **Worker**:承载模型副本 - -## 0)前置条件 - -- `pip install pulsing` -- 选择一种或两种后端: - - **Transformers**:安装 `torch` + `transformers` - - **vLLM**:安装 `vllm` - -## 1)启动 Router(终端 A) - -Router 需要指定 **actor system 地址**,以便其它进程启动的 workers 加入同一集群: - -```bash -pulsing actor pulsing.serving.Router \ - --addr 0.0.0.0:8000 \ - --name my-llm \ - -- \ - --http_port 8080 \ - --model_name gpt2 \ - --worker_name worker -``` - -## 2)启动 Worker - -你可以启动 **一个或多个** worker。每个 worker 通过 `--seeds` 加入 Router 节点。 - -### 方案 A:Transformers Worker(终端 B) - -```bash -pulsing actor pulsing.serving.TransformersWorker \ - --addr 0.0.0.0:8001 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model_name gpt2 -``` - -### 方案 B:vLLM Worker(终端 C) - -```bash -pulsing actor pulsing.serving.vllm.VllmWorker \ - --addr 0.0.0.0:8002 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model Qwen/Qwen2.5-0.5B -``` - -## 3)验证集群与 worker - -### 列出 actors(观察者模式) - -```bash -pulsing inspect actors --endpoint 127.0.0.1:8000 -``` - -### 巡检集群 - -```bash -pulsing inspect cluster --seeds 127.0.0.1:8000 -``` - -## 4)调用 OpenAI 兼容 API - -### 非流式 - -```bash -curl -X POST http://localhost:8080/v1/chat/completions \ - -H "Content-Type: application/json" \ - -d '{"model": "gpt2", "messages": [{"role": "user", "content": "Hello"}], "stream": false}' -``` - -### 流式(SSE) - -```bash -curl -X POST http://localhost:8080/v1/chat/completions \ - -H "Content-Type: application/json" \ - -d '{"model": "gpt2", "messages": [{"role": "user", "content": "讲个笑话"}], "stream": true}' -``` - -## 排障 - -- 如果出现 `No available workers`,请检查: - - Router 已用 `--addr` 启动,Worker 已用 `--seeds ` 加入 - - **名字一致**:Worker 用 `--name worker`(`--` 前)启动,或 Router 用 `--worker_name <名字>`(`--` 后)与 Worker 一致 - - 执行 `pulsing inspect actors --seeds 127.0.0.1:8000`,确认能看到 Router 在找的名字(默认 `worker`) - -更多: - -- [运维(CLI)](../guide/operations.zh.md) -- [HTTP2 传输(设计)](../design/http2-transport.zh.md) -- [负载同步(设计)](../design/load_sync.zh.md) diff --git a/docs/src/forge/abstractions.md b/docs/src/forge/abstractions.md deleted file mode 100644 index 283e580fa..000000000 --- a/docs/src/forge/abstractions.md +++ /dev/null @@ -1,96 +0,0 @@ -# Abstractions - -!!! info "Current abstraction layer" - - This page describes the current tool-execution abstraction. The versioned Session, Event, and Evolution protocols that supersede `ToolSession` as the product-state boundary are specified in [Forge Core Architecture](../design/forge/core-architecture.md). - -Forge provides a **standard, sandboxed workspace** for agents — independent of any single LLM product or CLI. - ---- - -## Core concepts - -| Concept | Type | Responsibility | -|---------|------|----------------| -| **ForgeEnvironment** | dataclass | Workspace root, sandbox policy, session hooks | -| **Runtime** | `LocalToolRuntime` / `HybridForgeRuntime` / `ToolWorkerActor` | Dispatch `call_tool`, return `ToolResult` | -| **ToolCallContext** | per-call | `cwd`, sandbox, `session`, exec manager | -| **ToolSession** | Host protocol | Plan, user input, token budget | -| **ToolExecutor** | Rust trait | Single-tool implementation | - -```text -Host creates ForgeEnvironment - → env.runtime() - → runtime.call_tool("shell_command", {...}) - → handler runs in ToolCallContext - → optional ToolSession callback for UI tools -``` - ---- - -## Environment and sandbox - -| Field | Meaning | -|-------|---------| -| `cwd` | Root for relative paths | -| `sandbox_policy` | `off` · `restricted` · `bwrap` | -| `dangerously_disable_sandbox` | Explicit dev-only bypass | - -Sandbox applies to **Forge-managed tools** only. Host may add VM/container boundaries; `ToolWorkerActor` adds process isolation. - ---- - -## ToolSession boundary - -Product-facing tools delegate to Host: - -```python -class ToolSession(Protocol): - def update_plan(self, args: UpdatePlanArgs) -> None: ... - def request_new_context(self) -> None: ... - def tokens_remaining(self) -> int | None: ... - def request_user_input(self, arguments: dict) -> dict: ... -``` - -| Implementation | Use | -|----------------|-----| -| `LocalToolSession` | Dev/tests with optional callbacks | -| `NullToolSession` | Shell/files only | -| Custom | Craft TUI, web dashboard, enterprise approval | - -**Principle**: Forge sends structured requests; Host decides presentation and blocking. - ---- - -## Deployment modes - -| Mode | API | When | -|------|-----|------| -| In-process | `ForgeEnvironment.runtime()` | Unit tests, single-process agents | -| Isolated | `ToolWorkerActor` + `pul.spawn(..., new_process=True)` | Child-process sandbox | -| Shared | `resolve("craft/ws/{id}/_tools")` | Multiple agents, one worker | - -Same tool names and args in all modes. - ---- - -## Rust / Python split - -| Python | Rust `pulsing-forge` | -|--------|----------------------| -| `ForgeEnvironment` | `ToolRuntimeConfig` | -| `HybridForgeRuntime` | `ToolRuntime` + handlers | -| `ToolSession` | `trait ToolSession` | -| Actor bindings, Code Mode, Extension | Hot-path exec / patch / MCP | - -Default path: Rust via PyO3; Python fallback for tools without Rust handlers. - ---- - -## Non-goals - -- Not a full agent OS (no LLM, no MCP catalog UI) -- Not container orchestration -- Not tied to one patch or shell JSON schema beyond the default 32-tool surface - -Implementation: [Engineering notes](../design/forge/engineering.md) · Architecture with Craft: [craft-architecture](../design/forge/craft-architecture.md) diff --git a/docs/src/forge/abstractions.zh.md b/docs/src/forge/abstractions.zh.md deleted file mode 100644 index b3760f780..000000000 --- a/docs/src/forge/abstractions.zh.md +++ /dev/null @@ -1,140 +0,0 @@ -# Pulsing Forge 抽象模型 - -!!! info "当前抽象层" - - 本页描述当前工具执行抽象。取代 `ToolSession` 作为产品状态边界的版本化 Session、Event、Evolution 协议见 [Forge 核心架构](../design/forge/core-architecture.zh.md)。 - -Forge 的设计目标:**给 Agent 一个标准、可沙箱化的「工作环境」**,而不是绑定某一种 LLM 产品或 CLI。 - ---- - -## 1. 核心概念 - -| 概念 | 类型 | 职责 | -|------|------|------| -| **ForgeEnvironment** | `ForgeEnvironment` | 工作区根目录、沙箱策略、Host 会话钩子 | -| **Runtime** | `LocalToolRuntime` / `ToolWorkerActor` | 按名称分发工具调用,返回 `ToolResult` | -| **ToolCallContext** | 每次调用注入 | `cwd` + sandbox + `session` 快照 | -| **ToolSession** | Host 实现 | Plan、用户输入、context 预算等产品行为 | -| **ToolExecutor** | Rust handler trait | 单一工具的实现(shell、patch、plan…) | - -关系: - -```text -Host 创建 ForgeEnvironment - → env.runtime() 得到 Runtime - → runtime.call_tool("shell_command", {...}) - → Runtime 构造 ToolCallContext 并调用对应 handler - → 若工具需要 UI(如 request_user_input),handler 回调 ToolSession -``` - ---- - -## 2. 环境与沙箱 - -**Environment** 回答:Agent 在哪个目录、以什么权限操作机器? - -| 字段 | 含义 | -|------|------| -| `cwd` | 工具解析相对路径的根目录 | -| `sandbox_policy` | `off` · `restricted` · `bwrap`(平台相关) | -| `dangerously_disable_sandbox` | 显式关闭沙箱(仅开发/受信场景) | - -沙箱只约束 **Forge 管理的工具路径**(shell、patch 等),不替代 OS 级容器。Host 仍可在更外层做 VM / 容器隔离;Forge 的 `ToolWorkerActor` 则提供进程级隔离部署。 - ---- - -## 3. Session:Host 与 Agent 的边界 - -部分工具是 **「环境能力」**(读文件、跑命令),部分是 **「产品能力」**(问用户、更新计划、换 context)。 - -Forge 把产品能力收敛到 **`ToolSession`**,避免在工具库里写 UI: - -```python -class ToolSession(Protocol): - def update_plan(self, args: UpdatePlanArgs) -> None: ... - def request_new_context(self) -> None: ... - def tokens_remaining(self) -> int | None: ... - def request_user_input(self, arguments: dict) -> dict: ... -``` - -| 实现 | 用途 | -|------|------| -| `LocalToolSession` | 本地开发、测试;内存 plan + 可选 callback | -| `NullToolSession` | 只要 shell/文件、不需要 plan/UI | -| 自定义 | Craft TUI、Web dashboard、企业审批流 | - -**原则**:Forge 发出「需要用户确认」的**结构化请求**;Host 决定如何展示与阻塞。 - ---- - -## 4. 工具域(Tool Domains) - -工具按**能力域**注册,而非按「抄哪家产品」划分: - -### Execution - -- `shell_command` — 标准 wire 参数(`command`/`timeout_ms`/`login`/`sandbox_permissions`),shell 内 `apply_patch` 自动拦截 -- `exec_command` / `write_stdin` — UnifiedExec 会话(`session_id`、`yield_time_ms`、`max_output_tokens`) -- `Bash` — `shell_command` 别名 - -### Filesystem - -- `apply_patch` — 结构化 patch;拒绝隐式裸 patch;支持 `command: ["apply_patch", "..."]` -- `view_image` — 返回 `content_items`(`input_image` + data URL);`detail`: `high` | `original` -- `Read` / `Glob` / `Grep` / `Edit` / `Write` — 通用文件 helper - -### Session - -- `update_plan` · `new_context` · `get_context_remaining` · `request_user_input` - -新增工具 = 新 `ToolExecutor` + 注册到 `ToolRuntime`,可选是否依赖 `ToolSession`。 - ---- - -## 5. 部署模式 - -| 模式 | API | 适用 | -|------|-----|------| -| **In-process** | `ForgeEnvironment` → `LocalToolRuntime` | 单进程 Agent、单元测试 | -| **Isolated actor** | `ToolWorkerActor` + Pulsing spawn | 子进程 / 集群 worker | -| **Shared worker** | gossip name `craft/ws/{id}/_tools` | 多 Agent 共享同一 sandbox 环境 | - -两种模式 **工具名与参数一致**,Host 只换 Runtime 后端。 - ---- - -## 6. 与 Agent 框架集成 - -```text -LangChain / AutoGen / 自研 loop - │ - ├─ 把 Forge 工具包装成 framework Tool - │ - └─ 或直接 call_tool("shell_command", {...}) -``` - -Forge **不**管理对话历史、不调用 LLM、不选模型——这些留在 Host。Forge 只保证:**给定 tool name + JSON args,在 Environment 里安全执行并返回文本结果**。 - ---- - -## 7. Rust / Python 对齐 - -| Python | Rust crate `pulsing-forge` | -|--------|----------------------------| -| `ForgeEnvironment` | `ToolRuntimeConfig` + `ToolCallContext` | -| `LocalToolRuntime` | `ToolRuntime` | -| `ToolSession` | `trait ToolSession` | -| `ToolResult` | `ToolResult` | - -Python 层用于 Actor worker 绑定与 fallback;**默认执行路径**为 Rust `ForgeRuntime`(PyO3)。一体化架构见 [craft-architecture.md](../design/forge/craft-architecture.md)。 - ---- - -## 8. 非目标(明确边界) - -- 不是完整 Agent OS(无 LLM、无 memory 产品、无 MCP 目录 UI) -- 不是容器编排(Kubernetes 层由部署解决) -- 不强制某一种 patch 或 shell JSON schema 以外的工具命名——但默认工具面覆盖主流 coding agent 需求 - -实现与路线图:[design/engineering.md](../design/forge/engineering.md) diff --git a/docs/src/forge/concepts.md b/docs/src/forge/concepts.md deleted file mode 100644 index efa139977..000000000 --- a/docs/src/forge/concepts.md +++ /dev/null @@ -1,76 +0,0 @@ -# Core Concepts - -!!! info "Scope" - - The Host/Forge split below describes the current tool-runtime API. The target control-plane boundary is defined by [Forge Core Architecture](../design/forge/core-architecture.md): Forge will own Session, Turn, Agent-loop, Event, and Evolution semantics, while clients own presentation and provider/tool adapters. - -## Host vs Forge - -| Layer | Owns | Does not own | -|-------|------|--------------| -| **Host** | LLM loop, chat history, UI, approvals display | Shell execution, patch apply | -| **Forge** | Tool dispatch, sandbox, MCP runtime, handlers | Model choice, login, product memory | - -Integration contract: - -```text -Host → runtime.call_tool(name, args) → ToolResult -Host ← ToolSession callbacks ← plan / user_input / permissions -Host ← tell_forge_event ← exec streams, tool_begin/end -``` - ---- - -## Three core types - -| Type | Role | -|------|------| -| **`ForgeEnvironment`** | Workspace root (`cwd`), sandbox policy, session hooks | -| **`ToolSession`** | Host-implemented product behavior (plan, prompts, token budget) | -| **`ToolResult`** | `{ content, is_error, structured? }` — uniform tool output | - ---- - -## Runtime stack - -```text -ForgeEnvironment - └─ HybridForgeRuntime (default with Rust) - ├─ Rust ForgeRuntime — most handlers + MCP - └─ Python LocalToolRuntime — exec/wait, Extension, Code Mode fallback -``` - -For isolation, swap the bottom layer for **`ToolWorkerActor`** via [`ForgeBackend`](deployment.md). - ---- - -## Tool domains - -Tools are grouped by **capability**, not by vendor: - -- **Execution** — shell, PTY, unified exec -- **Filesystem** — read, patch, image -- **Session** — plan, context, user input -- **Discovery** — plugins, tool_search -- **MCP** — resources, dynamic MCP tools -- **Code Mode** — `exec` / `wait` cells -- **Extension** — memories, skills, web.run, web_search - -See [Tools (32)](tools.md). - ---- - -## Quality verification - -Forge validates tool registration, default callability, and core integration paths in CI (`test_hybrid_forge_callable.py`, `test_pulsing_forge.py`). Capability claims should match test results. - -```bash -pytest tests/python/test_hybrid_forge_callable.py tests/python/test_pulsing_forge.py -q -``` - ---- - -## Related - -- [Abstractions](abstractions.md) — API-level detail -- [Pulsing Integration](pulsing-integration.md) — actors and events diff --git a/docs/src/forge/concepts.zh.md b/docs/src/forge/concepts.zh.md deleted file mode 100644 index 354b3ef63..000000000 --- a/docs/src/forge/concepts.zh.md +++ /dev/null @@ -1,74 +0,0 @@ -# 核心概念 - -!!! info "范围" - - 下述 Host/Forge 分工描述当前工具运行时 API。目标控制面边界以 [Forge 核心架构](../design/forge/core-architecture.zh.md) 为准:Forge 将拥有 Session、Turn、Agent loop、Event 与 Evolution 语义,客户端只负责展示和 Provider/Tool 适配。 - -## Host 与 Forge - -| 层 | 负责 | 不负责 | -|----|------|--------| -| **Host** | LLM 循环、对话、UI、审批展示 | 执行 shell、应用 patch | -| **Forge** | 工具分发、沙箱、MCP、handler | 选模型、登录、产品级记忆 | - -```text -Host → call_tool(name, args) → ToolResult -Host ← ToolSession 回调 ← plan / 用户输入 / 权限 -Host ← tell_forge_event ← exec 流、tool_begin/end -``` - ---- - -## 三个核心类型 - -| 类型 | 作用 | -|------|------| -| **`ForgeEnvironment`** | 工作区根目录、沙箱策略、会话钩子 | -| **`ToolSession`** | Host 实现的产品能力(plan、弹窗、token) | -| **`ToolResult`** | 统一返回 `{ content, is_error, structured? }` | - ---- - -## 运行时栈 - -```text -ForgeEnvironment - └─ HybridForgeRuntime(有 Rust 时默认) - ├─ Rust ForgeRuntime — 多数 handler + MCP - └─ Python LocalToolRuntime — exec/wait、Extension、Code Mode fallback -``` - -隔离执行时,通过 [`ForgeBackend`](deployment.zh.md) 换为 **`ToolWorkerActor`**。 - ---- - -## 工具域 - -按**能力**划分,而非按厂商: - -- **Execution** — shell、PTY、统一 exec -- **Filesystem** — 读写、patch、图像 -- **Session** — plan、context、用户输入 -- **Discovery** — 插件、tool_search -- **MCP** — 资源、动态 MCP 工具 -- **Code Mode** — `exec` / `wait` -- **Extension** — memories、skills、web.run、web_search - -见 [工具清单(32)](tools.zh.md)。 - ---- - -## 质量验证 - -Forge 在 CI 中验证工具注册、默认可调用性与核心集成路径(`test_hybrid_forge_callable.py`、`test_pulsing_forge.py`)。 - -```bash -pytest tests/python/test_hybrid_forge_callable.py tests/python/test_pulsing_forge.py -q -``` - ---- - -## 相关 - -- [抽象模型](abstractions.zh.md) -- [Pulsing 集成](pulsing-integration.zh.md) diff --git a/docs/src/forge/deployment.md b/docs/src/forge/deployment.md deleted file mode 100644 index 212fab72a..000000000 --- a/docs/src/forge/deployment.md +++ /dev/null @@ -1,87 +0,0 @@ -# Deployment on Pulsing - -Forge can run **entirely in-process** or use **Pulsing Actors** for isolation and cluster deployment. - ---- - -## ForgeBackend modes - -Unified entry: `python/pulsing/forge/backend.py` - -| Mode | Enum | Behavior | -|------|------|----------| -| **LOCAL** | `ForgeBackendMode.LOCAL` | Host runtime only — no worker | -| **DEDICATED** | `DEDICATED` | One `ToolWorkerActor` per host (via in-process supervisor) | -| **SHARED** | `SHARED` | `resolve("craft/ws/{workspace_id}/_tools")` | - -```python -from pulsing.forge import ForgeBackend, ForgeHostConfig, ForgeIsolatedWorker, create_host_runtime - -host = create_host_runtime(ForgeHostConfig(cwd=".", auto_approve=False)) -worker = ForgeIsolatedWorker.dedicated(ToolWorkerConfig(cwd=".", host_name="craft/ws/x/agent")) -backend = ForgeBackend(host=host, worker=worker, event_sink_name="craft/ws/x/agent/events") -result = await backend.call_tool("Read", {"file_path": "README.md"}) -``` - -Craft uses this path via `tool_host.py` — application code rarely touches spawn directly. - ---- - -## Named Forge actors (Craft bootstrap) - -When a Craft agent has a gossip name, `ensure_forge_actors()` spawns: - -| Actor | Gossip name | Role | -|-------|-------------|------| -| `ForgeEventInbox` | `{host}/events` | Collect tell events; forward streams to Host | -| `McpHubActor` | `craft/ws/{id}/_mcp_hub` | MCP refresh + tool discovery | -| `CodeCellRegistryActor` | `{host}/code_cells` | Code Mode `exec` / `wait` control plane | -| `ToolWorkerActor` | child process | Isolated tool execution | - -Host name vs event sink: - -- **`_forge_host_name`** — exec approval / permissions **ask** target -- **`_event_sink_name`** — Forge **tell** target (usually inbox) - ---- - -## Worker supervision - -`ForgeWorkerSupervisor` (in-process, **not** `@remote`) wraps `ToolWorkerActor`: - -- Spawns child with `pul.spawn(..., new_process=True)` -- Retries once on failure -- Must **not** spawn from inside another actor's mailbox handler - -`ToolWorkerActor` defers heavy init to `on_start` so isolated pickle succeeds. - ---- - -## Shared workspace worker - -```python -from pulsing.forge import spawn_shared_tool_worker, resolve_shared_tool_worker - -await spawn_shared_tool_worker(workspace_id="myws", cwd="/path/to/repo") -worker = await resolve_shared_tool_worker("myws") -``` - -Gossip name: `craft/ws/myws/_tools` (`naming.shared_tool_worker_name`). - ---- - -## When to use which mode - -| Scenario | Mode | -|----------|------| -| Unit tests, REPL | LOCAL | -| Single agent, strong isolation | DEDICATED | -| Many agents, one repo sandbox | SHARED | -| No Pulsing cluster / no agent name | LOCAL or DEDICATED without inbox actors | - ---- - -## Related - -- [Pulsing Integration](pulsing-integration.md) — ask/tell patterns -- [Craft architecture](../design/forge/craft-architecture.md) — full integration diagram diff --git a/docs/src/forge/deployment.zh.md b/docs/src/forge/deployment.zh.md deleted file mode 100644 index a843b62b2..000000000 --- a/docs/src/forge/deployment.zh.md +++ /dev/null @@ -1,78 +0,0 @@ -# Pulsing 部署 - -Forge 可 **纯进程内** 运行,也可通过 **Pulsing Actor** 做隔离与集群部署。 - ---- - -## ForgeBackend 三档 - -统一入口:`python/pulsing/forge/backend.py` - -| 模式 | 枚举 | 行为 | -|------|------|------| -| **LOCAL** | `ForgeBackendMode.LOCAL` | 仅 Host runtime,无 worker | -| **DEDICATED** | `DEDICATED` | 每 Host 一个 `ToolWorkerActor`(经进程内 supervisor) | -| **SHARED** | `SHARED` | `resolve("craft/ws/{workspace_id}/_tools")` | - -Craft 通过 `tool_host.py` 使用此路径,应用代码通常不直接 spawn。 - ---- - -## 命名 Forge Actor(Craft bootstrap) - -具 gossip 名的 Craft Agent 在 `on_start` 调用 `ensure_forge_actors()`: - -| Actor | Gossip 名 | 职责 | -|-------|-----------|------| -| `ForgeEventInbox` | `{host}/events` | 收集 tell 事件;流式转发 Host | -| `McpHubActor` | `craft/ws/{id}/_mcp_hub` | MCP refresh + 工具发现 | -| `CodeCellRegistryActor` | `{host}/code_cells` | Code Mode 控制面 | -| `ToolWorkerActor` | 子进程 | 隔离工具执行 | - -双 sink 约定: - -- **`_forge_host_name`** — 审批 / 权限 **ask** 目标 -- **`_event_sink_name`** — Forge **tell** 目标(通常为 inbox) - ---- - -## Worker 监管 - -`ForgeWorkerSupervisor` 为 **进程内类**(非 `@remote`): - -- `pul.spawn(..., new_process=True)` 拉起 worker -- 失败自动 respawn 一次 -- **禁止**在 Actor mailbox 处理中 spawn 子进程 - -`ToolWorkerActor` 重资源延迟到 `on_start`,保证 isolated pickle 成功。 - ---- - -## Workspace 共享 Worker - -```python -from pulsing.forge import spawn_shared_tool_worker, resolve_shared_tool_worker - -await spawn_shared_tool_worker(workspace_id="myws", cwd="/path/to/repo") -worker = await resolve_shared_tool_worker("myws") -``` - -Gossip 名:`craft/ws/myws/_tools`。 - ---- - -## 选型 - -| 场景 | 模式 | -|------|------| -| 单测、REPL | LOCAL | -| 单 Agent 强隔离 | DEDICATED | -| 多 Agent 共享 sandbox | SHARED | -| 无集群 / 无 agent 名 | LOCAL | - ---- - -## 相关 - -- [Pulsing 集成](pulsing-integration.zh.md) -- [Craft 一体化架构](../design/forge/craft-architecture.zh.md) diff --git a/docs/src/forge/getting-started.md b/docs/src/forge/getting-started.md deleted file mode 100644 index e016d41a6..000000000 --- a/docs/src/forge/getting-started.md +++ /dev/null @@ -1,102 +0,0 @@ -# Getting Started - -## Install - -```bash -pip install pulsing -# Optional extras if defined in your distribution: -# pip install pulsing[forge] -``` - -For Rust-accelerated handlers and MCP runtime: - -```bash -uv run maturin develop # from repo root -``` - ---- - -## Minimal example - -```python -from pulsing.forge import ForgeEnvironment, LocalToolSession - -env = ForgeEnvironment( - cwd=".", - sandbox_policy="off", - session=LocalToolSession(token_budget=128_000), -) -rt = env.runtime() - -out = rt.call_tool("Glob", {"pattern": "*.md", "path": "."}) -print(out.content, out.is_error) -``` - -After `maturin develop`, `env.runtime()` defaults to **`HybridForgeRuntime`**: Rust handlers first, Python fallback for Host-only tools — all **32 tools callable**. - ---- - -## Host session hooks - -Tools like `request_user_input` and `update_plan` call back into **`ToolSession`**: - -```python -from pulsing.forge import ForgeEnvironment, LocalToolSession - -session = LocalToolSession() -session.user_input = lambda args: {"answers": {"confirm": "yes"}} - -env = ForgeEnvironment(session=session) -env.runtime().call_tool("request_user_input", {"questions": [...]}) -``` - -Forge emits structured requests; your Host decides how to show UI or auto-approve. - ---- - -## Isolated worker (Pulsing Actor) - -```python -import pulsing as pul -from pulsing.forge import ToolWorkerActor, ToolWorkerConfig - -await pul.init() -try: - worker = await ToolWorkerActor.spawn(ToolWorkerConfig(cwd="."), public=False) - pong = await worker.ping() - out = await worker.Read(file_path="README.md") -finally: - await pul.shutdown() -``` - -Unified deployment: [`ForgeBackend`](deployment.md) (LOCAL / DEDICATED / SHARED). - ---- - -## REPL (no LLM) - -```bash -python -m pulsing.forge.repl -pulsing forge repl -``` - -Drive tools directly, save JSONL traces, replay steps. See [Session REPL design](../design/forge/session-repl.md). - ---- - -## Verify install - -```bash -pytest tests/python/test_pulsing_forge.py tests/python/test_hybrid_forge_callable.py -q -``` - -Example script: `examples/python/forge_minimal.py` - ---- - -## Next steps - -- [Concepts](concepts.md) — mental model -- [Tools (32)](tools.md) — inventory -- [Deployment on Pulsing](deployment.md) — cluster path -- [Craft integration](../design/forge/craft-architecture.md) — reference Host diff --git a/docs/src/forge/getting-started.zh.md b/docs/src/forge/getting-started.zh.md deleted file mode 100644 index a56ef38a8..000000000 --- a/docs/src/forge/getting-started.zh.md +++ /dev/null @@ -1,97 +0,0 @@ -# 快速开始 - -## 安装 - -```bash -pip install pulsing -``` - -Rust 加速路径与 MCP runtime(仓库开发): - -```bash -uv run maturin develop -``` - ---- - -## 最小示例 - -```python -from pulsing.forge import ForgeEnvironment, LocalToolSession - -env = ForgeEnvironment( - cwd=".", - sandbox_policy="off", - session=LocalToolSession(token_budget=128_000), -) -rt = env.runtime() - -out = rt.call_tool("Glob", {"pattern": "*.md", "path": "."}) -print(out.content, out.is_error) -``` - -`maturin develop` 后默认 **`HybridForgeRuntime`**:Rust 优先 + Python fallback,**32 工具均可调用**。 - ---- - -## Host 会话钩子 - -`request_user_input`、`update_plan` 等通过 **`ToolSession`** 回调 Host: - -```python -from pulsing.forge import ForgeEnvironment, LocalToolSession - -session = LocalToolSession() -session.user_input = lambda args: {"answers": {"confirm": "yes"}} - -env = ForgeEnvironment(session=session) -env.runtime().call_tool("request_user_input", {"questions": [...]}) -``` - ---- - -## 隔离 Worker(Pulsing Actor) - -```python -import pulsing as pul -from pulsing.forge import ToolWorkerActor, ToolWorkerConfig - -await pul.init() -try: - worker = await ToolWorkerActor.spawn(ToolWorkerConfig(cwd="."), public=False) - await worker.ping() - await worker.Read(file_path="README.md") -finally: - await pul.shutdown() -``` - -统一部署见 [Pulsing 部署](deployment.zh.md)(LOCAL / DEDICATED / SHARED)。 - ---- - -## REPL(无 LLM) - -```bash -python -m pulsing.forge.repl -``` - -直接调工具、保存 JSONL trace、逐步 replay。设计说明:[Session REPL](../design/forge/session-repl.zh.md)。 - ---- - -## 验证 - -```bash -pytest tests/python/test_pulsing_forge.py tests/python/test_hybrid_forge_callable.py -q -``` - -示例:`examples/python/forge_minimal.py` - ---- - -## 下一步 - -- [核心概念](concepts.zh.md) -- [工具清单(32)](tools.zh.md) -- [Pulsing 部署](deployment.zh.md) -- [Craft 集成](../design/forge/craft-architecture.zh.md) diff --git a/docs/src/forge/index.md b/docs/src/forge/index.md deleted file mode 100644 index 9fe81042f..000000000 --- a/docs/src/forge/index.md +++ /dev/null @@ -1,90 +0,0 @@ -# Pulsing Forge - -**Agent tool and environment runtime** for coding agents — sandboxed shell, filesystem, session tools, MCP, and plugins in one embeddable library. - -> **Snapshot**: 2026-05 · **32 tools callable out of the box** (Hybrid + MCP runtime) -> **Import**: `pip install pulsing` → `from pulsing.forge import ForgeEnvironment` - -!!! info "Current API and target architecture" - - This chapter documents the **current tool/environment runtime**. The accepted target expands Forge into the persistent, self-evolving Agent Runtime and makes GUI, CLI, and Python SDK clients of one protocol. See [Forge Core Architecture](../design/forge/core-architecture.md). Target-state text is not a claim that those capabilities are implemented. - ---- - -## One sentence - -Forge answers: **given a tool name and JSON arguments, how do we execute safely in a workspace?** - -It is **not** a chat product or CLI clone. **Host** owns LLM and UI; **Forge** owns environment and tool execution. - ---- - -## Why Forge - -| Pain | Forge provides | -|------|----------------| -| Reimplementing Read / shell / patch per project | One tool surface + `ToolResult` | -| Scattered sandbox policy | `sandbox_policy`: `off` / `restricted` / `bwrap` | -| Plan / prompts coupled to tools | `ToolSession` callbacks — Forge has no built-in UI | -| Dev vs isolated execution drift | Same 32 tool names: in-process or `ToolWorkerActor` | - ---- - -## Ecosystem - -```text -Pulsing Distributed Actor runtime (optional) -Pulsing Forge Tool + environment library (this chapter) -Craft Multi-Agent reference app (Forge reference Host) -``` - ---- - -## Three deployment modes - -| Mode | API | Use when | -|------|-----|----------| -| **In-process** | `ForgeEnvironment.runtime()` | Tests, prototypes | -| **Hybrid (default)** | `HybridForgeRuntime` after `maturin develop` | Production host tools | -| **Isolated actor** | `ForgeBackend` + `ToolWorkerActor` | Sandbox in child process / cluster | - -Same LLM tool schema across modes. - ---- - -## Quick start - -```python -from pulsing.forge import ForgeEnvironment, LocalToolSession - -env = ForgeEnvironment(cwd=".", session=LocalToolSession()) -rt = env.runtime() -rt.call_tool("shell_command", {"cmd": "pytest -q", "workdir": "."}) -``` - -See [Getting Started](getting-started.md) · [Abstractions](abstractions.md) · [Deployment on Pulsing](deployment.md). - ---- - -## Documentation map - -| Doc | Audience | -|-----|----------| -| [Getting Started](getting-started.md) | Install, first `call_tool`, tests | -| [Concepts](concepts.md) | Host vs Forge, core types | -| [Abstractions](abstractions.md) | Environment, Session, tool domains | -| [Tools (32)](tools.md) | Tool inventory by domain | -| [Deployment on Pulsing](deployment.md) | `ForgeBackend`, actors, isolation | -| [Pulsing Integration](pulsing-integration.md) | ask/tell, inbox, MCP hub, code cells | - -**Design deep dives** (Architecture & Design → Forge): - -- [Core Architecture](../design/forge/core-architecture.md) · [Engineering](../design/forge/engineering.md) · [Craft architecture](../design/forge/craft-architecture.md) - -**Package README**: [python/pulsing/forge/README.md](https://github.com/DeepLink-org/pulsing/blob/main/python/pulsing/forge/README.md) - ---- - -## License - -Apache-2.0 · Third-party notices in `crates/pulsing-forge/NOTICE` diff --git a/docs/src/forge/index.zh.md b/docs/src/forge/index.zh.md deleted file mode 100644 index 37e9e446c..000000000 --- a/docs/src/forge/index.zh.md +++ /dev/null @@ -1,350 +0,0 @@ -# Pulsing Forge — Agent 执行环境 - -> **读者**:想集成 coding agent 的开发者、框架作者、技术决策者 -> **版本快照**:2026-05 · **32 工具开箱 callable**(Hybrid + MCP runtime) -> **代码入口**:`pip install pulsing` → `from pulsing.forge import ForgeEnvironment` - -!!! info "当前 API 与目标架构" - - 本章描述的是**当前工具与环境运行时**。已接受的目标架构将 Forge 扩展为持久、自进化的 Agent Runtime,并让 GUI、CLI、Python SDK 成为同一协议的客户端。见 [Forge 核心架构](../design/forge/core-architecture.zh.md)。目标设计不代表对应能力已经实现。 - ---- - -## 一句话 - -**Pulsing Forge 是给 AI Agent 用的「工作环境运行时」**——在指定 workspace 里安全地跑 shell、改文件、读图像、维护计划、连接 MCP,而不必在每个项目里重新拼 subprocess、sandbox、工具 schema 和审批流。 - -Forge **不是**某个 CLI 的换皮,也 **不是**完整 Agent 产品。它是一层可嵌入的库:**Host 管 LLM 与 UI,Forge 管环境 + 工具执行**。 - ---- - -## 为什么需要 Forge - -几乎每个 coding agent 项目都会重复造同一套轮子: - -| 重复劳动 | 典型痛点 | -|----------|----------| -| Shell / Read / patch | 每家参数名不同,错误处理各自为政 | -| 沙箱 | 策略散落,dev 与 prod 行为不一致 | -| Plan / 弹窗 / token 预算 | 与工具层强耦合,难以换 UI | -| 插件与 MCP | handler 有了,runtime 没接上,装完 server 调不动 | -| 本地调试 vs 隔离执行 | 两套代码路径,行为漂移 | - -Forge 把这些收敛成 **一套工具面 + 一个 Environment 抽象**,Host 只需实现 `ToolSession`(产品侧回调),其余交给运行时。 - ---- - -## 设计哲学 - -### 1. 环境优先,而非对话优先 - -Forge 回答的问题是:**「给定 tool name + JSON args,在 workspace 里怎么安全执行?」** - -它不管理对话历史、不选模型、不做登录——这些属于 Host。这种切分让 Forge 可以嵌入 LangChain、自研 loop、Craft、企业审批流,而不绑定某一种 LLM 产品形态。 - -### 2. Host 与 Forge 职责分离 - -```text -┌──────────────────────────────────────────┐ -│ Host(你的产品) │ -│ LLM loop · TUI/Web · 审批 UI · 记忆产品 │ -│ 实现 ToolSession:plan / 用户输入 / token │ -└────────────────────┬─────────────────────┘ - │ call_tool(name, args) -┌────────────────────▼─────────────────────┐ -│ Forge │ -│ 沙箱 · execpolicy · patch · MCP · 插件 │ -│ 返回 ToolResult { content, is_error } │ -└──────────────────────────────────────────┘ -``` - -Forge 发出**结构化请求**(「请批准这条命令」「请回答这个问题」);Host 决定如何展示、阻塞或自动批准。Forge 内置 UI 是非目标。 - -### 3. 一套工具面,多种部署形态 - -同一组 32 个工具名与参数,可在三种模式下运行: - -| 模式 | API | 适用 | -|------|-----|------| -| **进程内** | `ForgeEnvironment.runtime()` | 单进程 Agent、单元测试、快速原型 | -| **Rust 高性能路径** | `HybridForgeRuntime`(默认) | maturin 构建后的生产默认 | -| **Actor 隔离** | `ToolWorkerActor` | 子进程 / 集群 worker,与 Pulsing gossip 共享 | - -Host 换部署方式时,**LLM 侧 tool schema 不必改**。 - -### 4. Rust 核心 + Python 生态 - -执行热路径(shell、patch、文件、审批门、MCP client)在 Rust crate `pulsing-forge` 中实现;Python 提供 Actor 绑定、Code Mode、Extension 与 fallback。默认 **Hybrid dispatch**:Rust 优先,暂无 Rust handler 的工具自动走 Python——保证 **32 工具开箱 callable**。 - -### 5. 可验证的质量,而非口号 - -Forge 在 CI 中持续验证工具注册、默认可调用性与核心集成场景(`test_hybrid_forge_callable.py`、`test_pulsing_forge.py` 等)。对外说明能力边界时以测试结果为准,缺口诚实公开。 - ---- - -## Forge 是什么 / 不是什么 - -| ✅ Forge 是 | ❌ Forge 不是 | -|-------------|--------------| -| Agent 工具与环境运行时(库) | 完整 Agent OS 或 Chat 产品 | -| 可沙箱化的 workspace 执行层 | 容器编排(K8s 层由部署解决) | -| 主流 coding agent 工具面 + Claude 互操作 helper | 某单一 CLI / TUI 的复刻 | -| MCP runtime + 插件安装骨架 | MCP 目录 UI 或 OAuth 登录产品 | -| 与 Pulsing Actor 可选集成 | 强依赖分布式集群才能用 | - ---- - -## 架构一览 - -```text -Host 创建 ForgeEnvironment(cwd, sandbox_policy, session) - │ - ▼ - HybridForgeRuntime ← maturin 构建后默认 - ├─ Rust ForgeRuntime ← 22 handler + MCP runtime - └─ Python LocalToolRuntime ← 10 个 Host-only 工具 fallback - │ - ▼ - Handlers(按域) - Execution · Filesystem · Session · Discovery · MCP · Code Mode · Extension - │ - ▼ - ToolResult → Host(或 Craft.on_forge_event 事件流) -``` - -**三个核心类型**(详见 [abstractions.md](./abstractions.md)): - -- **`ForgeEnvironment`** — 工作区根目录、沙箱策略、会话钩子 -- **`ToolSession`** — Host 实现的产品能力(plan、用户输入、审批) -- **`ToolResult`** — 统一返回 `{ content, is_error, structured? }` - ---- - -## 工具能力全景(32 个) - -Forge 注册 **32 个标准工具**,覆盖主流 coding agent 主路径: - -### 隔离执行(11)— 适合 Actor worker - -在沙箱进程里跑,不污染 Host 状态: - -`Read` · `Glob` · `Grep` · `Edit` · `Write` · `Bash` · `shell_command` · `exec_command` · `write_stdin` · `apply_patch` · `view_image` - -### Host 协作(21)— 需要 UI 或全局状态 - -| 域 | 工具 | -|----|------| -| **Session** | `update_plan` · `new_context` · `get_context_remaining` · `request_user_input` · `request_permissions` | -| **Discovery / 插件** | `tool_search` · `list_available_plugins_to_install` · `request_plugin_install` | -| **MCP** | `list_mcp_resources` · `list_mcp_resource_templates` · `read_mcp_resource` | -| **Code Mode** | `exec` · `wait` | -| **Extension** | `web.run` · `skills.list` · `skills.read` · `memories.*`(4)· `web_search` | - -另:**Forge 额外**提供 `Read`/`Glob`/…/`Bash`(Claude 互操作 alias),与 Session 域工具互补。 - -完整参数见 [包内 README](https://github.com/DeepLink-org/pulsing/blob/main/python/pulsing/forge/README.md)。 - ---- - -## 开箱即用:Hybrid + MCP - -**2026-05 现状**(对外可宣传的能力): - -1. **`maturin develop` / 正式 wheel 安装后**,`ForgeEnvironment().runtime()` 默认走 `HybridForgeRuntime` -2. **32 工具均可调用**,不会出现 `Unknown tool`(CI:`test_hybrid_forge_callable.py`) -3. **MCP runtime 默认启动**:`list_mcp_resources` 等 wired;无配置 server 时返回空列表,而非 runtime 未初始化 -4. **Craft 已接入**:Host 路径 Hybrid、插件安装后 `refresh_mcp()`、隔离 worker 同套工具面 - -```python -from pulsing.forge import ForgeEnvironment - -env = ForgeEnvironment.ephemeral(cwd="/path/to/repo") # 本地 dev 默认 auto_approve -rt = env.runtime() - -rt.call_tool("shell_command", { - "command": "pytest -q", - "workdir": "/path/to/repo", - "timeout_ms": 60_000, -}) -rt.call_tool("list_mcp_resources", {}) -rt.call_tool("memories.list", {}) -``` - ---- - -## 成熟度与边界 - -**当前(2026-05)** - -| 维度 | 状态 | -|------|------| -| 32 工具 callable | ✅ Hybrid dispatch + Python fallback | -| MCP runtime | ✅ wired;无 server 时返回空列表 | -| Actor 隔离 worker | ✅ `ToolWorkerActor` + `ForgeBackend` | -| Code Mode L2 | 🟡 控制面 Actor 已接,后台续跑推进中 | -| MCP 动态进 LLM | 🟡 Hub + sync 已接,产品侧持续完善 | - -```bash -pytest tests/python/test_hybrid_forge_callable.py tests/python/test_pulsing_forge.py -q -``` - -### 已知边界(发版说明级) - -| 已就绪 | 仍在推进 | -|--------|----------| -| 32 工具 callable、Hybrid dispatch | Code Mode 后台 cell、yield 续跑 | -| MCP runtime live、refresh API | 动态 MCP 工具自动进 LLM schema | -| execpolicy + 审批门(Rust) | 更完整的 policy 与 sandbox 集成 | -| memories Extension 本地 L2 | web.run / skills authority、hosted search | -| Pulsing Actor 隔离 worker | Craft 与 Forge 集成测试持续加强 | - ---- - -## 适用场景 - -### 适合用 Forge - -- 你在做 **coding agent / dev agent**,需要稳定的 shell + 文件 + patch 工具层 -- 你想 **标准 coding agent 工具面**,又不想绑定某一家的 Chat 产品壳 -- 你需要 **同一套工具** 在本地进程与隔离 worker 之间切换 -- 你用 **Pulsing** 做分布式 Agent,需要 gossip 共享的 tool worker -- 你在评估 **Craft** 或想参考其 Multi-Agent 架构(Craft 是 Forge 的参考 Host) - -### 可能不需要 Forge - -- 只要简单 `subprocess.run` 一两个命令(直接写即可) -- 需要完整开箱 Chat 产品(看 Craft 或自建 Host + Forge) -- 只要 MCP server 开发、不要 agent 工具层(Forge 范围过大) - ---- - -## 5 分钟上手 - -### 安装 - -```bash -pip install pulsing -# 从源码开发(Rust 路径 + Hybrid 默认): -maturin develop # 或 uv run maturin develop -``` - -### 最小示例 - -```python -from pulsing.forge import ForgeEnvironment, LocalToolSession - -env = ForgeEnvironment( - cwd=".", - session=LocalToolSession(token_budget=128_000), -) -rt = env.runtime() - -# 读文件 -print(rt.call_tool("Read", {"file_path": "README.md"})) - -# 跑测试 -print(rt.call_tool("shell_command", { - "command": "pytest tests/python/test_pulsing_forge.py -q", - "workdir": ".", - "timeout_ms": 120_000, -})) -``` - -### 接入自研 Agent loop - -```python -# 伪代码:把 Forge 当 tool backend -FORGE_TOOLS = env.runtime().tool_names() # 32 个 - -async def on_llm_tool_call(name: str, arguments: dict): - result = env.runtime().call_tool(name, arguments) - return result.content -``` - -### 接入 Pulsing 隔离 worker - -```python -import pulsing as pul -from pulsing.forge import ToolWorkerActor, ToolWorkerConfig - -await pul.init() -worker = await ToolWorkerActor.spawn(config=ToolWorkerConfig(cwd=".")) -out = await worker.Read(file_path="README.md") -await pul.shutdown() -``` - ---- - -## 与 Pulsing 生态的关系 - -```text -Pulsing 分布式 Actor 运行时(集群、gossip、隔离 spawn) - │ -Pulsing Forge Agent 工具与环境(import: pulsing.forge) ← 本文 - │ -Craft Multi-Agent 参考应用(pulsing.craft,Forge 的参考 Host) -``` - -- **只用 Forge**:`ForgeEnvironment` + `runtime()`,无需启动集群 -- **Forge + Pulsing**:`ToolWorkerActor` 隔离执行,事件经 `tell_forge_event` 回 Host -- **Forge + Craft**:开箱 Multi-Agent、审批 UI、LLM schema(Craft 侧 schema 仍在补全) - -Forge 可独立嵌入;Pulsing 与 Craft 是「把 Forge 跑满」的推荐路径,不是硬性依赖。 - ---- - -## 与其他方案的比较 - -| 维度 | 自研 subprocess | LangChain Tools | 闭源 Agent CLI | **Pulsing Forge** | -|------|-----------------|-----------------|----------------|-------------------| -| 工具面统一 | ❌ 各自实现 | 框架绑定 | 产品内封闭 | ✅ 32 工具标准面 | -| 沙箱 / execpolicy | 自行维护 | 通常无 | 通常成熟 | 🟡 Rust 门控 + 持续完善 | -| MCP | 自行接 | 视集成而定 | 视产品而定 | ✅ runtime wired | -| 与 Host 解耦 | ✅ | 部分 | ❌ 产品绑定 | ✅ ToolSession 边界 | -| 隔离 / 集群执行 | 自行造 | 通常无 | 单机为主 | ✅ Actor worker | -| 开源可嵌入 | ✅ | ✅ | ❌ | ✅ | - -Forge 的定位:**开源、可嵌入、基于 Pulsing Actor** 的 agent 执行层——介于「自己拼 shell」与「绑定完整闭源产品」之间。 - ---- - -## 路线图(高层) - -1. **MCP 动态注册** — 插件安装 → server 拉起 → 工具进 LLM catalog -2. **Code Mode L2** — 后台 cell、yield 续跑(Python / Actor 控制面) -3. **Rust handler 覆盖** — execpolicy、unified_exec、Extension 深化 -4. **Forge × Pulsing** — 事件 Queue、多节点 worker(见 [Pulsing 集成](pulsing-integration.zh.md)) - ---- - -## 文档导航 - -| 文档 | 适合谁 | -|------|--------| -| **本文** | 对外介绍、选型、推广 | -| [快速开始](getting-started.zh.md) | 安装与首个 `call_tool` | -| [核心概念](concepts.zh.md) | Host / Forge 心智模型 | -| [抽象模型](abstractions.zh.md) | Environment、Session、工具域 | -| [工具清单(32)](tools.zh.md) | 按域划分的工具表 | -| [Pulsing 部署](deployment.zh.md) | ForgeBackend、Actor 拓扑 | -| [Pulsing 集成](pulsing-integration.zh.md) | ask/tell、能力矩阵 | -| [包内 README](https://github.com/DeepLink-org/pulsing/blob/main/python/pulsing/forge/README.md) | API 速查 | -| [Craft 一体化](../design/forge/craft-architecture.zh.md) | 架构 Review | -| [工程说明](../design/forge/engineering.zh.md) | crate 与实现细节 | - ---- - -## 许可与致谢 - -Apache-2.0。Rust 核心 crate:`pulsing-forge`。部分实现参考了业界开源 agent-tool 实践;第三方声明见 `crates/pulsing-forge/NOTICE`。 - -**Try it:** - -```bash -pip install pulsing && python -c " -from pulsing.forge import ForgeEnvironment -print(ForgeEnvironment.ephemeral().runtime().call_tool('Glob', {'pattern': '*.md', 'path': '.'})) -" -``` - -有问题或集成需求,欢迎从 [快速开始](getting-started.zh.md) 入手,或查阅 `tests/python/test_hybrid_forge_callable.py` 了解 32 工具 smoke 覆盖。 diff --git a/docs/src/forge/pulsing-integration.md b/docs/src/forge/pulsing-integration.md deleted file mode 100644 index b26a41d68..000000000 --- a/docs/src/forge/pulsing-integration.md +++ /dev/null @@ -1,94 +0,0 @@ -# Pulsing Integration - -How Forge uses Pulsing Actor capabilities — and what remains in-process. - ---- - -## Capability matrix - -| Pulsing feature | Forge usage | Maturity | -|-----------------|-------------|:--------:| -| `@remote` + spawn | `ToolWorkerActor`, inbox, MCP hub, code registry | ✅ | -| `resolve` (gossip) | Shared worker, inbox, hub, registry | ✅ | -| `ask` | Exec approval, permissions, code cell nested tools | ✅ | -| `tell` | Forge events, inbox → Host side effects | ✅ | -| `new_process` | Isolated `ToolWorkerActor` | ✅ | -| `ForgeBackend` | LOCAL / DEDICATED / SHARED | ✅ | -| Supervision policy | Manual respawn via supervisor | 🟡 | -| Queue / Topic | Not used — events in memory | ⚪ | -| Multi-node placement | Local spawn only | ⚪ | - ---- - -## Message flows - -### Tool execution - -```text -CraftAgent.call_tool("Read", ...) - → ForgeBackend - → ForgeWorkerSupervisor → ToolWorkerActor (child process) - → ToolResult -``` - -### Events (streaming) - -```text -Worker / Host runtime - → tell_forge_event(inbox) - → ForgeEventInbox.on_forge_event - → tell Host.on_forge_stream_event / on_forge_side_effect -``` - -### Approvals (blocking) - -```text -Worker - → ask Host.resolve_exec_approval - → Host UI / PermissionChecker - → decision dict -``` - ---- - -## What stays in-process (by design) - -| Component | Reason | -|-----------|--------| -| `HybridForgeRuntime` | PyO3 callbacks, Session state, MCP in Rust | -| `ForgeWorkerSupervisor` | Cannot spawn child from actor mailbox | -| REPL `LocalToolRuntime` | Debug path without cluster | -| Extension handlers | Local I/O, no cross-node need | - -This is **intentional layering**: Actor for deployment boundaries, not for every function call. - ---- - -## Developer-facing surface - -Most integrators should use: - -```python -from pulsing.forge import ForgeEnvironment # library / tests -from pulsing.forge import ForgeBackend, ... # Craft-style host -``` - -Only advanced hosts need `tell_forge_event`, `ensure_forge_actors`, or custom gossip names. - ---- - -## Constraints (read before extending) - -1. **No `new_process` spawn inside actor mailbox handlers** — use Host process or delayed patterns. -2. **Isolated actors must pickle cleanly** — defer locks / exec managers to `on_start`. -3. **Separate approval sink from event sink** — inbox receives tells; Host receives asks. - ---- - -## Next steps (P1+) - -- Forge events → Pulsing `Queue` for audit and replay -- REPL remote worker mode (`resolve` shared worker) -- Optional multi-node worker placement - -Design reference: [craft-architecture](../design/forge/craft-architecture.md) diff --git a/docs/src/forge/pulsing-integration.zh.md b/docs/src/forge/pulsing-integration.zh.md deleted file mode 100644 index a6d13a78b..000000000 --- a/docs/src/forge/pulsing-integration.zh.md +++ /dev/null @@ -1,83 +0,0 @@ -# Pulsing 集成 - -Forge 如何使用 Pulsing Actor 能力,以及哪些部分刻意保持进程内。 - ---- - -## 能力矩阵 - -| Pulsing 能力 | Forge 用法 | 成熟度 | -|-------------|-----------|:------:| -| `@remote` + spawn | `ToolWorkerActor`、inbox、MCP hub、code registry | ✅ | -| `resolve` | 共享 worker、inbox、hub、registry | ✅ | -| `ask` | 审批、权限、Code Mode 嵌套工具 | ✅ | -| `tell` | Forge 事件、inbox → Host 副作用 | ✅ | -| `new_process` | 隔离 `ToolWorkerActor` | ✅ | -| `ForgeBackend` | LOCAL / DEDICATED / SHARED | ✅ | -| Supervision | supervisor 手工 respawn | 🟡 | -| Queue / Topic | 未用,事件在内存 | ⚪ | -| 多节点 placement | 仅本机 spawn | ⚪ | - ---- - -## 消息路径 - -### 工具执行 - -```text -CraftAgent.call_tool → ForgeBackend → Supervisor → ToolWorkerActor → ToolResult -``` - -### 事件(流式) - -```text -Worker/Host → tell inbox → ForgeEventInbox → tell Host(stream / side_effect) -``` - -### 审批(同步) - -```text -Worker → ask Host.resolve_exec_approval → UI → decision -``` - ---- - -## 刻意进程内的部分 - -| 组件 | 原因 | -|------|------| -| `HybridForgeRuntime` | PyO3 回调、Session、Rust MCP | -| `ForgeWorkerSupervisor` | 不能在 mailbox 内 spawn 子进程 | -| REPL | 调试路径 | -| Extension | 本地 I/O | - -Actor 用于**部署边界**,不是每个函数调用都 Actor 化。 - ---- - -## 对外 API(集成者) - -```python -from pulsing.forge import ForgeEnvironment # 库 / 单测 -from pulsing.forge import ForgeBackend, ... # 类 Craft Host -``` - -只有高级 Host 才需要直接操作 `tell_forge_event` 或 gossip 命名。 - ---- - -## 扩展前必读 - -1. **不要在 Actor mailbox 里 `new_process` spawn** -2. **隔离 Actor 必须可 pickle** — 重对象放 `on_start` -3. **审批 sink 与事件 sink 分离** — inbox 收 tell,Host 收 ask - ---- - -## 后续(P1+) - -- 事件进 Pulsing `Queue`(审计 / replay) -- REPL 远程 worker 模式 -- 跨节点 worker placement - -设计详图:[Craft 一体化架构](../design/forge/craft-architecture.zh.md) diff --git a/docs/src/forge/tools.md b/docs/src/forge/tools.md deleted file mode 100644 index d9dc7eacd..000000000 --- a/docs/src/forge/tools.md +++ /dev/null @@ -1,66 +0,0 @@ -# Tools (32) - -Forge registers **32 standard tools** covering the main coding-agent path. Definitions: `python/pulsing/forge/integrated.py`. - ---- - -## By deployment - -| Partition | Count | Runs on | -|-----------|------:|---------| -| **Isolated** | 11 | `ToolWorkerActor` (child process) | -| **Host** | 21 | `HybridForgeRuntime` / in-process | - -Host and isolated sets are **disjoint** — routing is automatic via `ForgeBackend`. - ---- - -## Isolated (11) - -Filesystem, shell, patch (sandbox boundary): - -`Read` · `Glob` · `Grep` · `Edit` · `Write` · `Bash` · `shell_command` · `exec_command` · `write_stdin` · `apply_patch` · `view_image` - ---- - -## Host (21) - -| Domain | Tools | -|--------|-------| -| **Session** | `update_plan`, `new_context`, `get_context_remaining`, `request_user_input`, `request_permissions` | -| **Discovery** | `tool_search`, `request_plugin_install`, `list_resources` | -| **MCP** | `list_mcp_resources`, `list_mcp_resource_templates`, `mcp__*` (dynamic) | -| **Code Mode** | `exec`, `wait` | -| **Extension** | `memories.*`, `skills.*`, `web.run`, `web_search` (8) | - -**Python-only Host (10)** when Rust lacks handler: `exec`, `wait`, Extension×8 — covered by Hybrid fallback. - ---- - -## Claude interoperability - -Forge also exposes Claude-style names (`Read`, `Bash`, …) on the isolated path — complementary to the standard tool surface. - ---- - -## Dynamic tools - -- **Plugin / tool_search** — deferred stubs activated after search -- **MCP** — live tools after `refresh_mcp()`; registered into Host LLM schema via MCP hub sync - ---- - -## Verification - -```bash -pytest tests/python/test_hybrid_forge_callable.py -q -pytest tests/python/craft/test_tools.py -q # Craft schema coverage -pytest tests/python/test_pulsing_forge.py -q -``` - ---- - -## Deep reference - -- [Engineering](../design/forge/engineering.md) — crate layout and implementation -- Package API table: [python/pulsing/forge/README.md](https://github.com/DeepLink-org/pulsing/blob/main/python/pulsing/forge/README.md) diff --git a/docs/src/forge/tools.zh.md b/docs/src/forge/tools.zh.md deleted file mode 100644 index 7607c6a93..000000000 --- a/docs/src/forge/tools.zh.md +++ /dev/null @@ -1,66 +0,0 @@ -# 工具清单(32) - -Forge 注册 **32 个标准工具**,覆盖主流 coding agent 主路径。定义见 `python/pulsing/forge/integrated.py`。 - ---- - -## 按部署划分 - -| 分区 | 数量 | 运行位置 | -|------|------:|----------| -| **隔离** | 11 | `ToolWorkerActor`(子进程) | -| **Host** | 21 | `HybridForgeRuntime` / 进程内 | - -两套工具名 **不相交**,由 `ForgeBackend` 自动路由。 - ---- - -## 隔离(11) - -文件、shell、patch(沙箱边界): - -`Read` · `Glob` · `Grep` · `Edit` · `Write` · `Bash` · `shell_command` · `exec_command` · `write_stdin` · `apply_patch` · `view_image` - ---- - -## Host(21) - -| 域 | 工具 | -|----|------| -| **Session** | `update_plan`, `new_context`, `get_context_remaining`, `request_user_input`, `request_permissions` | -| **发现** | `tool_search`, `request_plugin_install`, `list_resources` | -| **MCP** | `list_mcp_resources`, `list_mcp_resource_templates`, `mcp__*`(动态) | -| **Code Mode** | `exec`, `wait` | -| **Extension** | `memories.*`, `skills.*`, `web.run`, `web_search`(共 8 个) | - -Rust 暂无 handler 的 **10 个 Host 工具**由 Hybrid Python fallback 覆盖。 - ---- - -## Claude 互操作 - -隔离路径上的 `Read`、`Bash` 等 Claude 风格命名与标准工具面互补。 - ---- - -## 动态工具 - -- **插件 / tool_search** — 延迟注册,搜索后激活 -- **MCP** — `refresh_mcp()` 后 live 工具经 Hub 同步进 LLM schema - ---- - -## 验证 - -```bash -pytest tests/python/test_hybrid_forge_callable.py -q -pytest tests/python/craft/test_tools.py -q -pytest tests/python/test_pulsing_forge.py -q -``` - ---- - -## 深入 - -- [工程说明](../design/forge/engineering.zh.md) -- [包内 API 表](https://github.com/DeepLink-org/pulsing/blob/main/python/pulsing/forge/README.md) diff --git a/docs/src/guide/actors.md b/docs/src/guide/actors.md index f0072daa9..32873e9ba 100644 --- a/docs/src/guide/actors.md +++ b/docs/src/guide/actors.md @@ -344,4 +344,3 @@ await pul.shutdown() - [Remote Actors](remote_actors.md) — cluster communication - [Reliability](reliability.md) — idempotency, retries, timeouts - [Operations](operations.md) — CLI tools for inspection -- [LLM Inference](../examples/llm_inference.md) — production inference setup diff --git a/docs/src/guide/actors.zh.md b/docs/src/guide/actors.zh.md index 166b9c5ad..e8ea593c2 100644 --- a/docs/src/guide/actors.zh.md +++ b/docs/src/guide/actors.zh.md @@ -344,4 +344,3 @@ await pul.shutdown() - [远程 Actor](remote_actors.zh.md) — 集群通信 - [可靠性](reliability.zh.md) — 幂等、重试、超时 - [运维操作](operations.zh.md) — CLI 检查工具 -- [LLM 推理](../examples/llm_inference.zh.md) — 生产推理部署 diff --git a/docs/src/guide/index.md b/docs/src/guide/index.md index 1a114e09d..e1c8a4ca6 100644 --- a/docs/src/guide/index.md +++ b/docs/src/guide/index.md @@ -55,6 +55,5 @@ This guide covers **how to build** with Pulsing. For design rationale, see [Arch | Choose communication pattern | [Communication Patterns](communication_patterns.md) | | Reliability patterns | [Reliability](reliability.md) | | Secure your cluster | [Security](security.md) | -| Run LLM inference | [LLM Inference](../quickstart/llm_inference.md) | | API details | [API Overview](../api/overview.md) | | Full API contract | [Complete Reference](../api_reference.md) | diff --git a/docs/src/guide/index.zh.md b/docs/src/guide/index.zh.md index aeccd7e30..80427cc27 100644 --- a/docs/src/guide/index.zh.md +++ b/docs/src/guide/index.zh.md @@ -55,6 +55,5 @@ | 选择通信范式 | [通信范式](communication_patterns.zh.md) | | 可靠性模式 | [可靠性](reliability.zh.md) | | 保护集群安全 | [安全](security.zh.md) | -| 运行 LLM 推理 | [LLM 推理](../quickstart/llm_inference.zh.md) | | API 详情 | [API 概述](../api/overview.zh.md) | | 完整 API 契约 | [完整参考](../api_reference.zh.md) | diff --git a/docs/src/guide/operations.md b/docs/src/guide/operations.md index 93a732ba5..9123d24f2 100644 --- a/docs/src/guide/operations.md +++ b/docs/src/guide/operations.md @@ -1,231 +1,40 @@ -# CLI Commands +# CLI Operations -Pulsing ships with built-in CLI tools for starting actors, inspecting systems, and benchmarking distributed services. +## Start an actor ---- - -## Starting Actors - -The `pulsing actor` command starts actors by providing their full class path. Arguments are split by `--` so that **actor-level options** (e.g. `--addr`, `--seeds`, `--name`) and **Actor constructor arguments** never collide. - -### Parameter separation (`--`) - -- **Before `--`**: All arguments are passed to the `actor` subcommand as-is (positional actor type + any options such as `--addr`, `--seeds`, `--name`). -- **After `--`**: All `--key value` pairs are collected and passed to the Actor's constructor. Use this to avoid name collision with actor-level options. - -If you omit `--`, only the arguments recognized by the `actor` subcommand are used; constructor args must then be passed via `-D actor.extra_kwargs='{"key":"value"}'` or by using `--` when you need to pass both. - -### Format - -Actor type must be a full class path: -- Format: `module.path.ClassName` -- Example: `pulsing.serving.Router` -- Example: `pulsing.serving.TransformersWorker` -- Example: `pulsing.serving.VllmWorker` -- Example: `my_module.my_actor.MyCustomActor` - -### Examples - -#### Router (OpenAI-compatible HTTP API) - -```bash -# Actor-level (addr, name) before --; Router constructor args after -- -pulsing actor pulsing.serving.Router \ - --addr 0.0.0.0:8000 \ - --name my-llm \ - -- \ - --http_port 8080 \ - --model_name gpt2 \ - --worker_name worker -``` - -#### Transformers Worker - -```bash -pulsing actor pulsing.serving.TransformersWorker \ - --addr 0.0.0.0:8001 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model_name gpt2 -``` - -#### vLLM Worker - -```bash -pulsing actor pulsing.serving.vllm.VllmWorker \ - --addr 0.0.0.0:8002 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model Qwen/Qwen2 \ - --role aggregated \ - --max_new_tokens 512 -``` - -#### Multiple Workers +Provide an importable user class implementing the actor API: ```bash -# Start multiple workers with different names -pulsing actor pulsing.serving.TransformersWorker \ - --name worker-1 \ - --seeds 127.0.0.1:8000 \ - -- --model_name gpt2 - -pulsing actor pulsing.serving.TransformersWorker \ - --name worker-2 \ - --seeds 127.0.0.1:8000 \ - -- --model_name gpt2 - -# Router targeting specific worker name -pulsing actor pulsing.serving.Router \ - --addr 0.0.0.0:8000 \ - --seeds 127.0.0.1:8000 \ - -- --worker_name worker-1 +pulsing actor my_app.Counter --addr 0.0.0.0:8000 --name counter -- --initial 10 ``` -### Common options (before `--`) - -- `--name NAME`: Actor name (default: "worker") -- `--addr ADDR`: Actor System bind address -- `--seeds SEEDS`: Comma-separated list of seed nodes - -Arguments after `--` are passed to the Actor's constructor as `--key value` pairs. - -The Actor class must: -- Be importable from the specified module path -- Be an `pulsing.core.Actor` subclass or a `@pulsing.remote` class -- Have a constructor with named parameters (arguments after `--` are matched to constructor parameters) - -**How it works:** The CLI passes everything before `--` to the actor subcommand, and collects every `--key value` after `--` into the Actor constructor. Use `pulsing actor --help` to see actor-level options; for constructor parameters, see the Actor class documentation. +Options before `--` configure the node and actor registration. +Options after `--` are passed to the actor constructor. +Use `--seeds 127.0.0.1:8000` to join an existing cluster. ---- +## Inspect a cluster ---- - -## Inspect - -`pulsing inspect` is a lightweight **observer** tool that queries actor systems via HTTP (no cluster join required). It provides multiple subcommands for different inspection needs. - -### Subcommands - -#### Cluster Status - -Inspect cluster members and their status: +Inspection uses HTTP observer mode and does not join the cluster. ```bash pulsing inspect cluster --seeds 127.0.0.1:8000 -``` - -Output includes: -- Total nodes and alive count -- Status summary (Alive, Suspect, Failed, etc.) -- Detailed member list with node ID, address, and status - -#### Actors Distribution - -Inspect named actors distribution across the cluster: - -```bash -pulsing inspect actors --seeds 127.0.0.1:8000 -``` - -Options: -- `--top N`: Show top N actors by instance count -- `--filter STR`: Filter actor names by substring -- `--all_actors True`: Include internal/system actors - -Examples: -```bash -# Show top 10 actors -pulsing inspect actors --seeds 127.0.0.1:8000 --top 10 - -# Filter actors by name -pulsing inspect actors --seeds 127.0.0.1:8000 --filter worker -``` - -#### Metrics - -Inspect Prometheus metrics from cluster nodes: - -```bash +pulsing inspect actors --endpoint 127.0.0.1:8000 --detailed +pulsing inspect actors --seeds 127.0.0.1:8000 --json pulsing inspect metrics --seeds 127.0.0.1:8000 +pulsing inspect watch --seeds 127.0.0.1:8000 --interval 2 ``` -Options: -- `--raw True`: Output raw metrics (default) -- `--raw False`: Show summary only (key metrics) +Use `--timeout` to bound requests and `--best_effort` to continue when a node +is unavailable. `pulsing actor list` has been replaced by `pulsing inspect actors`. -#### Watch Mode - -Watch cluster state changes in real-time: +## Workspace files ```bash -pulsing inspect watch --seeds 127.0.0.1:8000 -``` - -Options: -- `--interval 1.0`: Refresh interval in seconds (default: 1.0) -- `--kind all`: What to watch: `cluster`, `actors`, `metrics`, or `all` (default: `all`) -- `--max_rounds N`: Maximum number of refresh rounds (None = infinite) - -Examples: -```bash -# Watch cluster member changes -pulsing inspect watch --seeds 127.0.0.1:8000 --kind cluster --interval 2.0 - -# Watch actor changes -pulsing inspect watch --seeds 127.0.0.1:8000 --kind actors +pulsing init --template minimal +pulsing checkpoint -m "working state" +pulsing history +pulsing rollback ``` -### Common Options - -All subcommands support: - -- `--timeout 10.0`: Request timeout in seconds (default: 10.0) -- `--best_effort True`: Continue even if some nodes fail (default: False) - -!!! note - Observer mode uses HTTP/2 (h2c) and does NOT join the gossip cluster, making it lightweight and suitable for production monitoring. - ---- - -## Bench - -`pulsing bench` runs load tests against an OpenAI-compatible inference endpoint. - -```bash -pulsing bench gpt2 --url http://localhost:8080 -``` - -!!! note "Optional Extension" - If you see `pulsing._bench module not found`: - - ```bash - maturin develop --manifest-path crates/pulsing-bench-py/Cargo.toml - ``` - ---- - -## Quick Reference - -| Task | Command | -|------|---------| -| Start router | `pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 --name my-llm -- --http_port 8080 --model_name gpt2 --worker_name worker` | -| Start worker | `pulsing actor pulsing.serving.TransformersWorker --addr 0.0.0.0:8001 --seeds 127.0.0.1:8000 --name worker -- --model_name gpt2` | -| Chat completions | `curl -X POST http://localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{"model":"gpt2","messages":[{"role":"user","content":"Hello"}],"stream":false}'` | -| Start multiple workers | `pulsing actor ... --name worker-1 --seeds ... -- --model_name gpt2` | -| Router with custom worker | `pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 -- --worker_name worker-1` | -| List actors | `pulsing inspect actors --endpoint 127.0.0.1:8000` | -| Inspect cluster | `pulsing inspect cluster --seeds 127.0.0.1:8000` | -| Inspect actors | `pulsing inspect actors --seeds 127.0.0.1:8000 --top 10` | -| Inspect metrics | `pulsing inspect metrics --seeds 127.0.0.1:8000` | -| Watch cluster | `pulsing inspect watch --seeds 127.0.0.1:8000` | -| Benchmark | `pulsing bench gpt2 --url http://localhost:8080` | - ---- - -## Next Steps - -- [LLM Inference](../examples/llm_inference.md) - runnable end-to-end tutorial -- [Security](security.md) - mTLS and cluster isolation +The Rust CLI can execute a Python workflow once with `pulsing run [SCRIPT]`. +There are no built-in inference servers, benchmark commands, or agent sessions. diff --git a/docs/src/guide/operations.zh.md b/docs/src/guide/operations.zh.md index 6dd8870fb..f6fc61673 100644 --- a/docs/src/guide/operations.zh.md +++ b/docs/src/guide/operations.zh.md @@ -1,240 +1,39 @@ -# CLI 命令 +# CLI 运维 -Pulsing 内置 CLI 工具,用于启动 actors、检查系统和基准测试分布式服务。 +## 启动 actor ---- - -## 启动 Actor - -`pulsing actor` 通过完整类路径启动 actor。参数以 `--` 分隔,避免 **actor 级选项**(如 `--addr`、`--seeds`、`--name`)与 **Actor 构造参数** 重名。 - -### 参数分隔(`--`) - -- **`--` 之前**:整段原样传给 `actor` 子命令(位置参数:actor 类型 + 任意选项如 `--addr`、`--seeds`、`--name`)。 -- **`--` 之后**:所有 `--key value` 会收集并传给 Actor 的构造函数。用于传入构造参数,避免与 actor 级选项冲突。 - -若不写 `--`,则只会使用 `actor` 子命令能识别的参数;若要同时传 actor 级与构造参数,请使用 `--` 分隔,或通过 `-D actor.extra_kwargs='{"key":"value"}'` 传构造参数。 - -### 格式 - -Actor 类型必须是完整的类路径: -- 格式: `module.path.ClassName` -- 示例: `pulsing.serving.Router` -- 示例: `pulsing.serving.TransformersWorker` -- 示例: `pulsing.serving.VllmWorker` -- 示例: `my_module.my_actor.MyCustomActor` - -### 示例 - -#### Router(OpenAI 兼容 HTTP API) - -```bash -# actor 级(addr、name)在 -- 前;Router 构造参数在 -- 后 -pulsing actor pulsing.serving.Router \ - --addr 0.0.0.0:8000 \ - --name my-llm \ - -- \ - --http_host 0.0.0.0 \ - --http_port 8080 \ - --model_name my-llm \ - --worker_name worker \ - --scheduler_type stream_load -``` - -#### Transformers Worker - -```bash -pulsing actor pulsing.serving.worker.TransformersWorker \ - --addr 0.0.0.0:8001 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model_name gpt2 \ - --device cpu -``` - -#### vLLM Worker - -```bash -pulsing actor pulsing.serving.vllm.VllmWorker \ - --addr 0.0.0.0:8002 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model Qwen/Qwen2 \ - --role aggregated \ - --max_new_tokens 512 -``` - -#### 多个 Worker +指定实现 actor API 的、可导入的用户类: ```bash -# 启动多个不同名称的 worker -pulsing actor pulsing.serving.worker.TransformersWorker \ - --name worker-1 \ - --seeds 127.0.0.1:8000 \ - -- --model_name gpt2 - -pulsing actor pulsing.serving.worker.TransformersWorker \ - --name worker-2 \ - --seeds 127.0.0.1:8000 \ - -- --model_name gpt2 - -# Router 路由到特定 worker 名称 -pulsing actor pulsing.serving.Router \ - --addr 0.0.0.0:8000 \ - --seeds 127.0.0.1:8000 \ - -- --worker_name worker-1 +pulsing actor my_app.Counter --addr 0.0.0.0:8000 --name counter -- --initial 10 ``` -### 通用选项(`--` 之前) - -- `--name NAME`: Actor 名称(默认: "worker") -- `--addr ADDR`: Actor System 绑定地址 -- `--seeds SEEDS`: 逗号分隔的种子节点列表 - -`--` 之后的参数以 `--key value` 形式传入 Actor 构造函数。 - -Actor 类必须: -- 可从指定模块路径导入 -- 继承自 `pulsing.core.Actor` -- 构造函数为命名参数(`--` 后的参数会匹配到构造参数) - -**工作原理**:`--` 之前的整段原样传给 actor 子命令;`--` 之后的每个 `--key value` 会收集并传入 Actor 构造函数。可用 `pulsing actor --help` 查看 actor 级选项;构造参数见各 Actor 类文档。 +`--` 之前的参数配置节点与 actor 注册,之后的参数传给 actor 构造函数。 +通过 `--seeds 127.0.0.1:8000` 加入已有集群。 ---- +## 观察集群 -## Inspect - -`pulsing inspect` 是轻量级 **观察者**工具,通过 HTTP 查询 actor 系统(**无需加入集群**)。它提供多个子命令用于不同的检查需求。 - -### 子命令 - -#### 集群状态 - -检查集群成员及其状态: +Inspect 使用 HTTP 观察者模式,不加入集群。 ```bash pulsing inspect cluster --seeds 127.0.0.1:8000 -``` - -输出包括: -- 总节点数和存活节点数 -- 状态摘要(Alive、Suspect、Failed 等) -- 详细的成员列表,包含节点 ID、地址和状态 - -#### Actor 分布 - -检查命名 actors 在集群中的分布: - -```bash -pulsing inspect actors --seeds 127.0.0.1:8000 -``` - -选项: -- `--endpoint ADDR`: 查询单个节点(例如:`127.0.0.1:8000`) -- `--top N`: 显示实例数最多的前 N 个 actors -- `--filter STR`: 按子字符串过滤 actor 名称 -- `--all_actors True`: 包含内部/系统 actors -- `--json_output True`: JSON 格式输出 -- `--detailed True`: 显示详细信息(类、模块等) - -示例: -```bash -# 查询单个节点 -pulsing inspect actors --endpoint 127.0.0.1:8000 - -# 显示前 10 个 actors -pulsing inspect actors --seeds 127.0.0.1:8000 --top 10 - -# 按名称过滤 actors -pulsing inspect actors --seeds 127.0.0.1:8000 --filter worker - -# 显示详细信息 pulsing inspect actors --endpoint 127.0.0.1:8000 --detailed -``` - -#### 指标 - -检查集群节点的 Prometheus 指标: - -```bash +pulsing inspect actors --seeds 127.0.0.1:8000 --json pulsing inspect metrics --seeds 127.0.0.1:8000 +pulsing inspect watch --seeds 127.0.0.1:8000 --interval 2 ``` -选项: -- `--raw True`: 输出原始指标(默认) -- `--raw False`: 仅显示摘要(关键指标) - -#### 监视模式 - -实时监视集群状态变化: - -```bash -pulsing inspect watch --seeds 127.0.0.1:8000 -``` - -选项: -- `--interval 1.0`: 刷新间隔(秒,默认: 1.0) -- `--kind all`: 监视内容:`cluster`、`actors`、`metrics` 或 `all`(默认: `all`) -- `--max_rounds N`: 最大刷新轮数(None = 无限) - -示例: -```bash -# 监视集群成员变化 -pulsing inspect watch --seeds 127.0.0.1:8000 --kind cluster --interval 2.0 - -# 监视 actor 变化 -pulsing inspect watch --seeds 127.0.0.1:8000 --kind actors -``` - -### 通用选项 - -所有子命令支持: - -- `--timeout 10.0`: 请求超时(秒,默认: 10.0) -- `--best_effort True`: 即使某些节点失败也继续(默认: False) - -!!! note - 观察者模式使用 HTTP/2 (h2c),**不会**加入 gossip 集群,使其轻量级且适合生产环境监控。 +`--timeout` 限制请求时间;`--best_effort` 允许节点不可用时继续。 +`pulsing actor list` 已替换为 `pulsing inspect actors`。 ---- - -## Bench - -`pulsing bench` 对 OpenAI 兼容推理端点进行负载测试。 +## Workspace 文件管理 ```bash -pulsing bench gpt2 --url http://localhost:8080 +pulsing init --template minimal +pulsing checkpoint -m "working state" +pulsing history +pulsing rollback ``` -!!! note "可选扩展" - 若提示 `pulsing._bench module not found`: - - ```bash - maturin develop --manifest-path crates/pulsing-bench-py/Cargo.toml - ``` - ---- - -## 快速参考 - -| 任务 | 命令 | -|------|------| -| 启动 router | `pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 -- --http_port 8080 --model_name my-llm` | -| 启动 worker | `pulsing actor pulsing.serving.TransformersWorker --addr 0.0.0.0:8001 --seeds ... -- --model_name gpt2` | -| 启动多个 worker | `pulsing actor ... --name worker-1 --seeds ... -- --model_name gpt2` | -| Router 指定 worker | `pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 -- --worker_name worker-1` | -| 列出 actors | `pulsing inspect actors --endpoint 127.0.0.1:8000` | -| 检查集群 | `pulsing inspect cluster --seeds 127.0.0.1:8000` | -| 检查 actors | `pulsing inspect actors --seeds 127.0.0.1:8000 --top 10` | -| 检查指标 | `pulsing inspect metrics --seeds 127.0.0.1:8000` | -| 监视集群 | `pulsing inspect watch --seeds 127.0.0.1:8000` | -| 基准测试 | `pulsing bench gpt2 --url http://localhost:8080` | - ---- - -## 下一步 - -- [LLM 推理](../examples/llm_inference.zh.md) — 可运行的端到端教程 -- [安全](security.zh.md) — mTLS 和集群隔离 +Rust CLI 可通过 `pulsing run [SCRIPT]` 执行一次 Python workflow。 +项目不再内置推理服务、benchmark 命令或 agent 交互会话。 diff --git a/docs/src/guide/style.md b/docs/src/guide/style.md index 3d333fe95..dead32232 100644 --- a/docs/src/guide/style.md +++ b/docs/src/guide/style.md @@ -1,71 +1,21 @@ -# Terminology & Style Guide +# Terminology and Style -This page defines terminology and style conventions for Pulsing documentation and code to ensure consistency. +| Symbol | Meaning | +|--------|---------| +| `ActorSystem` | Runtime managing actors and cluster connectivity | +| `Actor` | Message-handling interface | +| `ActorRef` | Low-level reference for messaging | +| `ActorProxy` | Python method-call proxy returned by `@remote` | -## Core Terminology - -| Term | Usage | Description | -|------|-------|-------------| -| `ActorSystem` | Code symbol | Rust/Python class name, use in code references | -| actor system | Conceptual | General description, lowercase | -| `Actor` | Code symbol | Base class name | -| actor | Conceptual | General description | -| `ActorRef` | Code symbol | Low-level actor reference | -| `ActorProxy` | Code symbol | High-level proxy returned by `@remote` decorator | - -## Component Naming - -| Component | CLI Actor Class Path | Description | -|-----------|---------------------|-------------| -| Router | `pulsing.serving.Router` | OpenAI-compatible HTTP router | -| TransformersWorker | `pulsing.serving.TransformersWorker` | Transformers inference worker | -| VllmWorker | `pulsing.serving.VllmWorker` | vLLM inference worker | - -**Note**: When documentation mentions "Router", it typically refers to the HTTP routing component for LLM inference services. Example code requiring task dispatch logic should use names like `Dispatcher` to avoid confusion. - -## CLI Command Format - -### Starting Actors - -Arguments are split by `--`: before `--` go to the actor subcommand (e.g. `--addr`, `--seeds`, `--name`); after `--` are passed to the Actor constructor. +Use user-defined class paths in CLI examples: ```bash -pulsing actor [options] [-- constructor-args] - -# Examples (use -- to separate actor-level options from constructor args) -pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 -- --http_port 8080 --model_name my-llm -pulsing actor pulsing.serving.TransformersWorker --addr 0.0.0.0:8001 -- --model_name gpt2 --device cpu +pulsing actor my_app.Counter --addr 0.0.0.0:8000 --name counter -- --initial 10 +pulsing inspect actors --endpoint 127.0.0.1:8000 ``` -### Inspect Commands (Observer Mode) - -`pulsing inspect` uses a subcommand structure: - -```bash -# Cluster status -pulsing inspect cluster --seeds
- -# Actor distribution -pulsing inspect actors --seeds
[--top N] [--filter ...] -pulsing inspect actors --endpoint
[--detailed] - -# Metrics -pulsing inspect metrics --seeds
[--raw] - -# Live watch -pulsing inspect watch --seeds
[--interval ...] [--kind ...] -``` - -**Removed**: `pulsing actor list` → Use `pulsing inspect actors` instead - -## Code Style - -- **Python**: Follow PEP 8, prefer type annotations -- **Rust**: Use `cargo fmt` and `cargo clippy` -- **Documentation**: Bilingual (`.zh.md` suffix for Chinese) - -## Documentation References +Arguments after `--` belong to the actor constructor. +Inspection is observer-only and does not join the cluster. -- Use backticks for code symbols: `` `ActorSystem` `` -- Use code blocks for commands -- Use backticks for file paths: `` `python/pulsing/actor/` `` +Use backticks for symbols and paths, PEP 8 for Python, `cargo fmt` for Rust, +and `.zh.md` for Chinese documentation. diff --git a/docs/src/guide/style.zh.md b/docs/src/guide/style.zh.md index 2cda8cb2a..3eadbd5c7 100644 --- a/docs/src/guide/style.zh.md +++ b/docs/src/guide/style.zh.md @@ -1,71 +1,19 @@ -# 术语与风格约定 +# 术语与风格 -本页定义 Pulsing 文档和代码中的术语与风格规范,确保一致性。 +| 符号 | 含义 | +|------|------| +| `ActorSystem` | 管理 actor 与集群连接的运行时 | +| `Actor` | 消息处理接口 | +| `ActorRef` | 低层消息引用 | +| `ActorProxy` | `@remote` 返回的 Python 方法调用代理 | -## 核心术语 - -| 术语 | 用法 | 说明 | -|------|------|------| -| `ActorSystem` | 代码符号 | Rust/Python 类名,用于代码引用 | -| actor system | 概念描述 | 一般性描述时使用小写 | -| `Actor` | 代码符号 | 基类名 | -| actor | 概念描述 | 一般性描述 | -| `ActorRef` | 代码符号 | 底层 actor 引用 | -| `ActorProxy` | 代码符号 | `@remote` 装饰器返回的高级代理 | - -## 组件命名 - -| 组件 | CLI actor 类路径 | 说明 | -|------|------------------|------| -| Router | `pulsing.serving.Router` | OpenAI 兼容 HTTP 路由 | -| TransformersWorker | `pulsing.serving.TransformersWorker` | Transformers 推理 Worker | -| VllmWorker | `pulsing.serving.VllmWorker` | vLLM 推理 Worker | - -**注意**:文档中提到"Router"时,通常指 LLM 推理服务的 HTTP 路由组件。示例代码中若需要任务分发逻辑,应使用 `Dispatcher` 等名称以避免混淆。 - -## CLI 命令格式 - -### 启动 Actor - -参数以 `--` 分隔:`--` 前为 actor 子命令选项(如 `--addr`、`--seeds`、`--name`),`--` 后为 Actor 构造参数。 - -```bash -pulsing actor <完整类路径> [选项] [-- 构造参数] - -# 示例(用 -- 区分 actor 级选项与构造参数) -pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 -- --http_port 8080 --model_name my-llm -pulsing actor pulsing.serving.TransformersWorker --addr 0.0.0.0:8001 -- --model_name gpt2 --device cpu -``` - -### 检查命令(观察者模式) - -`pulsing inspect` 使用子命令结构: +CLI 示例使用用户定义的类路径: ```bash -# 集群状态 -pulsing inspect cluster --seeds <地址> - -# Actor 分布 -pulsing inspect actors --seeds <地址> [--top N] [--filter ...] -pulsing inspect actors --endpoint <地址> [--detailed] - -# 指标 -pulsing inspect metrics --seeds <地址> [--raw] - -# 实时监视 -pulsing inspect watch --seeds <地址> [--interval ...] [--kind ...] +pulsing actor my_app.Counter --addr 0.0.0.0:8000 --name counter -- --initial 10 +pulsing inspect actors --endpoint 127.0.0.1:8000 ``` -**已移除**:`pulsing actor list` → 请使用 `pulsing inspect actors` - -## 代码风格 - -- **Python**:遵循 PEP 8,优先使用类型注解 -- **Rust**:使用 `cargo fmt` 和 `cargo clippy` -- **文档**:中英双语(`.zh.md` 为中文版) - -## 文档引用 - -- 代码符号使用反引号:`` `ActorSystem` `` -- 命令使用代码块 -- 文件路径使用反引号:`` `python/pulsing/actor/` `` +`--` 之后的参数属于 actor 构造函数。Inspect 只观察集群,不加入集群。 +符号与路径使用反引号,Python 遵循 PEP 8,Rust 使用 `cargo fmt`, +中文文档使用 `.zh.md` 后缀。 diff --git a/docs/src/index.md b/docs/src/index.md index 2e881f666..da7e1177f 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -51,14 +51,6 @@ A distributed actor runtime built in Rust, designed for Python. Connect AI agent
-- :material-robot:{ .lg .middle } **LLM Inference Services** - - --- - - Scalable inference backends with streaming token generation. OpenAI-compatible API out of the box. - - [:octicons-arrow-right-24: LLM Inference](quickstart/llm_inference.md) - - :material-account-group:{ .lg .middle } **Distributed Agents** --- diff --git a/docs/src/index.zh.md b/docs/src/index.zh.md index fc7b46ece..636fc7c72 100644 --- a/docs/src/index.zh.md +++ b/docs/src/index.zh.md @@ -51,14 +51,6 @@ Actor 运行时。流式优先。零依赖。内置发现。
-- :material-robot:{ .lg .middle } **LLM 推理服务** - - --- - - 可扩展的推理后端,支持流式 token 生成。开箱即用的 OpenAI 兼容 API。 - - [:octicons-arrow-right-24: LLM 推理](quickstart/llm_inference.zh.md) - - :material-account-group:{ .lg .middle } **分布式 Agent** --- diff --git a/docs/src/quickstart/index.md b/docs/src/quickstart/index.md index 4eff8930c..d3adfdad4 100644 --- a/docs/src/quickstart/index.md +++ b/docs/src/quickstart/index.md @@ -130,14 +130,6 @@ asyncio.run(main())
-- :material-robot:{ .lg .middle } **LLM Inference Service** - - --- - - Build a scalable inference backend with streaming and OpenAI-compatible API. - - [:octicons-arrow-right-24: ~10 minutes](llm_inference.md) - - :material-account-group:{ .lg .middle } **Distributed Agents** --- diff --git a/docs/src/quickstart/index.zh.md b/docs/src/quickstart/index.zh.md index 56123092e..0c5f72f68 100644 --- a/docs/src/quickstart/index.zh.md +++ b/docs/src/quickstart/index.zh.md @@ -130,14 +130,6 @@ asyncio.run(main())
-- :material-robot:{ .lg .middle } **LLM 推理服务** - - --- - - 构建支持流式输出和 OpenAI 兼容 API 的可扩展推理后端。 - - [:octicons-arrow-right-24: ~10 分钟](llm_inference.zh.md) - - :material-account-group:{ .lg .middle } **分布式 Agent** --- diff --git a/docs/src/quickstart/llm_inference.md b/docs/src/quickstart/llm_inference.md deleted file mode 100644 index 2e6e66712..000000000 --- a/docs/src/quickstart/llm_inference.md +++ /dev/null @@ -1,174 +0,0 @@ -# Tutorial: LLM Inference Service - -Build a **scalable LLM inference backend** with Pulsing in 10 minutes. - -**Before / After:** - -| | Before (single process or ad‑hoc script) | After (Pulsing) | -|---|------------------------------------------|-----------------| -| **API** | Your own HTTP or in-process only | OpenAI-compatible HTTP API (`/v1/chat/completions`) | -| **Scaling** | One process, one model | Router + N workers; add nodes and workers as needed | -| **Streaming** | Hand-rolled if any | Native streaming from Router to client | - -You get a **Router** (HTTP API + load balancing) and **Workers** (model backends). Same Actor model; add more workers or nodes without changing client code. - -**What you'll build:** - -- A Router that exposes an **OpenAI-compatible HTTP API** -- One or more Workers that host model replicas -- Streaming token generation - -``` -┌─────────────┐ ┌─────────────┐ ┌─────────────┐ -│ Client │────▶│ Router │────▶│ Worker │ -│ (curl/SDK) │ │ :8080 HTTP │ │ (gpt2/vLLM)│ -└─────────────┘ └──────┬──────┘ └─────────────┘ - │ - ▼ - ┌─────────────┐ - │ Worker │ - │ (replica) │ - └─────────────┘ -``` - ---- - -## Prerequisites - -```bash -pip install pulsing -``` - -Choose a backend: - -| Backend | Install | Best for | -|---------|---------|----------| -| **Transformers** | `pip install torch transformers` | Quick testing, CPU | -| **vLLM** | `pip install vllm` | Production, GPU | - ---- - -## Step 1: Start the Router - -Open **Terminal A**: - -```bash -pulsing actor pulsing.serving.Router \ - --addr 0.0.0.0:8000 \ - -- \ - --http_port 8080 \ - --model_name my-llm -``` - -| Flag | Description | -|------|-------------| -| `--addr` (before `--`) | Actor system address (workers join here) | -| `--http_port`, `--model_name` (after `--`) | Router constructor: HTTP port, model name in API responses | - ---- - -## Step 2: Start a Worker - -Open **Terminal B**: - -=== "Transformers (CPU)" - - ```bash - pulsing actor pulsing.serving.TransformersWorker \ - --addr 0.0.0.0:8001 \ - --seeds 127.0.0.1:8000 \ - -- \ - --model_name gpt2 \ - --device cpu - ``` - -=== "vLLM (GPU)" - - ```bash - pulsing actor pulsing.serving.VllmWorker \ - --addr 0.0.0.0:8002 \ - --seeds 127.0.0.1:8000 \ - -- \ - --model Qwen/Qwen2.5-0.5B - ``` - -| Flag | Description | -|------|-------------| -| `--addr`, `--seeds` (before `--`) | Actor-level: bind address, seed nodes | -| `--model` / `--model_name` (after `--`) | Constructor: model name/path | - ---- - -## Step 3: Verify the Cluster - -```bash -# List actors -pulsing inspect actors --endpoint 127.0.0.1:8000 - -# Inspect cluster state -pulsing inspect cluster --seeds 127.0.0.1:8000 -``` - -You should see the `router` and `worker` actors. - ---- - -## Step 4: Make Requests - -### Non-streaming - -```bash -curl -s http://localhost:8080/v1/chat/completions \ - -H "Content-Type: application/json" \ - -d '{ - "model": "my-llm", - "messages": [{"role": "user", "content": "Hello"}], - "stream": false - }' -``` - -### Streaming (SSE) - -```bash -curl -N http://localhost:8080/v1/chat/completions \ - -H "Content-Type: application/json" \ - -d '{ - "model": "my-llm", - "messages": [{"role": "user", "content": "Tell me a joke"}], - "stream": true - }' -``` - ---- - -## Scaling Out - -Add more workers to handle more load: - -```bash -# Terminal C -pulsing actor pulsing.serving.TransformersWorker --addr 0.0.0.0:8003 --seeds 127.0.0.1:8000 -- --model_name gpt2 - -# Terminal D -pulsing actor pulsing.serving.TransformersWorker --addr 0.0.0.0:8004 --seeds 127.0.0.1:8000 -- --model_name gpt2 -``` - -The Router automatically load-balances across all workers. - ---- - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| `No available workers` | Router looks for actors named `worker` by default. (1) Start workers with `--name worker` (before `--`). (2) Or start Router with `--worker_name ` (after `--`) to match. (3) Workers must use `--seeds `. Check: `pulsing inspect actors --seeds 127.0.0.1:8000` and ensure a `worker` (or your custom name) appears. | -| Connection refused | Check router started with `--addr` | -| Slow startup | First request loads model weights | - ---- - -## What's Next? - -- [Guide: Operations](../guide/operations.md) — CLI tools in depth -- [Guide: Security](../guide/security.md) — secure your cluster with mTLS -- [Design: Load Sync](../design/load_sync.md) — how load balancing works diff --git a/docs/src/quickstart/llm_inference.zh.md b/docs/src/quickstart/llm_inference.zh.md deleted file mode 100644 index 2d4651602..000000000 --- a/docs/src/quickstart/llm_inference.zh.md +++ /dev/null @@ -1,169 +0,0 @@ -# 教程:LLM 推理服务 - -10 分钟内用 Pulsing 构建一个**可扩展的 LLM 推理后端**。 - -**前后对比:** - -| | 之前(单进程或临时脚本) | 之后(Pulsing) | -|---|--------------------------|-----------------| -| **API** | 自建 HTTP 或仅进程内 | OpenAI 兼容 HTTP API(`/v1/chat/completions`) | -| **扩展** | 单进程、单模型 | Router + N 个 Worker;按需增加节点与 Worker | -| **流式** | 若有则手写 | Router 到客户端的原生流式 | - -你会得到一个 **Router**(HTTP API + 负载均衡)和若干 **Worker**(模型后端)。同一套 Actor 模型;增加 Worker 或节点无需改客户端代码。 - -**你将构建:** - -- 一个暴露 **OpenAI 兼容 HTTP API** 的 Router -- 一个或多个托管模型副本的 Worker -- 流式 token 生成 - -``` -┌─────────────┐ ┌─────────────┐ ┌─────────────┐ -│ 客户端 │────▶│ Router │────▶│ Worker │ -│ (curl/SDK) │ │ :8080 HTTP │ │ (gpt2/vLLM)│ -└─────────────┘ └──────┬──────┘ └─────────────┘ - │ - ▼ - ┌─────────────┐ - │ Worker │ - │ (副本) │ - └─────────────┘ -``` - ---- - -## 前置条件 - -```bash -pip install pulsing -``` - -选择后端: - -| 后端 | 安装 | 适用场景 | -|------|------|----------| -| **Transformers** | `pip install torch transformers` | 快速测试,CPU | -| **vLLM** | `pip install vllm` | 生产环境,GPU | - ---- - -## 步骤 1:启动 Router - -打开**终端 A**: - -```bash -pulsing actor pulsing.serving.Router \ - --addr 0.0.0.0:8000 \ - --name my-llm \ - -- \ - --http_port 8080 \ - --model_name gpt2 \ - --worker_name worker -``` - -| 参数 | 说明 | -|------|------| -| `--addr`、`--name`(`--` 前) | Actor 系统地址、Router 名称 | -| `--http_port`、`--model_name`、`--worker_name`(`--` 后) | Router 构造参数:HTTP 端口、API 模型名、目标 worker 名 | - ---- - -## 步骤 2:启动 Worker - -打开**终端 B**: - -=== "Transformers (CPU)" - - ```bash - pulsing actor pulsing.serving.TransformersWorker \ - --addr 0.0.0.0:8001 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model_name gpt2 - ``` - -=== "vLLM (GPU)" - - ```bash - pulsing actor pulsing.serving.VllmWorker \ - --addr 0.0.0.0:8002 \ - --seeds 127.0.0.1:8000 \ - --name worker \ - -- \ - --model Qwen/Qwen2.5-0.5B - ``` - -| 参数 | 说明 | -|------|------| -| `--addr`、`--seeds`(`--` 前) | actor 级:绑定地址、种子节点 | -| `--model` / `--model_name`(`--` 后) | 构造参数:模型名称/路径 | - ---- - -## 步骤 3:验证集群 - -```bash -# 列出 actor -pulsing inspect actors --endpoint 127.0.0.1:8000 - -# 检查集群状态 -pulsing inspect cluster --seeds 127.0.0.1:8000 -``` - -你应该能看到 `router` 和 `worker` actor。 - ---- - -## 步骤 4:发送请求 - -### 非流式 - -```bash -curl -X POST http://localhost:8080/v1/chat/completions \ - -H "Content-Type: application/json" \ - -d '{"model": "gpt2", "messages": [{"role": "user", "content": "Hello"}], "stream": false}' -``` - -### 流式 (SSE) - -```bash -curl -X POST http://localhost:8080/v1/chat/completions \ - -H "Content-Type: application/json" \ - -d '{"model": "gpt2", "messages": [{"role": "user", "content": "讲个笑话"}], "stream": true}' -``` - ---- - -## 扩展 - -添加更多 Worker 处理更大负载: - -```bash -# 终端 C -pulsing actor pulsing.serving.TransformersWorker --addr 0.0.0.0:8003 --seeds 127.0.0.1:8000 -- --model_name gpt2 - -# 终端 D -pulsing actor pulsing.serving.TransformersWorker --addr 0.0.0.0:8004 --seeds 127.0.0.1:8000 -- --model_name gpt2 -``` - -Router 会自动在所有 Worker 间负载均衡。 - ---- - -## 故障排查 - -| 问题 | 解决方案 | -|------|----------| -| `No available workers` | Router 默认按名字 `worker` 查找。需 (1) Worker 用 `--name worker`(在 `--` 前)启动,或 (2) Router 用 `--worker_name <名字>`(在 `--` 后)与 Worker 一致;(3) Worker 必须 `--seeds `。可执行 `pulsing inspect actors --seeds 127.0.0.1:8000` 确认是否有名为 `worker` 的 actor。 | -| 连接被拒绝 | 检查 Router 是否以 `--addr` 启动 | -| 启动慢 | 首次请求需要加载模型权重 | - ---- - -## 下一步 - -- [指南:运维操作](../guide/operations.zh.md) — 深入 CLI 工具 -- [指南:安全](../guide/security.zh.md) — 用 mTLS 保护集群 -- [设计:负载同步](../design/load_sync.md) — 负载均衡原理 diff --git a/docs/src/quickstart/migrate_from_ray.md b/docs/src/quickstart/migrate_from_ray.md index 2911a3a12..489923fbf 100644 --- a/docs/src/quickstart/migrate_from_ray.md +++ b/docs/src/quickstart/migrate_from_ray.md @@ -151,4 +151,3 @@ result = await worker.process("hello") - [Guide: Actors](../guide/actors.md) — understand the Actor model - [Guide: Remote Actors](../guide/remote_actors.md) — cluster setup -- [Tutorial: LLM Inference](llm_inference.md) — build an inference service diff --git a/docs/src/quickstart/migrate_from_ray.zh.md b/docs/src/quickstart/migrate_from_ray.zh.md index 1eec423fb..0119dec75 100644 --- a/docs/src/quickstart/migrate_from_ray.zh.md +++ b/docs/src/quickstart/migrate_from_ray.zh.md @@ -151,4 +151,3 @@ result = await worker.process("hello") - [指南:Actor](../guide/actors.zh.md) — 理解 Actor 模型 - [指南:远程 Actor](../guide/remote_actors.zh.md) — 集群设置 -- [教程:LLM 推理](llm_inference.zh.md) — 构建推理服务 diff --git a/examples/README.md b/examples/README.md index 753b0ed0c..c5c9bc11e 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,175 +1,33 @@ # Pulsing 示例 -## 🚀 从这里开始 +示例聚焦 actor 通信、发现、生命周期和传输。 ```bash -# 安装 pip install pulsing - -# 第一个示例(30秒) -python examples/quickstart/hello_agent.py -``` - -## 📚 示例导航 - -### ⭐ 快速入门 (`quickstart/`) - -| 示例 | 说明 | 难度 | -|------|------|------| -| `hello_agent.py` | 第一个 Multi-Agent 应用 | ⭐ | -| `ai_chat_room.py` | 4个 AI 讨论话题 | ⭐ | - -```bash python examples/quickstart/hello_agent.py -python examples/quickstart/ai_chat_room.py --topic "AI 会取代人类吗?" -``` - -### ⭐⭐ Multi-Agent 应用 (`agent/pulsing/`) - -| 示例 | 说明 | 特点 | -|------|------|------| -| `mbti_discussion.py` | MBTI 人格讨论投票 | 角色扮演、辩论、投票 | -| `parallel_ideas_async.py` | 并行创意生成 | 竞争提交、截止时间 | - -```bash -# MBTI 讨论(推荐!) -python examples/agent/pulsing/mbti_discussion.py --mock --group-size 6 --rounds 2 - -# 并行创意 -python examples/agent/pulsing/parallel_ideas_async.py --mock --n-ideas 5 --timeout 30 -``` - -### ⭐⭐ 框架集成 (`agent/autogen/`, `agent/langgraph/`) - -| 框架 | 示例 | 说明 | -|------|------|------| -| AutoGen | `agent/autogen/simple.py` | 单进程 | -| AutoGen | `agent/autogen/distributed.py` | 分布式 | -| LangGraph | `agent/langgraph/simple.py` | 单进程 | -| LangGraph | `agent/langgraph/distributed.py` | 分布式 | - -```bash -# AutoGen -cd examples/agent/autogen && ./run_distributed.sh - -# LangGraph -cd examples/agent/langgraph && ./run_distributed.sh -``` - -### ⭐⭐ Actor 基础 (`python/`) - -| 示例 | 说明 | -|------|------| -| `ping_pong.py` | Actor 基础通信 | -| `message_patterns.py` | RPC、流式消息 | -| `named_actors.py` | 服务发现 | -| `cluster.py` | 集群通信 | -| `remote_actor_example.py` | @remote 装饰器 | -| `tensor_message_fast_path.py` | TensorMessage raw TCP 快速传输与 HTTP/2 兼容路径 | -| `subprocess_example.py` | `subprocess` 兼容 API | - -```bash -python examples/python/ping_pong.py -python examples/python/cluster.py --port 8000 -python examples/python/tensor_message_fast_path.py -python examples/python/subprocess_example.py -USE_POLSING_SUBPROCESS=1 python examples/python/subprocess_example.py --resources -``` - -### ⭐⭐ CLI 工具 (`inspect/`) - -| 示例 | 说明 | -|------|------| -| `demo.sh` | 完整演示脚本(推荐) | -| `start_demo.sh` | 仅启动服务脚本 | -| `demo_service.py` | 多节点演示服务 | -| `README.md` | Inspect CLI 使用指南 | - -**一键运行完整演示:** - -```bash -./examples/inspect/demo.sh -``` - -这个脚本会自动: -- 启动 3 个节点 -- 运行所有 inspect 子命令 -- 展示各种用法和输出 -- 按 Ctrl+C 自动清理 - -**或手动启动服务:** - -```bash -# 启动服务(3个终端) -python examples/inspect/demo_service.py --port 8000 -python examples/inspect/demo_service.py --port 8001 --seed 127.0.0.1:8000 -python examples/inspect/demo_service.py --port 8002 --seed 127.0.0.1:8000 - -# 使用 inspect 查看集群状态 -pulsing inspect cluster --seeds 127.0.0.1:8000 -pulsing inspect actors --seeds 127.0.0.1:8000 -pulsing inspect metrics --seeds 127.0.0.1:8000 -pulsing inspect watch --seeds 127.0.0.1:8000 ``` -### ⭐⭐⭐ Rust 示例 (`rust/`) - -| 示例 | 说明 | +| 路径 | 内容 | |------|------| -| `ping_pong.rs` | 基础通信 | -| `behavior_counter.rs` | Behavior API | -| `behavior_fsm.rs` | 状态机 | -| `cluster.rs` | 集群 | +| `quickstart/hello_agent.py` | 两个 actor 互相调用 | +| `quickstart/ai_chat_room.py` | 使用本地文本模板的多 actor 协作,无模型依赖 | +| `quickstart/function_to_fleet.py` | 多 worker 任务分发 | +| `python/ping_pong.py` | 基础通信 | +| `python/message_patterns.py` | RPC 与流式消息 | +| `python/named_actors.py` | 服务发现 | +| `python/cluster.py` | 多节点集群 | +| `python/tensor_message_fast_path.py` | 连续 CPU buffer 传输 | +| `python/subprocess_example.py` | 子进程兼容 API | +| `python/isolated_actor_spawn.py` | 隔离子进程 actor | +| `agent/pulsing/runtime_lifecycle_example.py` | 生命周期管理 | +| `agent/autogen/` | 可选 AutoGen 集成 | +| `agent/langgraph/` | 可选 LangGraph 集成 | +| `inspect/` | CLI 集群观察 | +| `rust/` | Rust actor 与 Behavior API | + +Rust 示例: ```bash cargo run --example ping_pong -p pulsing-actor cargo run --example behavior_counter -p pulsing-actor -cargo run --example behavior_fsm -p pulsing-actor -``` - -## 🎯 我想做... - -| 场景 | 推荐示例 | -|------|----------| -| 先跑起来看看 | `quickstart/hello_agent.py` | -| 多 Agent 对话 | `quickstart/ai_chat_room.py` | -| AI 辩论/讨论 | `agent/pulsing/mbti_discussion.py` | -| 并行任务竞争 | `agent/pulsing/parallel_ideas_async.py` | -| 集群部署 | `python/cluster.py` | -| 传输连续 CPU Tensor | `python/tensor_message_fast_path.py` | -| 子进程资源调度 | `python/subprocess_example.py` | -| 学习 CLI 工具 | `inspect/demo_service.py` | -| 接入 AutoGen | `agent/autogen/` | -| 接入 LangGraph | `agent/langgraph/` | -| 学习 Rust API | `rust/behavior_*.rs` | - -## 💡 小贴士 - -### 模拟模式 vs LLM 模式 - -大多数示例支持 `--mock` 参数: - -```bash -# 模拟模式(无需 API Key,快速体验) -python examples/agent/pulsing/mbti_discussion.py --mock - -# LLM 模式(需要 API Key) -export OPENAI_API_KEY=your_key -python examples/agent/pulsing/mbti_discussion.py --topic "AI 的未来" -``` - -### 分布式模式 - -```python -# 单机(默认) -async with runtime(): - ... - -# 分布式 -async with runtime(addr="0.0.0.0:8001"): - ... - -# 加入集群 -async with runtime(addr="0.0.0.0:8002", seeds=["node1:8001"]): - ... ``` diff --git a/examples/agent/pulsing/README.md b/examples/agent/pulsing/README.md index 7da223786..058f7a00f 100644 --- a/examples/agent/pulsing/README.md +++ b/examples/agent/pulsing/README.md @@ -1,148 +1,8 @@ -# Pulsing Multi-Agent 示例 - -本目录包含使用 Pulsing Actor 框架实现的多智能体示例。 - -## 核心 API - -```python -import pulsing as pul -from pulsing.agent import agent, runtime, llm, parse_json, get_agent_meta - -# @pul.remote: 基础 Actor 装饰器 -@pul.remote -class MyActor: - async def work(self): ... - -# @agent: 带元信息的 Actor(用于可视化/调试) -@agent(role="研究员", goal="分析问题") -class Researcher: - async def analyze(self, topic: str): ... - -# 运行 -async with runtime(): - actor = await MyActor.spawn(name="actor") - result = await actor.work() - - # 通过名称获取其他 Actor - peer = await MyActor.resolve("actor") -``` - -## 示例列表 - -### 1. MBTI 人格讨论 (`mbti_discussion.py`) - -基于 MBTI 人格类型的多智能体讨论与投票,演示 `@pul.remote` 与 `@agent` 的区别。 - -``` - ┌─────────────────────────────────────┐ - │ ModeratorActor │ - │ (使用 @pul.remote,协调流程) │ - └──────────────┬──────────────────────┘ - │ resolve() - ┌───────────────────┼───────────────────────┐ - ▼ ▼ ▼ -┌────────┐ ┌────────┐ ┌────────┐ -│ INTJ │ ←────→ │ ENFP │ ←────→ │ ISFJ │ -│ Agent │ 辩论 │ Agent │ 辩论 │ Agent │ -│(@agent)│ │(@agent)│ │(@agent)│ -└────────┘ └────────┘ └────────┘ -``` - -**特点:** -- `ModeratorActor` 使用 `@pul.remote`(普通 Actor) -- `MBTIAgent` 使用 `@agent`(附带元信息) -- 可通过 `get_agent_meta()` 和 `list_agents()` 获取元信息 +# Actor 生命周期 ```bash -# 模拟模式 -python mbti_discussion.py --mock --group-size 6 --rounds 2 - -# LLM 模式 -export OPENAI_API_KEY=xxx -python mbti_discussion.py --topic "AI是否应该有情感" -``` - -### 2. 并行创意生成 (`parallel_ideas_async.py`) - -多个 Agent 并行生成方案,竞争提交给 Judge。 - -``` - ┌───────────┐ ┌───────────┐ ┌───────────┐ - │ IdeaAgent │ ←──→ │ IdeaAgent │ ←──→ │ IdeaAgent │ - │ (性能) │ 协作 │ (安全) │ 协作 │ (产品) │ - └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ - │ │ │ - └──────────────────┼──────────────────┘ - ▼ submit() - ┌───────────┐ - │ Judge │ - │ (截止时间) │ - └───────────┘ +python examples/agent/pulsing/runtime_lifecycle_example.py ``` -**特点:** -- 完全异步并行执行 -- Agent 间可通过 `ClassName.resolve()` 协作 -- 竞争性提交 + 截止时间机制 - -```bash -# 模拟模式 -python parallel_ideas_async.py --mock --n-ideas 5 --timeout 30 - -# LLM 模式 -export OPENAI_API_KEY=xxx -python parallel_ideas_async.py --question "如何提升 API 吞吐?" -``` - -## 安装 - -```bash -cd Pulsing -pip install -e . - -# 使用 LLM 模式需要 -pip install langchain-openai -``` - -## `@pul.remote` vs `@agent` - -| 特性 | `@pul.remote` | `@agent` | -|------|---------------|----------| -| 功能 | Actor 化 | Actor 化 + 元信息 | -| 用途 | 通用 | 需要可视化/调试时 | -| 元信息 | 无 | `role`, `goal`, `backstory`, `tags` | -| 性能开销 | 无 | 几乎无 | - -```python -# @pul.remote: 直接使用 -@pul.remote -class Worker: - async def work(self): ... - -# @agent: 附加元信息 -@agent(role="分析师", goal="深入分析", domain="AI") -class Analyst: - async def analyze(self): ... - -# 获取元信息 -meta = get_agent_meta("analyst") -print(meta.role) # "分析师" -print(meta.tags) # {"domain": "AI"} - -# 列出所有 Agent -for name, meta in list_agents().items(): - print(f"{name}: {meta.role}") -``` - -## 分布式部署 - -```python -# 节点 A -async with runtime(addr="0.0.0.0:8001"): - await JudgeActor.spawn(name="judge") - -# 节点 B(自动发现节点 A) -async with runtime(addr="0.0.0.0:8002", seeds=["node_a:8001"]): - judge = await JudgeActor.resolve("judge") # 跨节点透明调用 - await judge.submit(idea) -``` +演示 `pulsing.agent.runtime` 与 actor 元信息清理。 +LLM 客户端及 coding-agent 示例不再包含在本目录中。 diff --git a/examples/agent/pulsing/mbti_discussion.py b/examples/agent/pulsing/mbti_discussion.py deleted file mode 100644 index ae2af3b83..000000000 --- a/examples/agent/pulsing/mbti_discussion.py +++ /dev/null @@ -1,467 +0,0 @@ -""" -Multi-Agent Discussion and Voting Example Based on MBTI Personality Types - -This example uses `@pul.remote` for all actors. - -Usage: - python mbti_discussion.py --mock --topic "Remote work vs On-site work" - python mbti_discussion.py --topic "Should AI have emotions" --group-size 8 -""" - -from __future__ import annotations - -import argparse -import asyncio -import random -from collections import Counter - -import pulsing as pul -from pulsing.agent import llm, parse_json - -# ============================================================================ -# MBTI Personality Configuration -# ============================================================================ - -MBTI_TYPES = { - "INTJ": { - "name": "Architect", - "traits": "Strategic thinking, independent, efficiency-oriented", - "persuade_rate": 0.1, - "population": 2.1, - }, - "INTP": { - "name": "Logician", - "traits": "Analytical, innovative, truth-seeking", - "persuade_rate": 0.15, - "population": 3.3, - }, - "ENTJ": { - "name": "Commander", - "traits": "Decisive, leadership, efficient execution", - "persuade_rate": 0.1, - "population": 1.8, - }, - "ENTP": { - "name": "Debater", - "traits": "Argumentative, innovative, challenges tradition", - "persuade_rate": 0.2, - "population": 3.2, - }, - "INFJ": { - "name": "Advocate", - "traits": "Idealistic, insightful, meaning-focused", - "persuade_rate": 0.25, - "population": 1.5, - }, - "INFP": { - "name": "Mediator", - "traits": "Idealistic, empathetic, harmony-seeking", - "persuade_rate": 0.3, - "population": 4.4, - }, - "ENFJ": { - "name": "Protagonist", - "traits": "Charismatic, empathetic, inspiring", - "persuade_rate": 0.35, - "population": 2.5, - }, - "ENFP": { - "name": "Campaigner", - "traits": "Enthusiastic, creative, communicative", - "persuade_rate": 0.3, - "population": 8.1, - }, - "ISTJ": { - "name": "Logistician", - "traits": "Practical, reliable, detail-oriented", - "persuade_rate": 0.1, - "population": 11.6, - }, - "ISFJ": { - "name": "Defender", - "traits": "Caring, responsible, tradition-focused", - "persuade_rate": 0.2, - "population": 13.8, - }, - "ESTJ": { - "name": "Executive", - "traits": "Organized, practical, decisive", - "persuade_rate": 0.1, - "population": 8.7, - }, - "ESFJ": { - "name": "Consul", - "traits": "Caring, cooperative, harmony-focused", - "persuade_rate": 0.25, - "population": 12.3, - }, - "ISTP": { - "name": "Virtuoso", - "traits": "Calm, analytical, hands-on", - "persuade_rate": 0.15, - "population": 5.4, - }, - "ISFP": { - "name": "Adventurer", - "traits": "Flexible, sensitive, aesthetic-seeking", - "persuade_rate": 0.25, - "population": 8.8, - }, - "ESTP": { - "name": "Entrepreneur", - "traits": "Action-oriented, flexible, adaptable", - "persuade_rate": 0.2, - "population": 4.3, - }, - "ESFP": { - "name": "Entertainer", - "traits": "Energetic, optimistic, social", - "persuade_rate": 0.25, - "population": 8.5, - }, -} - -PERSUASION_MESSAGES = { - "INTJ": "From a long-term strategic perspective, this is a better choice", - "INTP": "From a logical analysis, there's a flaw in your argument", - "ENTJ": "We need decisive action, hesitation will miss opportunities", - "ENTP": "Let's think about this from another angle", - "INFJ": "Considering the long-term impact on society, we should reconsider", - "INFP": "If we look at it from others' perspectives, we might understand differently", - "ENFJ": "For the team's common goal, I suggest we find consensus", - "ENFP": "Imagine how many possibilities there would be if we did this!", - "ISTJ": "Based on past experience and data, this is a more reliable choice", - "ISFJ": "Considering the impact on everyone, I think we need to be cautious", - "ESTJ": "To improve efficiency, we need clear plans and execution", - "ESFJ": "To maintain team harmony, perhaps we can both compromise", - "ISTP": "From a technical feasibility perspective, this is the most practical solution", - "ISFP": "Everyone's feelings matter, but results are equally important", - "ESTP": "Rather than hesitating, let's try it and see the results", - "ESFP": "I think this choice would be more interesting and effective!", -} - - -def sample_mbti_group(size: int) -> list[str]: - types = list(MBTI_TYPES.keys()) - weights = [MBTI_TYPES[t]["population"] for t in types] - return random.choices(types, weights=weights, k=size) - - -# ============================================================================ -# Moderator Actor -# ============================================================================ - - -@pul.remote -class ModeratorActor: - """Moderator Actor: Coordinates the entire discussion process.""" - - def __init__(self, topic: str, rounds: int, debate_time: float, mock: bool): - self.topic = topic - self.rounds = rounds - self.debate_time = debate_time - self.mock = mock - self.agents: list[dict] = [] - self.opinions: list[dict] = [] - self.debates: list[dict] = [] - self.votes: dict[str, list[str]] = {} - - async def register_agent(self, name: str, mbti: str) -> dict: - self.agents.append({"name": name, "mbti": mbti}) - return {"status": "registered"} - - async def submit_opinion( - self, name: str, mbti: str, stance: str, argument: str - ) -> dict: - self.opinions.append( - {"name": name, "mbti": mbti, "stance": stance, "argument": argument} - ) - print(f" [{mbti}] 📝 {stance}") - print(f" └─ {argument}") - return {"received": True} - - async def submit_vote(self, mbti: str, vote: str) -> dict: - print(f" [{mbti}] 🗳️ {vote}") - if vote not in self.votes: - self.votes[vote] = [] - self.votes[vote].append(mbti) - return {"received": True} - - async def start_discussion(self) -> dict: - for r in range(self.rounds): - print(f"\n{'=' * 60}") - print(f"Round {r + 1}: Express Opinions") - print(f"{'=' * 60}") - - for agent_info in self.agents: - proxy = await MBTIAgent.resolve(agent_info["name"]) - await proxy.form_opinion(self.opinions[-10:]) - - print(f"\n{'=' * 60}") - print(f"Round {r + 1}: Free Debate ({self.debate_time}s)") - print(f"{'=' * 60}") - - for agent_info in self.agents: - my_opinion = next( - (o for o in self.opinions if o["name"] == agent_info["name"]), None - ) - if not my_opinion: - continue - - opponents = [ - o - for o in self.opinions - if o["stance"] != my_opinion["stance"] - and o["name"] != agent_info["name"] - ] - if not opponents: - opponents = [ - o for o in self.opinions if o["name"] != agent_info["name"] - ] - if not opponents: - continue - - target = random.choice(opponents) - proxy = await MBTIAgent.resolve(agent_info["name"]) - result = await proxy.debate(target) - - if result.get("success"): - self.debates.append(result) - icon = "✅" if result["changed"] else "❌" - print( - f" [{result['from']}] 💬 → [{result['to']}]: {result['message'][:40]}..." - ) - print(f" └─ {icon} [{result['to']}]: {result['reply']}") - - print(f"\n{'=' * 60}") - print("Final Voting") - print(f"{'=' * 60}") - - for agent_info in self.agents: - proxy = await MBTIAgent.resolve(agent_info["name"]) - await proxy.vote() - - return self._summarize() - - def _summarize(self) -> dict: - print(f"\n{'=' * 60}") - print("Voting Results") - print(f"{'=' * 60}") - - total = sum(len(v) for v in self.votes.values()) - sorted_votes = sorted(self.votes.items(), key=lambda x: len(x[1]), reverse=True) - - for stance, voters in sorted_votes: - pct = len(voters) / total * 100 if total > 0 else 0 - bar = "█" * int(pct / 5) + "░" * (20 - int(pct / 5)) - print(f" {stance:10} {bar} {len(voters)} votes ({pct:.0f}%)") - print(f" └─ {', '.join(voters)}") - - winner = sorted_votes[0][0] if sorted_votes else "None" - success = sum(1 for d in self.debates if d.get("changed")) - - print( - f"\nDebate Statistics: {len(self.debates)} exchanges, {success} successful persuasions" - ) - print(f"\n{'=' * 60}") - print(f"Final Result: {winner} wins") - print(f"{'=' * 60}") - - return {"winner": winner, "votes": self.votes, "debates": len(self.debates)} - - -# ============================================================================ -# MBTI Agent -# ============================================================================ - - -@pul.remote -class MBTIAgent: - """MBTI Agent: Autonomous actor participating in discussion.""" - - def __init__( - self, agent_name: str, mbti: str, topic: str, moderator: str, mock: bool - ): - self.name = agent_name - self.mbti = mbti - self.info = MBTI_TYPES[mbti] - self.topic = topic - self.moderator_name = moderator - self.mock = mock - self.stance: str = "" - self.argument: str = "" - - async def form_opinion(self, others: list[dict]) -> dict: - if self.mock: - await asyncio.sleep(random.uniform(0.05, 0.15)) - if self.mbti in ["INTJ", "INTP", "ENTJ", "ENTP"]: - stance = random.choice(["Support", "Oppose"]) - elif self.mbti in ["INFJ", "INFP", "ENFJ", "ENFP"]: - stance = random.choice(["Support", "Conditional Support", "Neutral"]) - else: - stance = random.choice(["Neutral", "Conditional Support", "Oppose"]) - - args = { - "Support": f"As {self.info['name']}, I think this helps improve efficiency and innovation", - "Oppose": f"As {self.info['name']}, I'm concerned this will bring uncontrollable risks", - "Neutral": f"As {self.info['name']}, I think we need more information to make a judgment", - "Conditional Support": f"As {self.info['name']}, I support but need clear boundaries", - } - self.stance = stance - self.argument = args.get(stance, "Needs discussion") - else: - client = await llm(temperature=0.8) - ctx = ( - "\n".join([f"- {o['mbti']}: {o['stance']}" for o in others[-5:]]) - if others - else "None" - ) - prompt = f"""You are {self.mbti} ({self.info["name"]}), personality traits: {self.info["traits"]}. -Topic: {self.topic} -Others' views: -{ctx} -Please express your view on the topic based on your personality traits. Output JSON: {{"stance": "Support/Oppose/Neutral/Conditional Support", "argument": "Argument based on topic (within 40 characters)"}}""" - resp = await client.ainvoke(prompt) - data = parse_json(resp.content, {}) - self.stance = data.get("stance", "Neutral") - self.argument = data.get("argument", "Needs discussion") - - moderator = await ModeratorActor.resolve(self.moderator_name) - await moderator.submit_opinion(self.name, self.mbti, self.stance, self.argument) - return {"mbti": self.mbti, "stance": self.stance} - - async def debate(self, target: dict) -> dict: - target_mbti = target["mbti"] - target_stance = target["stance"] - - if self.mock: - await asyncio.sleep(random.uniform(0.1, 0.3)) - message = PERSUASION_MESSAGES.get(self.mbti, "Please consider my view") - target_rate = MBTI_TYPES[target_mbti]["persuade_rate"] - changed = random.random() < target_rate - if changed: - reply = random.choice( - [ - "That makes sense, I agree", - "You convinced me", - "OK, I changed my mind", - ] - ) - else: - reply = random.choice( - ["I disagree", "Insufficient evidence", "I stand firm"] - ) - else: - client = await llm(temperature=0.8) - prompt1 = f"""You are {self.mbti}, the topic is "{self.topic}", your stance is {self.stance}. -The other party {target_mbti}'s stance is {target_stance}. Persuade them in one sentence. Output JSON: {{"message": "Persuasion message (within 30 characters)"}}""" - resp1 = await client.ainvoke(prompt1) - message = parse_json(resp1.content, {}).get( - "message", "Please consider my view" - ) - - target_info = MBTI_TYPES[target_mbti] - prompt2 = f"""You are {target_mbti} ({target_info["name"]}), {self.mbti} says: "{message}". -Based on your personality traits ({target_info["traits"]}), would you be persuaded? Output JSON: {{"changed": true/false, "reply": "Reply (within 10 characters)"}}""" - resp2 = await client.ainvoke(prompt2) - data = parse_json(resp2.content, {}) - changed = data.get("changed", False) - reply = data.get("reply", "I stand firm") - - return { - "success": True, - "from": self.mbti, - "to": target_mbti, - "message": message, - "reply": reply, - "changed": changed, - } - - async def vote(self) -> dict: - if self.mock: - await asyncio.sleep(random.uniform(0.02, 0.05)) - moderator = await ModeratorActor.resolve(self.moderator_name) - await moderator.submit_vote(self.mbti, self.stance or "Abstain") - return {"mbti": self.mbti, "vote": self.stance} - - -# ============================================================================ -# Main Flow -# ============================================================================ - - -async def run( - topic: str, - group_size: int = 6, - rounds: int = 2, - debate_time: float = 5.0, - mock: bool = False, -): - print("=" * 60) - print("MBTI Personality Type Discussion and Voting") - print("=" * 60) - print(f"Topic: {topic}") - print( - f"Participants: {group_size} | Rounds: {rounds} | Debate: {debate_time}s/round" - ) - print(f"Mode: {'Mock' if mock else 'LLM'}") - - await pul.init() - try: - mbti_group = sample_mbti_group(group_size) - dist = Counter(mbti_group) - print("\nGroup:") - for mbti, count in sorted(dist.items(), key=lambda x: -x[1]): - print(f" {mbti} ({MBTI_TYPES[mbti]['name']}): {count}") - - # Create moderator - moderator = await ModeratorActor.spawn( - topic=topic, - rounds=rounds, - debate_time=debate_time, - mock=mock, - name="moderator", - ) - - # Create participants - for i, mbti in enumerate(mbti_group): - agent_name = f"agent_{i}_{mbti}" - await MBTIAgent.spawn( - agent_name=agent_name, - mbti=mbti, - topic=topic, - moderator="moderator", - mock=mock, - name=agent_name, - ) - await moderator.register_agent(agent_name, mbti) - - print(f"\nRegistered Agents: {len(mbti_group)}") - - # Start discussion - result = await moderator.start_discussion() - return result - finally: - await pul.shutdown() - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - "--topic", default="Should remote work become the mainstream work style?" - ) - parser.add_argument("--group-size", type=int, default=6) - parser.add_argument("--rounds", type=int, default=2) - parser.add_argument("--debate-time", type=float, default=5.0) - parser.add_argument("--mock", action="store_true") - args = parser.parse_args() - - asyncio.run( - run( - topic=args.topic, - group_size=args.group_size, - rounds=args.rounds, - debate_time=args.debate_time, - mock=args.mock, - ) - ) diff --git a/examples/agent/pulsing/parallel_ideas_async.py b/examples/agent/pulsing/parallel_ideas_async.py deleted file mode 100644 index 336a4c78a..000000000 --- a/examples/agent/pulsing/parallel_ideas_async.py +++ /dev/null @@ -1,594 +0,0 @@ -""" -Pulsing Parallel Multi-Agent Example - -Architecture: N IdeaAgents iterate in parallel, competing to submit to Judge - -Usage: - python parallel_ideas_async.py --mock # Mock mode - python parallel_ideas_async.py --question "question" # Real LLM -""" - -from __future__ import annotations - -import argparse -import asyncio -import json -import random -import time -import pulsing as pul -from pulsing.agent import llm, parse_json - -# ============================================================================ -# Configuration -# ============================================================================ - -PERSONAS = [ - "Performance Engineer", - "Product Manager", - "System Architect", - "Security Expert", - "Reliability Ops", - "Researcher", - "Data Engineer", - "Cost Controller", - "UX Designer", - "Test Engineer", -] - -# Mock mode templates -MOCK_TEMPLATES = { - "Performance": ( - "Parallelization and cache optimization", - ["Load testing to locate bottlenecks", "Cache hit rate testing"], - ["Cache consistency"], - ), - "Security": ( - "Security boundaries and governance", - ["Threat modeling", "mTLS verification"], - ["Increased latency"], - ), - "Reliability": ( - "Resilience solutions", - ["Fault injection testing", "Retry strategy verification"], - ["Retry storms"], - ), - "Product": ( - "Streaming experience", - ["TTFB optimization", "A/B testing"], - ["Increased complexity"], - ), - "Cost": ( - "Cost-driven architecture", - ["Cost curve analysis", "On-demand scaling"], - ["Quality degradation"], - ), -} - -MOCK_SUGGESTIONS = { - "Performance": "Suggest adding cache layer and connection pool optimization", - "Security": "Suggest adding mTLS and audit logs", - "Reliability": "Suggest adding circuit breakers and retry mechanisms", - "Product": "Suggest adding streaming output and progress feedback", - "Cost": "Suggest evaluating on-demand scaling strategy", -} - -# ============================================================================ -# LLM Utilities -# ============================================================================ - - -async def get_llm(): - return await llm(temperature=0.7) - - -# ============================================================================ -# Judge Actor -# ============================================================================ - - -@pul.remote -class JudgeActor: - def __init__(self, timeout: float, mock: bool): - self.timeout = timeout - self.mock = mock - self.submissions: list[dict] = [] - self.deadline: float | None = None - self.result: dict | None = None - self._done = asyncio.Event() - self._agents: list[str] = [] - - def set_agents(self, names: list[str]): - self._agents = names - - async def submit(self, idea: dict, iterations: int) -> dict: - now = time.time() - - # Check deadline - if self.deadline and now > self.deadline: - print(f" ❌ [{idea['agent']}] Rejected (timeout)") - return {"accepted": False} - - self.submissions.append({"idea": idea, "iterations": iterations, "time": now}) - - # First submission starts timer - if not self.deadline: - self.deadline = now + self.timeout - print( - f"\n[Judge] Received first proposal [{idea['agent']}], deadline in {self.timeout}s" - ) - asyncio.create_task(self._timer()) - - remaining = self.deadline - now - print( - f" ✓ [{idea['agent']}] v{idea.get('version', 1)} " - f"score:{idea.get('score', 0)}/10 iterations:{iterations} remaining:{remaining:.1f}s" - ) - return {"accepted": True, "remaining": remaining} - - async def _timer(self): - await asyncio.sleep(self.timeout) - print(f"\n[Judge] ⏰ Deadline! Total {len(self.submissions)} proposals") - - # Stop all agents - for name in self._agents: - try: - agent = await IdeaAgent.resolve(name) - await agent.stop() - except Exception as e: - print(f"[Judge] Error stopping agent '{name}': {e}") - - await self._decide() - - async def _decide(self): - if not self.submissions: - self.result = {"error": "No proposals"} - self._done.set() - return - - # Print proposal list - for i, s in enumerate(self.submissions, 1): - idea = s["idea"] - print( - f" {i}. [{idea['agent']}] {idea['title']} - {idea.get('score', 0)}/10" - ) - - # Select highest score - best = max(self.submissions, key=lambda x: x["idea"].get("score", 0)) - self.result = { - "selected": best["idea"]["agent"], - "reason": f"Highest score ({best['idea'].get('score', 0)}/10)", - "proposal": best["idea"]["proposal"], - "count": len(self.submissions), - } - print(f"\n[Judge] Selected: [{self.result['selected']}]") - self._done.set() - - async def get_result(self) -> dict: - await self._done.wait() - return self.result or {} - - -# ============================================================================ -# IdeaAgent Actor -# ============================================================================ - - -@pul.remote -class IdeaAgent: - def __init__( - self, - persona: str, - question: str, - judge: str, - peers: list[str], - max_rounds: int, - target_score: int, - mock: bool, - collab: bool, - ): - self.persona = persona - self.question = question - self.judge_name = judge - self.peers = peers - self.max_rounds = max_rounds - self.target_score = target_score - self.mock = mock - self.collab = collab - - self.idea: dict | None = None - self.prev_idea: dict | None = None - self.prev_score = 0 - self.iterations = 0 - self.collabs = 0 - self._stopped = False - self._task: asyncio.Task | None = None - self._result: dict | None = None - - async def start(self): - if self._task: - return - self._task = asyncio.create_task(self._run()) - - async def get_result(self) -> dict: - if not self._task: - return {"error": "not started"} - if self._result: - return self._result - self._result = await self._task - return self._result - - def stop(self): - self._stopped = True - print(f" [{self.persona}] 🛑 Stopped") - - def assist(self, from_agent: str, context: dict) -> dict: - """Synchronous assistance (quick return based on current idea)""" - title = context.get("idea", {}).get("title", "") - print( - f" [{self.persona}] 📨 Received request from [{from_agent}]: {title[:20]}" - ) - - # Give suggestions based on professional field - suggestion = next( - (s for k, s in MOCK_SUGGESTIONS.items() if k in self.persona), - "Suggest multi-angle evaluation", - ) - if self.idea: - suggestion += f". Reference my proposal: {self.idea.get('title', '')}" - - print(f" [{self.persona}] 💡 Reply to [{from_agent}]: {suggestion[:40]}...") - return {"from": self.persona, "suggestion": suggestion} - - # -------------------- Main Loop -------------------- - - async def _run(self) -> dict: - start = time.time() - - # 1. Generate initial proposal - print(f"\n [{self.persona}] 🚀 Started") - self.idea = await self._generate() - self.iterations = 1 - - # Initial critique - critique = await self._critique() - self.idea["score"] = critique["score"] - self.prev_score = critique["score"] - self.prev_idea = self.idea.copy() - - # 2. Iterative improvement - while self.iterations < self.max_rounds and not self._stopped: - if self.idea["score"] >= self.target_score: - print(f" [{self.persona}] ✅ Reached target {self.target_score}") - break - - # Collaboration - advice = [] - if self.collab and critique.get("consult"): - advice = await self._collaborate(critique["consult"][:2]) - - if self._stopped: - break - - # Refine - self.iterations += 1 - self.prev_idea = self.idea.copy() - self.prev_score = self.idea["score"] - - self.idea = await self._refine(critique, advice) - critique = await self._critique() - new_score = critique["score"] - self.idea["score"] = new_score - - # Score comparison - if new_score < self.prev_score: - print(f" [{self.persona}] ⚠️ {self.prev_score}→{new_score} Reverted") - self.idea = self.prev_idea.copy() - elif new_score > self.prev_score: - print(f" [{self.persona}] ⬆️ {self.prev_score}→{new_score}") - - # 3. Submit - if self._stopped: - return {"persona": self.persona, "accepted": False, "reason": "stopped"} - - elapsed = time.time() - start - print(f" [{self.persona}] 📤 Submitted ({elapsed:.1f}s)") - - judge = await JudgeActor.resolve(self.judge_name) - result = await judge.submit(self.idea, self.iterations) - - return { - "persona": self.persona, - "accepted": result.get("accepted", False), - "score": self.idea.get("score", 0), - "iterations": self.iterations, - "elapsed": elapsed, - "collabs": self.collabs, - } - - # -------------------- Core Methods -------------------- - - async def _generate(self) -> dict: - if self.mock: - await asyncio.sleep(random.uniform(0.3, 1.0)) - for key, (title, exps, risks) in MOCK_TEMPLATES.items(): - if key in self.persona: - break - else: - title, exps, risks = ( - "Generic solution", - ["Validation experiment"], - ["Risk"], - ) - idea = { - "agent": self.persona, - "title": title, - "proposal": f"{self.persona}: {title}", - "experiments": exps, - "risks": risks, - "version": 1, - "score": 0, - } - else: - llm = await get_llm() - prompt = f'You are {self.persona}, propose a solution for: {self.question}\nOutput JSON: {{"title":"","proposal":"","experiments":[],"risks":[]}}' - resp = await llm.ainvoke(prompt) - data = parse_json(resp.content, {}) - idea = { - "agent": self.persona, - "title": data.get("title", "Solution"), - "proposal": data.get("proposal", ""), - "experiments": data.get("experiments", []), - "risks": data.get("risks", []), - "version": 1, - "score": 0, - } - - self._log_idea(idea, "📝 Generated") - return idea - - async def _critique(self) -> dict: - # Available experts to consult (exclude self) - available_experts = [p for p in PERSONAS if p != self.persona] - - if self.mock: - await asyncio.sleep(random.uniform(0.1, 0.3)) - score = min( - 10, - max( - 1, - 5 - + len(self.idea.get("experiments", [])) - + self.idea.get("version", 1) - - 1, - ), - ) - issues = ( - ["Insufficient experiments"] - if len(self.idea.get("experiments", [])) < 3 - else ["Solution feasible"] - ) - consult = [ - p - for p in ["Performance Engineer", "Security Expert"] - if p != self.persona - ][:2] - critique = { - "score": score, - "issues": issues, - "improvements": ["Add experiments"], - "consult": consult, - } - else: - llm = await get_llm() - prompt = f"""Review the following proposal, identify issues and give suggestions. - -Proposal: {json.dumps(self.idea, ensure_ascii=False)} - -Available experts: {", ".join(available_experts[:5])} - -Output JSON (no markdown): -{{"score": 1-10, "issues": ["issue1"], "improvements": ["improvement1"], "consult": ["expert name to consult"]}}""" - resp = await llm.ainvoke(prompt) - data = parse_json(resp.content, {}) - critique = { - "score": data.get("score", 5), - "issues": data.get("issues", []), - "improvements": data.get("improvements", []), - "consult": data.get("consult", []), - } - - consult_info = ( - f" → Suggest consulting: {critique['consult']}" - if critique.get("consult") - else "" - ) - print( - f" [{self.persona}] 📋 Critique: {critique['score']}/10 | {', '.join(str(i) for i in critique['issues'][:2])}{consult_info}" - ) - return critique - - async def _refine(self, critique: dict, advice: list[dict]) -> dict: - if self.mock: - await asyncio.sleep(random.uniform(0.2, 0.5)) - exps = list(self.idea.get("experiments", [])) - exps.append( - f"New: {critique['improvements'][0][:10]}..." - if critique.get("improvements") - else "Improved experiment" - ) - for a in advice: - exps.append(f"Collaboration: {a.get('suggestion', '')[:15]}...") - refined = { - **self.idea, - "title": self.idea["title"] + " (Improved)", - "experiments": exps[:5], - "version": self.idea.get("version", 1) + 1, - "score": 0, - } - else: - llm = await get_llm() - collab_text = ( - "\n".join([f"- {a['from']}: {a['suggestion']}" for a in advice]) - if advice - else "" - ) - prompt = f"You are {self.persona}, improve the proposal: {json.dumps(self.idea, ensure_ascii=False)}\nIssues: {critique['issues']}\nSuggestions: {critique['improvements']}\n{collab_text}\nOutput JSON" - resp = await llm.ainvoke(prompt) - data = parse_json(resp.content, {}) - refined = { - "agent": self.persona, - "title": data.get("title", self.idea["title"]), - "proposal": data.get("proposal", self.idea["proposal"]), - "experiments": data.get("experiments", []), - "risks": data.get("risks", []), - "version": self.idea.get("version", 1) + 1, - "score": 0, - } - - self._log_idea(refined, f"🔄 Refined v{refined['version']}") - return refined - - async def _collaborate(self, experts: list[str]) -> list[dict]: - advice = [] - for expert in experts: - if expert == self.persona: - continue - # Find corresponding peer - peer_name = next((n for n in self.peers if expert in n), None) - if not peer_name: - continue - - print(f" [{self.persona}] 🤝 Requesting [{expert}]") - try: - peer = await asyncio.wait_for(IdeaAgent.resolve(peer_name), timeout=5) - resp = await asyncio.wait_for( - peer.assist(from_agent=self.persona, context={"idea": self.idea}), - timeout=10, - ) - if resp.get("suggestion"): - advice.append(resp) - self.collabs += 1 - print( - f" [{self.persona}] ✓ Received from [{resp['from']}]: {resp['suggestion'][:30]}..." - ) - except Exception as e: - print(f" [{self.persona}] ⚠ Collaboration failed: {e}") - return advice - - def _log_idea(self, idea: dict, action: str): - print(f" [{self.persona}] {action}: {idea['title']}") - experiments = idea.get("experiments", [])[:3] - if experiments: - if isinstance(experiments[0], dict): - # Complex experiment format - for i, exp in enumerate(experiments, 1): - name = exp.get("name", exp.get("title", f"Experiment {i}")) - print(f" {i}. {name}") - else: - # Simple string format - for i, exp in enumerate(experiments, 1): - print(f" {i}. {exp[:50]}{'...' if len(str(exp)) > 50 else ''}") - - -# ============================================================================ -# Entry Point -# ============================================================================ - - -async def run( - question: str, - n: int = 3, - rounds: int = 3, - target: int = 8, - timeout: float = 30, - mock: bool = False, - collab: bool = True, -): - print("=" * 50) - print(f"Question: {question}") - print( - f"Agents: {n} | Rounds: {rounds} | Target: {target} | Timeout: {timeout}s | Collaboration: {collab}" - ) - print("=" * 50) - - await pul.init() - try: - # Create Judge - judge = await JudgeActor.spawn(timeout=timeout, mock=mock, name="judge") - - # Create all Agents - # Sanitize persona names for use in actor names (replace spaces with underscores) - agent_names = [f"agent_{p.replace(' ', '_')}" for p in PERSONAS] - agents = [] - for i, persona in enumerate(PERSONAS): - # Use sanitized name for actor name - name = f"agent_{persona.replace(' ', '_')}" - peers = [n for n in agent_names if n != name] - agent = await IdeaAgent.spawn( - persona=persona, - question=question, - judge="judge", - peers=peers, - max_rounds=rounds, - target_score=target, - mock=mock, - collab=collab, - name=name, - ) - agents.append(agent) - - await judge.set_agents(agent_names) - - # Start first n agents - active = agents[:n] - print(f"\nStarting {n} Agents: {[PERSONAS[i] for i in range(n)]}") - for a in active: - await a.start() - - # Wait for results - results = await asyncio.gather( - *[a.get_result() for a in active], return_exceptions=True - ) - final = await judge.get_result() - - # Output - print("\n" + "=" * 50) - print(f"Result: [{final.get('selected')}] - {final.get('reason')}") - print(f"Proposals: {final.get('count', 0)}") - print("\nAgent Statistics:") - for r in results: - if isinstance(r, dict): - s = "✓" if r.get("accepted") else "✗" - print( - f" {s} [{r['persona']}] score:{r.get('score', 0)} iterations:{r.get('iterations')} collabs:{r.get('collabs', 0)}" - ) - - return {"final": final, "agents": results} - finally: - await pul.shutdown() - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - "--question", default="How to implement high-performance multi-agent workflows?" - ) - parser.add_argument("--n-ideas", type=int, default=3) - parser.add_argument("--max-rounds", type=int, default=3) - parser.add_argument("--target-score", type=int, default=8) - parser.add_argument("--timeout", type=float, default=30) - parser.add_argument("--mock", action="store_true") - parser.add_argument("--no-collab", action="store_true") - args = parser.parse_args() - - asyncio.run( - run( - question=args.question, - n=args.n_ideas, - rounds=args.max_rounds, - target=args.target_score, - timeout=args.timeout, - mock=args.mock, - collab=not args.no_collab, - ) - ) diff --git a/examples/agent/workspace-demo.md b/examples/agent/workspace-demo.md deleted file mode 100644 index 4f15a88d7..000000000 --- a/examples/agent/workspace-demo.md +++ /dev/null @@ -1,48 +0,0 @@ -# Pulsing Agent — Workspace Demo - -基于 Pulsing 的 workspace CLI:在项目目录内管理 `.pulsing/`、启动节点、与 Agent 协作。 - -## 一键最小 Demo(无需 API Key) - -```bash -./examples/python/workspace_demo.sh -# 或 -uv run python examples/python/workspace_minimal_demo.py -``` - -单进程完成:`pulsing init` → 启动 `guide`(demo LLM)→ 发送一条消息并打印回复。 - -## 双终端流程 - -```bash -cd ~/myproject -pulsing init -pulsing agent wake --provider demo --agents guide # terminal 1 -pulsing agent say guide "list project files" # terminal 2 -``` - -真实模型时去掉 `--provider demo`,并配置 `ANTHROPIC_API_KEY` / `OPENAI_API_KEY`。 - -```bash -pulsing agent init -pulsing agent wake --agents guide # terminal 1 -pulsing agent look # default -pulsing agent list -pulsing agent task list -pulsing agent say guide "fix unit-tests" -pulsing agent spawn coder -pulsing agent demo # offline demo + optional dashboard -``` - -安装 LLM 依赖:`pip install pulsing[agent]` - -任务配置在 `.pulsing/cluster.json` 的 `puzzles` 字段。 - -隔离工具由 [Pulsing Forge](../../python/pulsing/forge/README.md) 提供(`ToolWorkerActor`)。 - -## 已弃用 - -- `pcraft` / `pulsing craft` → 使用 `pulsing agent` -- `pulsing.craft` 包 → 使用 `pulsing.agent` - -见 [agent-craft-migration.md](../../docs/design/agent-craft-migration.md)。 diff --git a/examples/python/README.md b/examples/python/README.md index ee863a697..3f20a2852 100644 --- a/examples/python/README.md +++ b/examples/python/README.md @@ -40,12 +40,6 @@ python examples/python/tensor_message_fast_path.py --transport http2 # Compatib python examples/python/subprocess_example.py # Native subprocess-compatible API USE_POLSING_SUBPROCESS=1 python examples/python/subprocess_example.py --resources # Pulsing backend python examples/python/isolated_actor_spawn.py # Actor in child OS process; cluster sees parent bridge -python examples/python/forge_minimal.py # Pulsing Forge (pulsing.forge) local + actor worker -python examples/python/forge_custom_agent.py # Embed Forge in your own agent framework -python examples/python/forge_custom_agent.py --isolated # Same, tools in ToolWorkerActor subprocess -python examples/python/forge_agent_quickstart.py # ForgeAgent demo (no API key) -./examples/python/workspace_demo.sh # workspace init → wake → say (demo LLM) -python examples/python/workspace_minimal_demo.py # same, single Python process ``` `tensor_message_fast_path.py` 会创建两个 ActorSystem,确保请求真实经过 TCP。示例使用 diff --git a/examples/python/craft_demo.sh b/examples/python/craft_demo.sh deleted file mode 100755 index 96e4e9d55..000000000 --- a/examples/python/craft_demo.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash -# One-shot agent workspace demo: three chattering agents + Zellij dashboard (if installed). -set -euo pipefail -ROOT="${1:-.}" -cd "$ROOT" -shift || true -if command -v pulsing-agent >/dev/null 2>&1; then - exec pulsing-agent demo "$@" -fi -exec pulsing agent demo "$@" diff --git a/examples/python/forge_agent_quickstart.py b/examples/python/forge_agent_quickstart.py deleted file mode 100644 index 843c53117..000000000 --- a/examples/python/forge_agent_quickstart.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: Apache-2.0 -"""Quickstart: ForgeAgent with zero API keys (demo provider). - - uv run python examples/python/forge_agent_quickstart.py - -With OpenAI: - - OPENAI_API_KEY=sk-... uv run python examples/python/forge_agent_quickstart.py \\ - --provider openai --model gpt-4o-mini \\ - "Find README files and summarize the project in one paragraph" -""" - -from __future__ import annotations - -import argparse -import asyncio -from pathlib import Path - -from pulsing.forge.host import ForgeAgent - - -def _parse_args() -> argparse.Namespace: - p = argparse.ArgumentParser(description=__doc__) - p.add_argument("prompt", nargs="?", default="List README files in this project.") - p.add_argument("--cwd", type=Path, default=Path.cwd()) - p.add_argument( - "--provider", default="demo", choices=["demo", "openai", "anthropic"] - ) - p.add_argument("--model", default=None) - p.add_argument("--quiet", action="store_true", help="Disable assistant streaming") - return p.parse_args() - - -async def _main() -> None: - args = _parse_args() - model = args.model - if model is None: - model = { - "demo": "demo", - "openai": "gpt-4o-mini", - "anthropic": "claude-sonnet-4-20250514", - }[args.provider] - - from pulsing.forge.host.cli_events import CliEventSink - - events = CliEventSink(stream_assistant=not args.quiet) - agent = ForgeAgent( - cwd=args.cwd.resolve(), - provider=args.provider, - model=model, - events=events, - ) - try: - print(f"# ForgeAgent ({args.provider}/{model})\n") - answer = await agent.run(args.prompt) - print(f"\n# done\n{answer}") - finally: - agent.close() - - -if __name__ == "__main__": - asyncio.run(_main()) diff --git a/examples/python/forge_custom_agent.py b/examples/python/forge_custom_agent.py deleted file mode 100644 index 3ca88b509..000000000 --- a/examples/python/forge_custom_agent.py +++ /dev/null @@ -1,354 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: Apache-2.0 -"""Embed Pulsing Forge in a **custom agent framework**. - -Your framework owns the LLM loop, memory, and UI. Forge provides the tool -runtime (Read, Glob, shell, patch, plan hooks, …) — no Craft required. - -Run (in-process, no cluster): - - uv run python examples/python/forge_custom_agent.py - -Run with an isolated ToolWorkerActor (separate OS process via Pulsing): - - uv run python examples/python/forge_custom_agent.py --isolated - -This example uses a **scripted mock LLM** so it works without API keys. -Replace ``ScriptedLLM`` with your real model client; keep ``ForgeToolBackend``. -""" - -from __future__ import annotations - -import argparse -import asyncio -import json -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any, Protocol - -import pulsing as pul -from pulsing.forge import ( - ForgeEnvironment, - LocalToolSession, - ParsedToolCall, - PlanItem, - StepStatus, - ToolResult, - ToolWorkerActor, - ToolWorkerConfig, - UpdatePlanArgs, - forge_tool_definitions, - openai_tool_message, - to_openai_tools, -) - -# --------------------------------------------------------------------------- -# 1. Your framework: session hooks (plan, user input, approvals) -# --------------------------------------------------------------------------- - - -class MyToolSession(LocalToolSession): - """Host-side state that Forge session tools write into.""" - - def __init__(self) -> None: - super().__init__(token_budget=128_000) - self.log: list[str] = [] - - def update_plan(self, args: UpdatePlanArgs) -> None: - super().update_plan(args) - steps = ", ".join(f"{p.step}({p.status})" for p in args.plan) - self.log.append(f"plan updated: {steps}") - - def request_user_input(self, arguments: dict[str, Any]) -> dict[str, Any]: - # In a real UI, show a modal and wait for the user. - questions = arguments.get("questions") or [] - self.log.append(f"user_input requested: {len(questions)} question(s)") - return {"answers": {q.get("id", "confirm"): "yes" for q in questions}} - - -# --------------------------------------------------------------------------- -# 2. Your framework: Forge as the tool backend -# --------------------------------------------------------------------------- - -DEMO_TOOL_NAMES = ["update_plan", "Glob", "Read", "shell_command"] - - -class ToolBackend(Protocol): - def tool_schemas(self) -> list[dict[str, Any]]: ... - - async def call_tool(self, name: str, arguments: dict[str, Any]) -> ToolResult: ... - - -@dataclass -class InProcessForgeBackend: - """ForgeEnvironment in the same process as your agent loop.""" - - cwd: Path - session: MyToolSession = field(default_factory=MyToolSession) - - def __post_init__(self) -> None: - env = ForgeEnvironment( - cwd=str(self.cwd), - sandbox_policy="off", - session=self.session, - auto_approve=True, - ) - self._runtime = env.runtime() - - def tool_schemas(self) -> list[dict[str, Any]]: - # Anthropic-shaped defs → OpenAI tools for the LLM client. - defs = forge_tool_definitions(DEMO_TOOL_NAMES) - available = set(self._runtime.tool_names()) - defs = [d for d in defs if d.get("name") in available] - return to_openai_tools(defs) - - async def call_tool(self, name: str, arguments: dict[str, Any]) -> ToolResult: - return self._runtime.call_tool(name, arguments) - - def close(self) -> None: - self._runtime.close() - - -@dataclass -class IsolatedForgeBackend: - """Forge tools in a ToolWorkerActor (child process). Host stays lightweight.""" - - worker: Any # ActorProxy - - def tool_schemas(self) -> list[dict[str, Any]]: - return to_openai_tools(forge_tool_definitions(DEMO_TOOL_NAMES)) - - async def call_tool(self, name: str, arguments: dict[str, Any]) -> ToolResult: - raw = await self.worker.call_tool(name, arguments) - return ToolResult.from_dict(raw) - - def close(self) -> None: - return None - - -# --------------------------------------------------------------------------- -# 3. Your framework: LLM client (mock here; swap for OpenAI/Anthropic/etc.) -# --------------------------------------------------------------------------- - - -@dataclass -class ToolCall: - call: ParsedToolCall - - -class ScriptedLLM: - """Deterministic tool-call sequence for the demo.""" - - def __init__(self, workspace: Path) -> None: - self._workspace = workspace - self._step = 0 - - def next_tool_calls(self, _messages: list[dict[str, Any]]) -> list[ToolCall]: - readme = self._workspace / "README.md" - if not readme.is_file(): - readme = self._workspace / "README.zh.md" - - script = [ - ToolCall( - ParsedToolCall( - id="call-plan", - name="update_plan", - arguments={ - "plan": [ - {"step": "Scan workspace", "status": "in_progress"}, - {"step": "Read README", "status": "pending"}, - {"step": "Run sanity check", "status": "pending"}, - ], - "explanation": "Exploring the repo before answering.", - }, - ) - ), - ToolCall( - ParsedToolCall( - id="call-glob", - name="Glob", - arguments={"pattern": "README*", "path": str(self._workspace)}, - ) - ), - ToolCall( - ParsedToolCall( - id="call-read", - name="Read", - arguments={"file_path": str(readme)}, - ) - ), - ToolCall( - ParsedToolCall( - id="call-shell", - name="shell_command", - arguments={ - "command": "echo forge-ok", - "workdir": str(self._workspace), - }, - ) - ), - ] - if self._step >= len(script): - return [] - call = script[self._step] - self._step += 1 - return [call] - - -# --------------------------------------------------------------------------- -# 4. Your framework: agent loop -# --------------------------------------------------------------------------- - - -@dataclass -class AgentConfig: - max_turns: int = 8 - system_prompt: str = ( - "You are a coding agent. Use tools to inspect the workspace, " - "then summarize what you found." - ) - - -class SimpleAgentFramework: - """Minimal Host: messages in memory, tools via Forge, LLM pluggable.""" - - def __init__( - self, - *, - backend: ToolBackend, - llm: ScriptedLLM, - config: AgentConfig | None = None, - ) -> None: - self.backend = backend - self.llm = llm - self.config = config or AgentConfig() - self.messages: list[dict[str, Any]] = [ - {"role": "system", "content": self.config.system_prompt}, - ] - - async def arun(self) -> str: - tools = self.backend.tool_schemas() - print(f"Registered {len(tools)} tools for the LLM:") - for t in tools: - print(f" - {t['function']['name']}") - - for turn in range(self.config.max_turns): - calls = self.llm.next_tool_calls(self.messages) - if not calls: - return self._final_answer() - - for call in calls: - tc = call.call - print( - f"\n[turn {turn + 1}] LLM → tool {tc.name}" - f"({json.dumps(tc.arguments, ensure_ascii=False)[:120]}…)" - ) - result = await self.backend.call_tool(tc.name, tc.arguments) - preview = result.content[:200].replace("\n", "\\n") - status = "ERROR" if result.is_error else "OK" - print(f" Forge → {status}: {preview}") - - self.messages.append( - { - "role": "assistant", - "tool_calls": [ - { - "id": tc.id, - "type": "function", - "function": { - "name": tc.name, - "arguments": json.dumps(tc.arguments), - }, - } - ], - } - ) - self.messages.append(openai_tool_message(tc.id, result)) - - return self._final_answer() - - def _final_answer(self) -> str: - session = getattr(self.backend, "session", None) - if isinstance(session, MyToolSession) and session.plan: - done = sum(1 for p in session.plan if p.status == StepStatus.COMPLETED) - plan_summary = f"{done}/{len(session.plan)} plan steps completed" - else: - plan_summary = "plan tracked in host session" - - tool_msgs = [m for m in self.messages if m.get("role") == "tool"] - return f"Agent finished after {len(tool_msgs)} tool result(s). {plan_summary}." - - -# --------------------------------------------------------------------------- -# 5. Entry -# --------------------------------------------------------------------------- - - -async def _run_in_process(workspace: Path) -> None: - session = MyToolSession() - backend = InProcessForgeBackend(cwd=workspace, session=session) - try: - agent = SimpleAgentFramework( - backend=backend, - llm=ScriptedLLM(workspace), - ) - print("== Custom agent framework + Forge (in-process) ==\n") - answer = await agent.arun() - print(f"\n== Final ==\n{answer}") - if session.log: - print("\n== Host session log ==") - for line in session.log: - print(f" {line}") - if session.plan: - print("\n== Plan snapshot ==") - for item in session.plan: - print(f" [{item.status}] {item.step}") - finally: - backend.close() - - -async def _run_isolated(workspace: Path) -> None: - await pul.init() - try: - worker = await ToolWorkerActor.spawn( - ToolWorkerConfig(cwd=str(workspace), auto_approve=True), - public=False, - ) - backend = IsolatedForgeBackend(worker=worker) - agent = SimpleAgentFramework( - backend=backend, - llm=ScriptedLLM(workspace), - ) - print("== Custom agent framework + Forge (isolated worker) ==\n") - ping = await worker.ping() - print(f"Worker: {ping}\n") - answer = await agent.arun() - print(f"\n== Final ==\n{answer}") - finally: - await pul.shutdown() - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument( - "--isolated", - action="store_true", - help="Run Forge tools inside ToolWorkerActor (Pulsing subprocess)", - ) - parser.add_argument( - "--workspace", - type=Path, - default=Path(__file__).resolve().parents[2], - help="Workspace root for tools (default: repo root)", - ) - args = parser.parse_args() - workspace = args.workspace.resolve() - - if args.isolated: - asyncio.run(_run_isolated(workspace)) - else: - asyncio.run(_run_in_process(workspace)) - - -if __name__ == "__main__": - main() diff --git a/examples/python/forge_minimal.py b/examples/python/forge_minimal.py deleted file mode 100644 index b2e01cb25..000000000 --- a/examples/python/forge_minimal.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: Apache-2.0 -"""Minimal Pulsing Forge demo (``pulsing.forge``; no Craft).""" - -from __future__ import annotations - -import asyncio -from pathlib import Path - -import pulsing as pul -from pulsing.forge import ForgeEnvironment, ToolWorkerActor, ToolWorkerConfig - - -async def main() -> None: - root = Path.cwd() - env = ForgeEnvironment(cwd=str(root), sandbox_policy="off") - rt = env.runtime() - - print("== local environment ==") - print(rt.call_tool("Glob", {"pattern": "README*", "path": str(root)}).content[:200]) - - print("== actor worker ==") - await pul.init() - try: - worker = await ToolWorkerActor.spawn( - ToolWorkerConfig(cwd=str(root)), - public=False, - ) - out = await worker.Glob(pattern="pyproject.toml", path=str(root)) - print(out.get("content", out)) - finally: - await pul.shutdown() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/examples/python/workspace_demo.sh b/examples/python/workspace_demo.sh deleted file mode 100755 index 10961e2e7..000000000 --- a/examples/python/workspace_demo.sh +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env bash -# SPDX-License-Identifier: Apache-2.0 -# Bootstrap a minimal Pulsing workspace demo from zero (no API key by default). -set -euo pipefail - -ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -DEMO_DIR="${PULSING_DEMO_DIR:-$(mktemp -d -t pulsing-ws-demo)}" -KEEP=0 - -usage() { - cat <<'EOF' -usage: workspace_demo.sh [options] [-- message] - -Bootstrap .pulsing/, wake guide with demo LLM, send one message. - -Options: - --dir PATH workspace directory (default: temp dir) - --keep keep workspace directory after run - --provider NAME demo | anthropic | openai (default: demo) - --real-llm alias for --provider anthropic - -h, --help show this help - -Environment: - PULSING_DEMO_DIR default workspace directory when --dir is omitted - -Examples: - ./examples/python/workspace_demo.sh - ./examples/python/workspace_demo.sh --dir ./my-ws --keep - ./examples/python/workspace_demo.sh -- "read README and summarize" -EOF -} - -ARGS=() -while [[ $# -gt 0 ]]; do - case "$1" in - --dir) - DEMO_DIR="$2" - shift 2 - ;; - --keep) - KEEP=1 - shift - ;; - --provider) - PROVIDER="$2" - shift 2 - ;; - --real-llm) - PROVIDER="anthropic" - shift - ;; - -h|--help) - usage - exit 0 - ;; - --) - shift - ARGS+=("$@") - break - ;; - *) - ARGS+=("$1") - shift - ;; - esac -done - -PROVIDER="${PROVIDER:-demo}" -PY_ARGS=(--dir "$DEMO_DIR" --provider "$PROVIDER") -[[ "$KEEP" -eq 1 ]] && PY_ARGS+=(--keep) -[[ ${#ARGS[@]} -gt 0 ]] && PY_ARGS+=(--message "${ARGS[*]}") - -cd "$ROOT" -if command -v uv >/dev/null 2>&1; then - exec uv run python examples/python/workspace_minimal_demo.py "${PY_ARGS[@]}" -fi -exec python examples/python/workspace_minimal_demo.py "${PY_ARGS[@]}" diff --git a/examples/python/workspace_minimal_demo.py b/examples/python/workspace_minimal_demo.py deleted file mode 100644 index 6cf8a511b..000000000 --- a/examples/python/workspace_minimal_demo.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: Apache-2.0 -"""CLI entry for :mod:`pulsing.workspace.minimal_demo`. - - uv run python examples/python/workspace_minimal_demo.py - -Two-terminal flow (after ``pulsing init``): - - pulsing agent wake --provider demo --agents guide # terminal 1 - pulsing agent say guide "list project files" # terminal 2 -""" - -from __future__ import annotations - -import argparse -import asyncio -import sys -import tempfile -from pathlib import Path - -from pulsing.workspace.minimal_demo import run_workspace_minimal_demo - - -def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: - p = argparse.ArgumentParser(description=__doc__) - p.add_argument("--dir", type=Path, default=None, help="workspace directory") - p.add_argument( - "--message", - default="list project files with Glob", - help="message sent to guide", - ) - p.add_argument( - "--provider", - default="demo", - choices=("demo", "anthropic", "openai"), - ) - p.add_argument("--model", default=None) - p.add_argument("--template", default="agent", choices=("agent", "minimal")) - p.add_argument("--keep", action="store_true") - return p.parse_args(argv) - - -async def _main_async(args: argparse.Namespace) -> int: - temp_dir: tempfile.TemporaryDirectory[str] | None = None - if args.dir is None: - temp_dir = tempfile.TemporaryDirectory(prefix="pulsing-ws-demo-") - root = Path(temp_dir.name) - else: - root = args.dir - - print(f"# workspace: {root}", file=sys.stderr) - if args.provider == "demo": - print("# LLM: demo (offline, no API key)", file=sys.stderr) - else: - print(f"# LLM: {args.provider}/{args.model or 'default'}", file=sys.stderr) - - try: - out = await run_workspace_minimal_demo( - root, - message=args.message, - provider=args.provider, - model=args.model, - template=args.template, - ) - except Exception as exc: - print(f"error: {exc}", file=sys.stderr) - return 1 - - body = out.get("assistant_text") or out.get("error") or out - print(f"\nguide › {body}\n") - if out.get("error"): - return 1 - - if temp_dir is not None and args.keep: - temp_dir.cleanup = lambda: None # type: ignore[method-assign] - print(f"# kept workspace at {root}", file=sys.stderr) - return 0 - - -def main(argv: list[str] | None = None) -> int: - return asyncio.run(_main_async(_parse_args(argv))) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/examples/quickstart/README.md b/examples/quickstart/README.md index 6e89b0dc4..a7b061322 100644 --- a/examples/quickstart/README.md +++ b/examples/quickstart/README.md @@ -1,217 +1,42 @@ -# 🚀 Pulsing 快速入门 - -**5分钟让你的 AI 们开始对话!** - -## 第一步:安装 +# 快速入门 ```bash pip install pulsing -``` - -## 第二步:运行示例 - -### 示例 1: Hello Agent(入门) - -最简单的 Multi-Agent 应用,两个 Agent 互相打招呼: - -```bash python examples/quickstart/hello_agent.py -``` - -输出: -``` -================================================== -🎉 Pulsing Multi-Agent 快速入门 -================================================== -✨ [Alice] 已上线 -✨ [Bob] 已上线 - ---- Agent 互相打招呼 --- - -👋 [Alice] 正在向 [Bob] 打招呼... -📨 [Bob] 收到消息: 嗨,我是 Alice! -💬 [Alice] 收到回复: 你好!我是 Bob - -👋 [Bob] 正在向 [Alice] 打招呼... -📨 [Alice] 收到消息: 嗨,我是 Bob! -💬 [Bob] 收到回复: 你好!我是 Alice - -================================================== -✅ 完成!你已经创建了第一个 Multi-Agent 应用 -================================================== -``` - -### 示例 2: AI 聊天室(有趣) - -4 个不同性格的 AI 讨论一个话题: - -```bash -python examples/quickstart/ai_chat_room.py -``` - -自定义话题: - -```bash -python examples/quickstart/ai_chat_room.py --topic "远程办公是否会成为主流?" --rounds 5 -``` - ---- - -## ⚡ 进阶示例 - -### 示例 3: Function → Fleet(横向扩展) - -**一行代码把函数变成可横向扩展的服务**——同一份代码,workers 从 1→N,吞吐线性提升: - -```bash -# 8 个 worker 处理 200 个任务 +python examples/quickstart/ai_chat_room.py --rounds 2 python examples/quickstart/function_to_fleet.py - -# 调整 worker 数量 -WORKERS=16 ITEMS=500 python examples/quickstart/function_to_fleet.py ``` -输出: -``` -================================================== -⚡ Function → Fleet Result -================================================== - Workers: 8 - Tasks: 200 - Duration: 0.52s - Throughput: 384.6 qps -================================================== -✅ Same code, more workers = higher throughput -================================================== -``` - -**核心代码**(仅 27 行): -```python -@remote -class Worker: - async def run(self, x: int) -> int: - await asyncio.sleep(0.02) # simulate I/O - return x * x +这些示例无需 LLM 或 API key。聊天室使用本地文本模板,演示 actor 间通信。 -async with runtime(): - ws = [await Worker.spawn(name=f"w{i}") for i in range(n)] - res = await asyncio.gather(*(ws[i % n].run(i) for i in range(m))) -``` - -### 示例 4: Chaos-proof(故障自愈) - -**Actor 崩溃后自动重启**——30% 崩溃率下,任务仍然全部完成: - -```bash -python examples/quickstart/chaos_proof.py -``` - -输出: -``` -================================================== -🛡️ Chaos-proof Result -================================================== - Total tasks: 50 - Succeeded: 50 - Retries: 23 - Crash rate: 30% -================================================== -✅ All succeeded! Actor auto-restarted on crash. -================================================== -``` - -**核心代码**: -```python -@remote(restart_policy="on_failure", max_restarts=50) -class FlakyWorker: - def work(self, x: int) -> int: - if random.random() < 0.3: # 30% 概率崩溃 - raise RuntimeError("boom") - return x + 1 -``` - -**亮点**:30% 崩溃率,框架自动重启 Actor,调用方简单重试,最终 100% 完成。 - ---- - -## 核心概念(10秒理解) +核心用法: ```python import pulsing as pul from pulsing.agent import runtime -# 1. @pul.remote 让类变成可分布式部署的 Agent -@pul.remote -class MyAgent: - def hello(self): - return "Hello!" - -# 2. runtime() 管理 Agent 生命周期 -async with runtime(): - # 3. spawn() 创建 Agent 实例 - agent = await MyAgent.spawn(name="my_agent") - - # 4. 直接调用方法(自动变成远程调用) - result = await agent.hello() - - # 5. MyAgent.resolve() 通过名字找到已有 Agent - same_agent = await MyAgent.resolve("my_agent") -``` - -## 下一步 - -| 我想... | 去看... | -|---------|---------| -| 看更复杂的 Multi-Agent | `examples/agent/pulsing/mbti_discussion.py` | -| 学习分布式部署 | `examples/python/cluster.py` | -| 集成 AutoGen | `examples/agent/autogen/` | -| 集成 LangGraph | `examples/agent/langgraph/` | - -```bash -# MBTI 人格讨论(推荐!) -python examples/agent/pulsing/mbti_discussion.py --mock --group-size 6 - -# 并行创意生成 -python examples/agent/pulsing/parallel_ideas_async.py --mock --n-ideas 5 -``` - -## 常见问题 - -### Q: 如何接入真实 LLM? -```bash -export OPENAI_API_KEY=your_key -export OPENAI_BASE_URL=https://api.openai.com/v1 # 可选 - -# 去掉 --mock 参数 -python examples/agent/pulsing/mbti_discussion.py --topic "AI 的未来" -``` +@pul.remote +class Counter: + def __init__(self): + self.value = 0 -### Q: 如何分布式部署? + def inc(self): + self.value += 1 + return self.value -```python -# 节点 1 -async with runtime(addr="0.0.0.0:8001"): - await MyAgent.spawn(name="agent") -# 节点 2(自动发现节点 1) -async with runtime(addr="0.0.0.0:8002", seeds=["node1:8001"]): - agent = await MyAgent.resolve("agent") # 跨节点调用 +async def main(): + async with runtime(): + counter = await Counter.spawn(name="counter") + print(await counter.inc()) ``` -### Q: @remote vs @agent 有什么区别? +分布式部署时为 `runtime` 配置 `addr` 和 `seeds`, +通过 `await Counter.resolve("counter")` 查找已有 actor。 -- `@remote`:基础 Actor,功能完整 -- `@agent`:= `@remote` + 元信息(role/goal),用于可视化和调试 +下一步: -```python -from pulsing.agent import agent, get_agent_meta - -@agent(role="研究员", goal="深入分析") -class Researcher: - ... - -# 可以查询元信息 -meta = get_agent_meta("researcher") -print(meta.role) # "研究员" -``` +- `examples/python/message_patterns.py`:请求响应、单向与流式消息。 +- `examples/python/cluster.py`:多节点通信。 +- `examples/python/tensor_message_fast_path.py`:buffer 传输。 diff --git a/examples/quickstart/ai_chat_room.py b/examples/quickstart/ai_chat_room.py index e08fe4a29..38dd0fe44 100644 --- a/examples/quickstart/ai_chat_room.py +++ b/examples/quickstart/ai_chat_room.py @@ -188,7 +188,7 @@ async def main(topic: str, rounds: int): print("✅ Chat ended!") print("=" * 60) print("\n💡 Tip: Modify AI_PERSONAS to customize AI personalities") - print("💡 Tip: Set OPENAI_API_KEY to connect to real LLM") + print("💡 Tip: Responses use local templates; no model or API key is required") if __name__ == "__main__": diff --git a/examples/quickstart/hello_agent.py b/examples/quickstart/hello_agent.py index 1196a47e9..7d4c6b898 100644 --- a/examples/quickstart/hello_agent.py +++ b/examples/quickstart/hello_agent.py @@ -60,12 +60,8 @@ async def main(): print("✅ Done! You've created your first Multi-Agent application") print("=" * 50) print("\nNext steps:") - print( - " - Try MBTI discussion: python examples/agent/pulsing/mbti_discussion.py --mock" - ) - print( - " - Try parallel ideas: python examples/agent/pulsing/parallel_ideas_async.py --mock" - ) + print(" - Try message patterns: python examples/python/message_patterns.py") + print(" - Try named actors: python examples/python/named_actors.py") if __name__ == "__main__": diff --git a/examples/rust/actor_benchmark.rs b/examples/rust/actor_benchmark.rs deleted file mode 100644 index 1bfe4aa05..000000000 --- a/examples/rust/actor_benchmark.rs +++ /dev/null @@ -1,141 +0,0 @@ -//! Benchmark Example -//! -//! This example demonstrates how to use the Actor-based benchmark architecture. -//! -//! Architecture: -//! - Worker Actor: Sends HTTP requests to the target endpoint -//! - Scheduler Actor: Controls request timing (constant VUs or constant rate) -//! - Coordinator Actor: Orchestrates the benchmark lifecycle -//! - MetricsAggregator Actor: Collects metrics and calculates statistics -//! - ConsoleRenderer Actor: Displays real-time progress -//! -//! Run with: -//! ```bash -//! cargo run --example actor_benchmark -- --url http://localhost:8000 --model gpt2 -//! ``` - -use pulsing_bench::{run_benchmark, BenchmarkArgs}; - -#[tokio::main] -async fn main() -> pulsing_actor::error::Result<()> { - // Parse command line arguments (simplified) - let args: Vec = std::env::args().collect(); - - let mut benchmark_args = BenchmarkArgs::default(); - - let mut i = 1; - while i < args.len() { - match args[i].as_str() { - "--url" if i + 1 < args.len() => { - benchmark_args.url = args[i + 1].clone(); - i += 2; - } - "--model" if i + 1 < args.len() => { - benchmark_args.model_name = args[i + 1].clone(); - i += 2; - } - "--max-vus" if i + 1 < args.len() => { - benchmark_args.max_vus = args[i + 1].parse()?; - i += 2; - } - "--duration" if i + 1 < args.len() => { - benchmark_args.duration_secs = args[i + 1].parse()?; - i += 2; - } - "--warmup" if i + 1 < args.len() => { - benchmark_args.warmup_secs = args[i + 1].parse()?; - i += 2; - } - "--workers" if i + 1 < args.len() => { - benchmark_args.num_workers = args[i + 1].parse()?; - i += 2; - } - "--kind" if i + 1 < args.len() => { - benchmark_args.benchmark_kind = args[i + 1].clone(); - i += 2; - } - "--api-key" if i + 1 < args.len() => { - benchmark_args.api_key = args[i + 1].clone(); - i += 2; - } - "--help" | "-h" => { - print_help(); - return Ok(()); - } - _ => { - i += 1; - } - } - } - - println!("Starting benchmark..."); - println!(" URL: {}", benchmark_args.url); - println!(" Model: {}", benchmark_args.model_name); - println!(" Max VUs: {}", benchmark_args.max_vus); - println!(" Duration: {}s", benchmark_args.duration_secs); - println!(" Workers: {}", benchmark_args.num_workers); - println!(" Kind: {}", benchmark_args.benchmark_kind); - println!(); - - // Run the benchmark - let report = run_benchmark(benchmark_args).await?; - - // Print summary - println!("\n=== Benchmark Report ==="); - println!("Run ID: {}", report.run_id); - println!("Total Duration: {:.2}s", report.total_duration_secs); - println!("Phases completed: {}", report.phases.len()); - - for phase in &report.phases { - println!("\n--- {} ---", phase.phase_name); - println!(" Successful requests: {}", phase.metrics.successful_requests); - println!(" Failed requests: {}", phase.metrics.failed_requests); - println!(" Request rate: {:.2} req/s", phase.metrics.request_rate); - if let Some(ttft) = phase.metrics.avg_ttft_ms { - println!(" Avg TTFT: {:.1}ms", ttft); - } - if let Some(tpot) = phase.metrics.avg_tpot_ms { - println!(" Avg TPOT: {:.2}ms", tpot); - } - } - - Ok(()) -} - -fn print_help() { - println!( - r#" -Pulsing Benchmark Example - -USAGE: - actor_benchmark [OPTIONS] - -OPTIONS: - --url Target URL (default: http://localhost:8000) - --model Model name (default: gpt2) - --max-vus Maximum virtual users (default: 128) - --duration Test duration in seconds (default: 120) - --warmup Warmup duration in seconds (default: 30) - --workers Number of worker actors (default: 4) - --kind Benchmark kind: throughput, sweep, rate, csweep (default: throughput) - --api-key API key for authentication - -h, --help Print this help message - -BENCHMARK KINDS: - throughput - Run at maximum throughput (constant VUs) - sweep - Find max throughput, then test at various rates - rate - Test at specific rates (use --rates) - csweep - Concurrency sweep to find optimal VU count - -EXAMPLES: - # Simple throughput test - actor_benchmark --url http://localhost:8000 --model gpt2 --duration 60 - - # Concurrency sweep - actor_benchmark --url http://localhost:8000 --model gpt2 --kind csweep --max-vus 100 - - # With authentication - actor_benchmark --url http://api.example.com --api-key sk-xxx --model gpt-4 -"# - ); -} diff --git a/pyproject.toml b/pyproject.toml index aed2644e8..d7cf74f08 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,7 @@ classifiers = [ "Topic :: Scientific/Engineering :: Artificial Intelligence", "Operating System :: POSIX :: Linux", ] -keywords = ["actor", "distributed", "async", "llm", "inference"] +keywords = ["actor", "distributed", "async"] [project.urls] Homepage = "https://github.com/DeepLink-org/Pulsing" @@ -38,12 +38,6 @@ Issues = "https://github.com/DeepLink-org/Pulsing/issues" Changelog = "https://github.com/DeepLink-org/Pulsing/blob/main/CHANGELOG.md" [project.optional-dependencies] -forge = [] -tools = [] # deprecated alias for forge -agent = [ - "anthropic>=0.40.0", - "openai>=1.0.0", -] storage = [ "pylance", "pyarrow>=22.0.0", @@ -60,7 +54,6 @@ dev = [ [project.scripts] pulsing = "pulsing.cli.__main__:main" -pulsing-agent = "pulsing.cli.agent.main:main" [tool.maturin] module-name = "pulsing._core" @@ -78,14 +71,6 @@ build-backend = "maturin" minversion = "8.0" asyncio_mode = "auto" testpaths = ["tests/python"] -markers = [ - "forge: Forge test suite", - "forge_l0: registry / manifest gates", - "forge_l1: callable smoke (all 32 tools)", - "forge_l2: wire shape and side-effect checks", - "forge_l3: scenario and trace integration", - "forge_l4: actor / cluster integration (slow)", -] [tool.ruff] line-length = 88 diff --git a/python/pulsing/agent/__init__.py b/python/pulsing/agent/__init__.py index e045f26e1..8bead572e 100644 --- a/python/pulsing/agent/__init__.py +++ b/python/pulsing/agent/__init__.py @@ -1,105 +1,26 @@ -""" -Pulsing Agent Toolbox - -Lightweight multi-agent development tools, fully compatible with pulsing.core. - -Core APIs: -- runtime(): Actor system lifecycle management -- agent(): @remote with metadata (for visualization) -- llm(): LLM client -- parse_json(): JSON parsing - -Example: - from pulsing.core import remote, resolve - from pulsing.agent import agent, runtime, llm, get_agent_meta +"""Actor lifecycle and metadata helpers. - # @remote: Basic Actor - @remote - class Worker: - async def work(self): ... - - # @agent: Actor with metadata (for visualization/debugging) - @agent(role="Researcher", goal="Deep analysis") - class Researcher: - async def analyze(self, topic: str) -> str: - client = await llm() - return await client.ainvoke(f"Analyze: {topic}") - - async def main(): - async with runtime(): - r = await Researcher.spawn(name="researcher") - result = await r.analyze("AI") - - # Get metadata - meta = get_agent_meta("researcher") - print(meta.role) # "Researcher" +LLM clients and the Forge-backed coding-agent SDK are no longer bundled. """ -# Runtime +from .base import AgentMeta, agent, clear_agent_registry, get_agent_meta, list_agents from .runtime import runtime - -# Agent decorator (@remote with metadata) -from .base import agent, AgentMeta, get_agent_meta, list_agents, clear_agent_registry - -# LLM -from .llm import llm, reset_llm - -# Utility functions -from .utils import parse_json, extract_field - -# Agent workspace / cluster / spawn (Phase 1–2) -from .config import AgentConfig, spawn_agent -from .host import Agent, LlmChat -from .workspace import find_workspace_root -from .cluster import list_cluster_agents, resolve_agent +from .utils import extract_field, parse_json def cleanup(): - """ - Clean up all agent-related global state. - - Includes: - - Agent metadata registry - - LLM singleton - - Recommended to call when repeatedly creating/destroying runtime to avoid memory leaks. - - Example: - from pulsing.agent import runtime, cleanup - - try: - async with runtime(): - agent = await MyAgent.spawn(name="agent") - await agent.work() - finally: - cleanup() # Clean up all global state - """ + """Clear actor metadata between runtime sessions.""" clear_agent_registry() - reset_llm() __all__ = [ - # Runtime "runtime", "cleanup", - # Agent "agent", "AgentMeta", "get_agent_meta", "list_agents", "clear_agent_registry", - # LLM - "llm", - "reset_llm", - # Utility functions "parse_json", "extract_field", - # Workspace agent SDK - "AgentConfig", - "Agent", - "LlmChat", - "spawn_agent", - "find_workspace_root", - "list_cluster_agents", - "resolve_agent", ] diff --git a/python/pulsing/agent/actors/__init__.py b/python/pulsing/agent/actors/__init__.py deleted file mode 100644 index c9fba74a0..000000000 --- a/python/pulsing/agent/actors/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace agents (LLM + tools on Pulsing Actors).""" - -from pulsing.agent.actors.actor import AgentActor -from pulsing.agent.actors.npc import Agent, NpcAgent -from pulsing.agent.loop.llm_chat import LlmChat - -__all__ = ["Agent", "AgentActor", "NpcAgent", "LlmChat"] diff --git a/python/pulsing/agent/actors/activity.py b/python/pulsing/agent/actors/activity.py deleted file mode 100644 index 3a2c04bf2..000000000 --- a/python/pulsing/agent/actors/activity.py +++ /dev/null @@ -1,80 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Lightweight per-agent activity snapshot for cluster watch.""" - -from __future__ import annotations - -import time -from typing import Any - -from pulsing.agent.actors.log import append_log - -ActivityState = str # idle | starting | thinking | tool | unknown - - -def _activity_line(state: str, detail: str, tool: str, from_sender: str) -> str: - who = f" from {from_sender}" if from_sender else "" - if state == "tool" and tool: - body = detail or tool - return f"⚙ {tool}: {body}" - if state == "thinking": - return f"… thinking{who}" + (f" — {detail}" if detail else "") - if state == "idle": - return "● idle" - if state == "starting": - return "○ starting" - return f"{state}: {detail or tool or '—'}" - - -def init_activity(agent: Any) -> None: - agent._activity = _snapshot("starting", detail="booting") - - -def set_activity( - agent: Any, - *, - state: ActivityState, - detail: str = "", - from_sender: str = "", - tool: str = "", -) -> None: - prev = getattr(agent, "_activity", None) or {} - now = time.time() - same_state = prev.get("state") == state and prev.get("tool") == tool - agent._activity = { - "state": state, - "detail": (detail or "").strip(), - "from": (from_sender or prev.get("from") or "").strip(), - "tool": (tool or "").strip(), - "since": prev.get("since", now) if same_state else now, - "updated_at": now, - } - if not same_state or (detail or "").strip() != (prev.get("detail") or "").strip(): - append_log( - agent, - _activity_line( - state, - agent._activity["detail"], - agent._activity["tool"], - agent._activity["from"], - ), - ) - - -def get_activity(agent: Any) -> dict[str, Any]: - snap = dict(getattr(agent, "_activity", _snapshot("unknown"))) - snap.setdefault("name", getattr(agent, "_cluster_short_name", "") or "") - snap.setdefault("npc_class", getattr(agent, "_npc_class", "") or "") - snap.setdefault("role", getattr(agent, "_agent_role", "") or "") - return snap - - -def _snapshot(state: ActivityState, *, detail: str = "") -> dict[str, Any]: - now = time.time() - return { - "state": state, - "detail": detail, - "from": "", - "tool": "", - "since": now, - "updated_at": now, - } diff --git a/python/pulsing/agent/actors/actor.py b/python/pulsing/agent/actors/actor.py deleted file mode 100644 index a5c850d4f..000000000 --- a/python/pulsing/agent/actors/actor.py +++ /dev/null @@ -1,142 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace agent actor base: LLM session + tools. Mailbox serializes.""" - -from __future__ import annotations - -import asyncio -import logging -from typing import Any - -from pulsing.agent.actors.activity import set_activity -from pulsing.agent.actors.tool_host import call_tool, stop_isolated_worker -from pulsing.agent.loop.llm_chat import LlmChat - -logger = logging.getLogger(__name__) - - -class AgentActor: - """Shared actor surface: ``chat`` / ``chat_stream`` + ``call_tool``.""" - - async def _emit_text_chunk(self, chunk: str) -> None: - if chunk: - print(chunk, end="", flush=True) - - def _reply(self, out: dict[str, Any]) -> dict[str, Any]: - return { - "ok": out.get("ok", True), - "events": out.get("events", []), - "session_id": self._session.session_id, - "assistant_text": out.get("assistant_text", ""), - "streamed_assistant": bool(out.get("streamed_assistant")), - } - - async def on_start(self, actor_id) -> None: - async with self._on_start_lock: - if self._on_start_done: - return - from pulsing.forge.setup_actors import ensure_forge_actors - - await ensure_forge_actors(self) - cb = self._emit_text_chunk if self._stream_assistant else None - self._llm = LlmChat.from_agent(self, text_stream_callback=cb) - if self._initial_messages: - self._llm.set_messages(self._initial_messages) - self._on_start_done = True - set_activity(self, state="idle") - - async def on_stop(self) -> None: - await stop_isolated_worker(self) - - def get_session_id(self) -> str: - return self._session.session_id - - async def call_tool(self, name: str, kwargs: dict[str, Any]) -> Any: - from pulsing.agent.loop.tool_base import ToolResult - - return await call_tool(self, name, kwargs) - - async def chat( - self, - message: str, - *, - stream_assistant: bool | None = None, - ) -> dict[str, Any]: - if stream_assistant is not None: - self._stream_assistant = bool(stream_assistant) - if self._llm is not None: - cb = self._emit_text_chunk if self._stream_assistant else None - self._llm.set_stream_assistant(self._stream_assistant, cb) - text = (message or "").strip() - if not text: - return { - "ok": True, - "events": [], - "session_id": self._session.session_id, - "assistant_text": "", - "streamed_assistant": False, - } - if self._llm is None: - return {"ok": False, "error": "agent not ready (on_start pending)"} - set_activity(self, state="thinking", detail="LLM turn") - try: - out = await self._llm.respond(text) - finally: - set_activity(self, state="idle") - return self._reply(out) - - async def chat_stream( - self, - message: str, - *, - stream_assistant: bool | None = None, - ): - if stream_assistant is not None: - self._stream_assistant = bool(stream_assistant) - if self._llm is not None: - cb = self._emit_text_chunk if self._stream_assistant else None - self._llm.set_stream_assistant(self._stream_assistant, cb) - text = (message or "").strip() - if not text: - yield {"kind": "_final", **self._reply({"ok": True, "events": []})} - return - if self._llm is None: - yield {"kind": "error", "message": "agent not ready (on_start pending)"} - return - - q: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue() - - async def sink(ev: dict[str, Any]) -> None: - await q.put(ev) - - self._forge_stream_sink = sink - - async def worker() -> None: - try: - out = await self._llm.respond(text, event_sink=sink) - await q.put({"kind": "_final", **out}) - except BaseException as e: - await q.put( - { - "kind": "_final", - "ok": False, - "error": repr(e), - "events": [], - "assistant_text": "", - "streamed_assistant": False, - } - ) - finally: - await q.put(None) - - task = asyncio.create_task(worker()) - try: - while True: - item = await q.get() - if item is None: - break - if item.get("kind") == "_final": - item.update(self._reply(item)) - yield item - finally: - self._forge_stream_sink = None - await task diff --git a/python/pulsing/agent/actors/bootstrap.py b/python/pulsing/agent/actors/bootstrap.py deleted file mode 100644 index 604181896..000000000 --- a/python/pulsing/agent/actors/bootstrap.py +++ /dev/null @@ -1,125 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Attach runtime state to a craft agent actor.""" - -from __future__ import annotations - -import asyncio -from typing import Any - -import pulsing as pul - -from pulsing.agent.actors.activity import init_activity -from pulsing.agent.actors.log import init_log -from pulsing.agent.actors.session import AgentSession -from pulsing.agent.cluster.constants import short_agent_name, full_agent_name -from pulsing.agent.npc.config import NpcConfig -from pulsing.agent.actors.forge_runtime import init_forge_host -from pulsing.agent.loop.constants import ( - CLUSTER_TOOL_NAMES, - FORGE_HOST_TOOL_NAMES, - FORGE_ISOLATED_TOOL_NAMES, - NPC_TOOL_NAMES, - QUEST_TOOL_NAMES, -) -from pulsing.agent.loop.llm_chat import LlmChat -from pulsing.agent.loop.permissions import PermissionChecker -from pulsing.agent.loop.sandbox import normalize_policy -from pulsing.agent.loop.sandbox_manager import SandboxManager -from pulsing.agent.loop.split_tools import build_tools_for_agent - -DEFAULT_SYSTEM_PROMPT = ( - "You are a coding agent with filesystem and shell tools. " - "Prefer small, safe steps. Current working directory context is implied by the user." -) - - -def setup_agent( - agent: Any, config: NpcConfig, *, stream_assistant: bool | None = None -) -> None: - system_prompt, allow, forbid, npc_class_name, personality = ( - config.resolved_profile() - ) - if stream_assistant is None: - stream_assistant = False - - agent._provider = (config.provider or "anthropic").strip().lower() - agent._api_key = config.api_key - agent._base_url = config.base_url - agent._model = config.model - agent._cwd = config.cwd - agent._auto_approve = config.auto_approve - agent._system_prompt = (system_prompt or "").strip() or DEFAULT_SYSTEM_PROMPT - agent._summon_depth = max(0, int(config.summon_depth)) - agent._max_summon_depth = max(1, int(config.max_summon_depth)) - agent._prompt_callback = config.prompt_callback - agent._stream_assistant = stream_assistant - agent._sandbox_policy = normalize_policy(config.sandbox_policy) - agent._dangerously_disable_sandbox = config.dangerously_disable_sandbox - agent._sandbox_mgr = SandboxManager( - agent._sandbox_policy, - dangerously_disable_sandbox=config.dangerously_disable_sandbox, - ) - agent._cluster_short_name = ( - short_agent_name(config.agent_name, workspace_id=config.workspace_id) - if config.agent_name - else "" - ) - agent._workspace_id = (config.workspace_id or "").strip() or None - agent._agent_role = (config.agent_role or "").strip() - agent._agent_description = (config.agent_description or "").strip() - agent._npc_class = npc_class_name - agent._personality = personality - agent._cluster_enabled = bool(agent._cluster_short_name) and bool( - agent._workspace_id - ) - agent._shared_tool_worker = bool(config.shared_tool_worker) - agent._summon_enabled = bool( - agent._workspace_id - and agent._cluster_short_name - and agent._summon_depth < agent._max_summon_depth - ) - agent._lock = asyncio.Lock() - agent._worker_spawn: pul.IsolatedSpawnHandle | None = None - agent._worker_proxy: pul.ActorProxy | None = None - agent._checker = PermissionChecker( - auto_approve=config.auto_approve, - prompt_callback=config.prompt_callback, - ) - tool_list = build_tools_for_agent( - agent._checker, - cwd=config.cwd, - cluster_enabled=agent._cluster_enabled, - summon_enabled=agent._summon_enabled, - tool_allowlist=set(allow) if allow else None, - tool_forbid=set(forbid) if forbid else None, - ) - agent._tools_by_name = {t.name: t for t in tool_list} - agent._local_tools = { - n: t - for n, t in agent._tools_by_name.items() - if n not in FORGE_ISOLATED_TOOL_NAMES - and n not in FORGE_HOST_TOOL_NAMES - and n not in CLUSTER_TOOL_NAMES - and n not in NPC_TOOL_NAMES - and n not in QUEST_TOOL_NAMES - } - agent._session = AgentSession(model=config.model) - agent._forge_events: list[dict[str, Any]] = [] - agent._forge_stream_sink = None - ws = (config.workspace_id or "").strip() - short = agent._cluster_short_name - agent._forge_host_name = ( - full_agent_name(short, workspace_id=ws) if ws and short else None - ) - agent._event_sink_name = None - agent._forge_actors_ready = False - agent._forge_inbox_proxy = None - agent._mcp_hub_name = None - agent._code_cell_registry_name = None - agent._initial_messages: list[dict] = [] - agent._llm: LlmChat | None = None - agent._on_start_done = False - agent._on_start_lock = asyncio.Lock() - init_activity(agent) - init_log(agent) - init_forge_host(agent) diff --git a/python/pulsing/agent/actors/forge_events.py b/python/pulsing/agent/actors/forge_events.py deleted file mode 100644 index 6ed2f0ed8..000000000 --- a/python/pulsing/agent/actors/forge_events.py +++ /dev/null @@ -1,133 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Handle Forge P2P events on workspace Agent.""" - -from __future__ import annotations - -import asyncio -import logging -from typing import Any - -from pulsing.forge.events import ForgeEvent, ForgeEventKind -from pulsing.forge.p2p_transport import tell_forge_event, tell_forge_event_sync - -logger = logging.getLogger(__name__) - - -def forge_event_sink(agent: Any) -> str | None: - name = getattr(agent, "_event_sink_name", None) - if not name: - return None - return str(name).strip() or None - - -async def emit_forge_event(agent: Any, event: ForgeEvent) -> None: - """Deliver a forge event via actor tell (same path as cross-process workers).""" - sink = forge_event_sink(agent) - if not sink: - logger.debug("forge event sink unset; handling locally kind=%s", event.kind) - await handle_forge_event(agent, event.to_dict()) - return - await tell_forge_event(sink, event) - - -def emit_forge_event_sync(agent: Any, event: ForgeEvent) -> None: - """Sync tell from tool threads / Rust callbacks.""" - sink = forge_event_sink(agent) - if not sink: - logger.debug("forge event sink unset; handling locally kind=%s", event.kind) - _schedule_local(agent, event) - return - tell_forge_event_sync(sink, event) - - -def _schedule_local(agent: Any, event: ForgeEvent) -> None: - raw = event.to_dict() - - async def _deliver() -> None: - await handle_forge_event(agent, raw) - - try: - loop = asyncio.get_running_loop() - loop.create_task(_deliver()) - except RuntimeError: - asyncio.run(_deliver()) - - -def make_host_emit(agent: Any): - return lambda event: emit_forge_event_sync(agent, event) - - -async def apply_forge_side_effects(agent: Any, raw: dict[str, Any]) -> None: - """Update session / activity / stream sink without recording events.""" - event = ForgeEvent.from_dict(raw) - - if event.kind == ForgeEventKind.PLAN_UPDATED.value: - session = getattr(agent, "_forge_session", None) - if session is not None: - from pulsing.forge.session import PlanItem, StepStatus - - items = [] - for item in event.payload.get("plan") or []: - status = item.get("status", StepStatus.PENDING) - if isinstance(status, str): - status = StepStatus(status) - items.append(PlanItem(step=str(item.get("step", "")), status=status)) - session.plan = items - - if event.kind == ForgeEventKind.NEW_CONTEXT.value: - session = getattr(agent, "_forge_session", None) - if session is not None: - session.new_context_requested = True - - sink = getattr(agent, "_forge_stream_sink", None) - if sink is not None: - payload = _to_stream_chunk(event) - if payload is not None: - result = sink(payload) - if hasattr(result, "__await__"): - await result - - if event.kind == ForgeEventKind.EXEC_OUTPUT_DELTA.value and hasattr( - agent, "_activity" - ): - chunk = str(event.payload.get("chunk") or "") - if chunk: - detail = chunk.strip().splitlines()[-1][:120] - from pulsing.agent.actors.activity import set_activity - - set_activity( - agent, - state="tool", - detail=detail or "exec…", - tool="exec_command", - ) - - -async def handle_forge_event(agent: Any, raw: dict[str, Any]) -> None: - events = getattr(agent, "_forge_events", None) - if events is None: - agent._forge_events = [] - events = agent._forge_events - events.append(dict(raw)) - await apply_forge_side_effects(agent, raw) - - -def _to_stream_chunk(event: ForgeEvent) -> dict[str, Any] | None: - if event.kind == ForgeEventKind.EXEC_OUTPUT_DELTA.value: - return { - "kind": "forge_exec_delta", - "session_id": event.payload.get("session_id"), - "stream": event.payload.get("stream"), - "chunk": event.payload.get("chunk"), - } - if event.kind == ForgeEventKind.TOOL_BEGIN.value: - return {"kind": "forge_tool_begin", "tool": event.source, **event.payload} - if event.kind == ForgeEventKind.TOOL_END.value: - return {"kind": "forge_tool_end", "tool": event.source, **event.payload} - if event.kind == ForgeEventKind.PLAN_UPDATED.value: - return {"kind": "forge_plan_updated", **event.payload} - if event.kind == ForgeEventKind.NEW_CONTEXT.value: - return {"kind": "forge_new_context"} - if event.kind == ForgeEventKind.USER_INPUT_REQUEST.value: - return {"kind": "forge_user_input_request", **event.payload} - return {"kind": "forge_event", "forge_kind": event.kind, **event.payload} diff --git a/python/pulsing/agent/actors/forge_runtime.py b/python/pulsing/agent/actors/forge_runtime.py deleted file mode 100644 index 320abcf4f..000000000 --- a/python/pulsing/agent/actors/forge_runtime.py +++ /dev/null @@ -1,62 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Attach unified Forge host runtime to workspace Agent.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.agent.actors.forge_events import make_host_emit -from pulsing.agent.actors.forge_session import build_agent_forge_session -from pulsing.forge.backend import ForgeHostConfig, create_host_runtime -from pulsing.forge.events import ForgeEvent -from pulsing.forge.integrated import ForgeHostLink -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE - - -def _tokens_remaining(agent: Any) -> int | None: - session = getattr(agent, "_forge_session", None) - if session is not None: - return session.tokens_remaining() - return None - - -def init_forge_host(agent: Any) -> None: - emit = make_host_emit(agent) - session = build_agent_forge_session(agent, emit) - agent._forge_session = session - - checker = getattr(agent, "_checker", None) - user_input_cb = getattr(checker, "prompt_user_input", None) if checker else None - exec_cb = getattr(checker, "prompt_exec_approval", None) if checker else None - perms_cb = getattr(checker, "prompt_request_permissions", None) if checker else None - plugin_cb = getattr(checker, "prompt_plugin_install", None) if checker else None - auto_approve = bool(getattr(agent, "_auto_approve", False)) - - host_cfg = ForgeHostConfig( - cwd=agent._cwd, - sandbox_policy=agent._sandbox_policy, - dangerously_disable_sandbox=agent._dangerously_disable_sandbox, - auto_approve=auto_approve, - session=session, - ) - - if RUST_FORGE_AVAILABLE: - agent._forge_host = create_host_runtime( - host_cfg, - event_callback=lambda raw: emit(ForgeEvent.from_dict(raw)), - user_input_callback=user_input_cb, - exec_approval_callback=exec_cb, - request_permissions_callback=perms_cb, - tokens_remaining_callback=lambda: _tokens_remaining(agent), - plugin_install_callback=plugin_cb, - ) - else: - agent._forge_host = ForgeHostLink( - cwd=agent._cwd, - sandbox_policy=agent._sandbox_policy, - dangerously_disable_sandbox=agent._dangerously_disable_sandbox, - session=session, - emit=emit, - ) - - agent._forge_worker = None diff --git a/python/pulsing/agent/actors/forge_session.py b/python/pulsing/agent/actors/forge_session.py deleted file mode 100644 index 28b5abb63..000000000 --- a/python/pulsing/agent/actors/forge_session.py +++ /dev/null @@ -1,61 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Agent host ToolSession — plan state + permission prompts.""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Any - -from pulsing.forge.discovery.catalog import ToolCatalog -from pulsing.forge.p2p_session import EmitFn, P2PToolSession -from pulsing.forge.session import PlanItem, UpdatePlanArgs - - -@dataclass -class AgentForgeSession(P2PToolSession): - """Host-side session: local state + P2P forge events.""" - - user_input: Any = None - plugin_install: Any = None - plan: list[PlanItem] = field(default_factory=list) - new_context_requested: bool = False - token_budget: int | None = None - context_window: int = 200_000 - tool_catalog: ToolCatalog = field(default_factory=ToolCatalog) - - def update_plan(self, args: UpdatePlanArgs) -> None: - self.plan = list(args.plan) - super().update_plan(args) - - def request_new_context(self) -> None: - self.new_context_requested = True - super().request_new_context() - - def tokens_remaining(self) -> int | None: - if self.token_budget is not None: - return self.token_budget - agent = getattr(self, "_agent", None) - llm = getattr(agent, "_llm", None) if agent is not None else None - if llm is not None: - return llm.estimate_tokens_remaining(self.context_window) - return None - - def request_plugin_install(self, args: dict[str, Any]) -> bool: - cb = self.plugin_install - if cb is not None: - return bool(cb(args)) - return super().request_plugin_install(args) - - -def build_agent_forge_session(agent: Any, emit: EmitFn | None) -> AgentForgeSession: - checker = getattr(agent, "_checker", None) - user_input_cb = getattr(checker, "prompt_user_input", None) if checker else None - plugin_cb = getattr(checker, "prompt_plugin_install", None) if checker else None - session = AgentForgeSession( - emit=emit, - user_input=user_input_cb, - plugin_install=plugin_cb, - ) - session.tool_catalog.load_codex_plugins() - session._agent = agent # noqa: SLF001 — host back-ref for token estimate - return session diff --git a/python/pulsing/agent/actors/log.py b/python/pulsing/agent/actors/log.py deleted file mode 100644 index cc3f24fd8..000000000 --- a/python/pulsing/agent/actors/log.py +++ /dev/null @@ -1,36 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Per-agent scroll log (in-memory ring buffer).""" - -from __future__ import annotations - -import time -from typing import Any - -_MAX_LINES = 400 - - -def init_log(agent: Any) -> None: - agent._log_seq = 0 - agent._log_lines: list[tuple[int, str]] = [] - - -def append_log(agent: Any, message: str) -> None: - text = (message or "").strip() - if not text: - return - agent._log_seq = int(getattr(agent, "_log_seq", 0)) + 1 - stamp = time.strftime("%H:%M:%S") - agent._log_lines.append((agent._log_seq, f"[{stamp}] {text}")) - if len(agent._log_lines) > _MAX_LINES: - agent._log_lines = agent._log_lines[-_MAX_LINES:] - - -def get_logs(agent: Any, *, since: int = 0) -> dict[str, Any]: - since = max(0, int(since)) - lines = [text for seq, text in agent._log_lines if seq > since] - return { - "name": getattr(agent, "_cluster_short_name", "") or "", - "since": since, - "next": int(getattr(agent, "_log_seq", 0)), - "lines": lines, - } diff --git a/python/pulsing/agent/actors/npc.py b/python/pulsing/agent/actors/npc.py deleted file mode 100644 index 2b6acaf51..000000000 --- a/python/pulsing/agent/actors/npc.py +++ /dev/null @@ -1,157 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace agent — single @remote actor.""" - -from __future__ import annotations - -import asyncio -from typing import Any, Literal - -from pulsing.core.remote import remote - -from pulsing.agent.actors.actor import AgentActor -from pulsing.agent.actors.activity import get_activity, set_activity -from pulsing.agent.actors.log import append_log, get_logs -from pulsing.agent.actors.bootstrap import setup_agent -from pulsing.agent.cluster.constants import full_agent_name -from pulsing.agent.npc.config import NpcConfig - -MessageChannel = Literal["say", "whisper"] - - -def format_incoming(sender: str, body: str, *, channel: MessageChannel) -> str: - s = (sender or "peer").strip() or "peer" - tag = f"{s} whispers" if channel == "whisper" else s - return f"[{tag}]\n{body.strip()}" - - -@remote -class Agent(AgentActor): - """Workspace agent. Spawn via :func:`pulsing.agent.npc.spawn_npc`.""" - - def __init__(self, config: NpcConfig) -> None: - setup_agent(self, config) - - def metadata(self) -> dict[str, str]: - md: dict[str, str] = { - "agent.kind": "workspace", - "agent.name": self._cluster_short_name, - } - if self._npc_class: - md["agent.class"] = self._npc_class - if self._agent_role: - md["agent.role"] = self._agent_role - if self._workspace_id: - md["agent.workspace_id"] = self._workspace_id - return md - - def ping(self) -> dict[str, Any]: - return {"ok": True, "kind": "npc", "name": self._cluster_short_name} - - def get_cluster_info(self) -> dict[str, Any]: - short = self._cluster_short_name - ws = self._workspace_id or "" - return { - "full_name": ( - full_agent_name(short, workspace_id=ws) if short and ws else None - ), - "workspace_id": ws or None, - "role": self._agent_role, - "model": self._model, - "cwd": self._cwd, - "kind": "npc", - "name": short, - "npc_class": self._npc_class, - "summon_depth": self._summon_depth, - "description": self._agent_description, - "provider": self._provider, - "cluster_enabled": self._cluster_enabled, - "shared_tool_worker": self._shared_tool_worker, - } - - def get_activity(self) -> dict[str, Any]: - return get_activity(self) - - def get_logs(self, since: int = 0) -> dict[str, Any]: - return get_logs(self, since=since) - - async def on_forge_event(self, event: dict[str, Any]) -> None: - from pulsing.agent.actors.forge_events import handle_forge_event - - await handle_forge_event(self, event) - - async def on_forge_side_effect(self, event: dict[str, Any]) -> None: - from pulsing.agent.actors.forge_events import apply_forge_side_effects - - await apply_forge_side_effects(self, event) - - async def on_forge_stream_event(self, event: dict[str, Any]) -> None: - from pulsing.agent.actors.forge_events import apply_forge_side_effects - - await apply_forge_side_effects(self, event) - - async def resolve_exec_approval(self, request: dict[str, Any]) -> dict[str, Any]: - checker = getattr(self, "_checker", None) - if checker is None: - return {"decision": "denied"} - decision = checker.prompt_exec_approval(dict(request)) - return {"decision": decision} - - async def resolve_request_permissions(self, args: dict[str, Any]) -> dict[str, Any]: - checker = getattr(self, "_checker", None) - if checker is None: - return {"permissions": {}, "scope": "turn", "strict_auto_review": False} - return checker.prompt_request_permissions(dict(args)) - - def get_forge_events(self, since: int = 0) -> list[dict[str, Any]]: - inbox = getattr(self, "_forge_inbox_proxy", None) - if inbox is not None: - try: - return inbox.get_forge_events(since) - except Exception: - pass - events = getattr(self, "_forge_events", []) - if since <= 0: - return list(events) - return events[since:] - - async def deliver_message( - self, - from_sender: str, - message: str, - *, - channel: MessageChannel = "say", - wait: bool = True, - timeout: float = 600.0, - ) -> dict[str, Any]: - body = (message or "").strip() - if not body: - return {"ok": False, "error": "empty message"} - who = (from_sender or "peer").strip() or "peer" - ch: MessageChannel = "whisper" if channel == "whisper" else "say" - line = format_incoming(who, body, channel=ch) - append_log(self, f"← {ch} {who}: {body[:160]}") - if not wait: - set_activity( - self, state="thinking", detail="queued message", from_sender=who - ) - self.delayed(0).chat(line) - return {"ok": True, "accepted": True, "from": who, "channel": ch} - set_activity(self, state="thinking", detail="incoming message", from_sender=who) - try: - out = await asyncio.wait_for(self.chat(line), timeout=timeout) - except asyncio.TimeoutError: - set_activity(self, state="idle") - append_log(self, f"✗ timed out after {timeout}s") - return { - "ok": False, - "error": f"timed out after {timeout}s", - "from": who, - "channel": ch, - } - text = str(out.get("assistant_text") or "").strip() - if text: - append_log(self, f"→ {text[:240]}") - return {**out, "from": who, "channel": ch} - - -NpcAgent = Agent diff --git a/python/pulsing/agent/actors/session.py b/python/pulsing/agent/actors/session.py deleted file mode 100644 index dfa849aeb..000000000 --- a/python/pulsing/agent/actors/session.py +++ /dev/null @@ -1,15 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""In-memory agent session id (no disk persistence).""" - -from __future__ import annotations - -import uuid - - -class AgentSession: - def __init__(self, *, model: str, session_id: str | None = None) -> None: - self.model = model - self.session_id = session_id or uuid.uuid4().hex[:16] - - def append_message(self, message: dict) -> None: - _ = message diff --git a/python/pulsing/agent/actors/summon_tool.py b/python/pulsing/agent/actors/summon_tool.py deleted file mode 100644 index ccffbee42..000000000 --- a/python/pulsing/agent/actors/summon_tool.py +++ /dev/null @@ -1,94 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Summon tool: spawn NPC and optional whisper round-trip.""" - -from __future__ import annotations - -import json -import uuid -from typing import Any - -import pulsing as pul - -from pulsing.agent.cluster.constants import full_agent_name -from pulsing.agent.loop.tool_base import ToolResult - - -def _parse_wait(kwargs: dict[str, Any]) -> bool: - wait = kwargs.get("wait", True) - if isinstance(wait, str): - return wait.strip().lower() not in ("0", "false", "no", "off") - return bool(wait) - - -async def tool_summon(agent: Any, kwargs: dict[str, Any]) -> ToolResult: - if agent._summon_depth >= agent._max_summon_depth: - return ToolResult(content="Summon: max depth reached.", is_error=True) - goal = str(kwargs.get("goal") or kwargs.get("task") or "").strip() - if not goal: - return ToolResult(content="Summon: goal required.", is_error=True) - ws = agent._workspace_id - if not ws: - return ToolResult(content="Summon: no workspace.", is_error=True) - - child = str(kwargs.get("name") or "").strip() or f"sub-{uuid.uuid4().hex[:6]}" - task_id = str(kwargs.get("task_id") or "").strip() or f"s-{uuid.uuid4().hex[:10]}" - npc_class = str(kwargs.get("npc_class") or "artisan").strip() - wait = _parse_wait(kwargs) - timeout = float(kwargs.get("timeout", 600.0)) - try: - from pulsing.agent.actors import Agent - from pulsing.agent.npc import spawn_npc - from pulsing.agent.npc.config import NpcConfig - - cfg = NpcConfig( - model=str(kwargs.get("model") or agent._model), - cwd=agent._cwd, - provider=agent._provider, - api_key=agent._api_key, - base_url=agent._base_url, - auto_approve=agent._auto_approve, - sandbox_policy=agent._sandbox_policy, - dangerously_disable_sandbox=agent._dangerously_disable_sandbox, - agent_name=child, - workspace_id=ws, - npc_class=npc_class, - personality=str(kwargs.get("personality") or ""), - summon_depth=agent._summon_depth + 1, - max_summon_depth=agent._max_summon_depth, - shared_tool_worker=agent._shared_tool_worker, - ) - await spawn_npc(cfg, public=True) - from_name = agent._cluster_short_name or "parent" - peer = await pul.resolve( - full_agent_name(child, workspace_id=ws), - cls=Agent, - timeout=120.0, - ) - result = await peer.deliver_message( - from_name, - goal, - channel="whisper", - wait=wait, - timeout=timeout, - ) - except Exception as e: - return ToolResult(content=f"Summon failed: {e!r}", is_error=True) - - ok = result.get("ok", True) - status = "completed" if ok and wait else ("accepted" if ok else "failed") - text = str(result.get("assistant_text") or result.get("error") or "")[:8000] - return ToolResult( - content=json.dumps( - { - "task_id": task_id, - "npc": child, - "class": npc_class, - "status": status, - "wait": wait, - "goal": goal, - "assistant_text": text, - }, - ensure_ascii=False, - ), - is_error=not ok, - ) diff --git a/python/pulsing/agent/actors/tool_host.py b/python/pulsing/agent/actors/tool_host.py deleted file mode 100644 index 1305ff8f6..000000000 --- a/python/pulsing/agent/actors/tool_host.py +++ /dev/null @@ -1,201 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tool dispatch + isolated worker.""" - -from __future__ import annotations - -import asyncio -import logging -from typing import Any - -from pulsing.agent.actors.activity import set_activity -from pulsing.agent.actors.forge_events import emit_forge_event -from pulsing.agent.cluster.resolve import dispatch_cluster_tool -from pulsing.forge.backend import ForgeBackend, ForgeIsolatedWorker -from pulsing.forge.config import ToolWorkerConfig -from pulsing.forge.discovery.activate import activate_discovered_tools -from pulsing.forge.events import ForgeEvent -from pulsing.agent.loop.constants import ( - CLUSTER_TOOL_NAMES, - FORGE_HOST_TOOL_NAMES, - FORGE_ISOLATED_TOOL_NAMES, - NPC_TOOL_NAMES, - QUEST_TOOL_NAMES, -) -from pulsing.agent.loop.tool_base import ToolResult - -logger = logging.getLogger(__name__) - - -def _worker_config(agent: Any) -> ToolWorkerConfig: - return ToolWorkerConfig( - cwd=agent._cwd, - sandbox_policy=agent._sandbox_policy, - dangerously_disable_sandbox=agent._dangerously_disable_sandbox, - auto_approve=bool(getattr(agent, "_auto_approve", False)), - event_sink_name=getattr(agent, "_event_sink_name", None), - host_name=getattr(agent, "_forge_host_name", None), - ) - - -def _tool_activity(agent: Any, name: str, kwargs: dict[str, Any]) -> str: - tool = agent._tools_by_name.get(name) - if tool is None: - return name - return tool.get_activity_description(**kwargs) or name - - -def _forge_backend(agent: Any) -> ForgeBackend: - backend = getattr(agent, "_forge_backend", None) - if backend is not None: - return backend - host = getattr(agent, "_forge_host", None) - if host is None: - raise RuntimeError("Forge host runtime not initialized") - worker = getattr(agent, "_forge_worker", None) - backend = ForgeBackend( - host=host, - worker=worker, - event_sink_name=getattr(agent, "_event_sink_name", None), - ) - agent._forge_backend = backend - return backend - - -async def _ensure_forge_worker( - agent: Any, *, reason: str = "startup" -) -> ForgeIsolatedWorker: - worker = getattr(agent, "_forge_worker", None) - if worker is None: - cfg = _worker_config(agent) - if agent._shared_tool_worker and agent._workspace_id: - worker = ForgeIsolatedWorker.shared(cfg, workspace_id=agent._workspace_id) - else: - worker = ForgeIsolatedWorker.dedicated(cfg) - agent._forge_worker = worker - agent._forge_backend = None - await worker.ensure_ready(reason=reason) - return worker - - -async def call_tool(agent: Any, name: str, kwargs: dict[str, Any]) -> ToolResult: - set_activity( - agent, state="tool", detail=_tool_activity(agent, name, kwargs), tool=name - ) - try: - if name in CLUSTER_TOOL_NAMES: - return await dispatch_cluster_tool(agent, name, kwargs) - if name in NPC_TOOL_NAMES: - from pulsing.agent.actors.summon_tool import tool_summon - - return await tool_summon(agent, kwargs) - if name in QUEST_TOOL_NAMES: - from pulsing.agent.loop.quest_tools import tool_quest_report - - return await tool_quest_report(agent, kwargs) - if name in FORGE_HOST_TOOL_NAMES: - return await _host_forge_tool(agent, name, kwargs) - if name in FORGE_ISOLATED_TOOL_NAMES: - return await _isolated_forge_tool(agent, name, kwargs) - tool = agent._local_tools.get(name) - if tool is None: - return ToolResult(content=f"Unknown tool: {name}", is_error=True) - await emit_forge_event(agent, ForgeEvent.tool_begin(name, kwargs)) - out = ToolResult(content="", is_error=True) - try: - out = await asyncio.to_thread(tool.execute, **kwargs) - finally: - await emit_forge_event( - agent, - ForgeEvent.tool_end( - name, - is_error=bool(out.is_error), - content_preview=out.content, - ), - ) - return out - finally: - set_activity(agent, state="thinking", detail="LLM turn", tool="") - - -async def ensure_isolated_worker(agent: Any, *, reason: str = "startup") -> None: - await _ensure_forge_worker(agent, reason=reason) - - -async def _host_forge_tool(agent: Any, name: str, kwargs: dict[str, Any]) -> ToolResult: - backend = _forge_backend(agent) - result = await backend.call_tool(name, kwargs) - if not result.is_error: - if name == "tool_search": - llm = getattr(agent, "_llm", None) - activate_discovered_tools( - agent._tools_by_name, - result.content, - register=llm.register_tool if llm is not None else None, - ) - elif name == "request_plugin_install": - _sync_installed_plugin_tools(agent) - await _refresh_mcp_runtime(agent) - return ToolResult(content=result.content, is_error=result.is_error) - - -async def _isolated_forge_tool( - agent: Any, name: str, kwargs: dict[str, Any] -) -> ToolResult: - await _ensure_forge_worker(agent, reason="tool call") - backend = _forge_backend(agent) - return await backend.call_tool(name, kwargs) - - -def _sync_installed_plugin_tools(agent: Any) -> None: - session = getattr(agent, "_forge_session", None) - if session is None: - return - llm = getattr(agent, "_llm", None) - for entry in session.tool_catalog.deferred: - if entry.name in agent._tools_by_name: - continue - from pulsing.forge.discovery.activate import DeferredDiscoveredTool - - tool = DeferredDiscoveredTool( - name=entry.name, - description=entry.description, - parameters=entry.parameters, - ) - agent._tools_by_name[entry.name] = tool - if llm is not None: - llm.register_tool(tool) - - -def _refresh_mcp_runtime(agent: Any) -> None: - backend = getattr(agent, "_forge_backend", None) - if backend is not None: - backend.refresh_mcp() - session = getattr(agent, "_forge_session", None) - if session is not None: - try: - session.tool_catalog.refresh_from_codex() - except Exception as exc: - logger.warning("MCP catalog refresh failed: %s", exc) - - -async def refresh_mcp_tools(agent: Any) -> list[str]: - from pulsing.forge.mcp.sync import sync_mcp_tools_to_agent - - _refresh_mcp_runtime(agent) - return await sync_mcp_tools_to_agent(agent) - - -async def stop_isolated_worker(agent: Any) -> None: - """Tear down the isolated worker + host runtime (avoid orphaned exec children).""" - worker = getattr(agent, "_forge_worker", None) - if worker is not None: - try: - await worker.close() - except Exception as exc: - logger.warning("isolated worker close failed: %s", exc) - host = getattr(agent, "_forge_host", None) - if host is not None and hasattr(host, "close"): - try: - host.close() - except Exception as exc: - logger.warning("forge host close failed: %s", exc) diff --git a/python/pulsing/agent/cluster/__init__.py b/python/pulsing/agent/cluster/__init__.py deleted file mode 100644 index 87ce7cafe..000000000 --- a/python/pulsing/agent/cluster/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Local agent cluster: gossip discovery and inter-agent messaging.""" - -from pulsing.agent.cluster.constants import ( - full_agent_name, - short_agent_name, - workspace_agent_name, -) -from pulsing.agent.cluster.discovery import list_cluster_agents -from pulsing.agent.cluster.resolve import ( - message_cluster_agent, - resolve_agent, - resolve_craft_agent, -) - -__all__ = [ - "full_agent_name", - "short_agent_name", - "workspace_agent_name", - "list_cluster_agents", - "message_cluster_agent", - "resolve_agent", - "resolve_craft_agent", -] diff --git a/python/pulsing/agent/cluster/activity.py b/python/pulsing/agent/cluster/activity.py deleted file mode 100644 index 3235d4133..000000000 --- a/python/pulsing/agent/cluster/activity.py +++ /dev/null @@ -1,121 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Collect and format live activity across workspace NPCs.""" - -from __future__ import annotations - -import asyncio -import time -from typing import Any - -from pulsing.agent.cluster.discovery import list_cluster_agents -from pulsing.agent.cluster.resolve import resolve_agent - -_STATE_LABEL = { - "idle": "idle", - "starting": "boot", - "thinking": "think", - "tool": "tool", - "unknown": "?", - "offline": "off", -} - - -def _ago(seconds: float) -> str: - if seconds < 1: - return "now" - if seconds < 60: - return f"{int(seconds)}s" - return f"{int(seconds // 60)}m" - - -def format_activity_table( - rows: list[dict[str, Any]], *, title: str = "Cluster activity" -) -> str: - if not rows: - return "(no agents — run `pulsing agent wake` or `pulsing agent spawn NAME`)" - lines = [ - title + ":", - f"{'NPC':<16} {'CLASS':<12} {'STATE':<6} {'FOR':<10} {'AGE':<5} DETAIL", - ] - for r in rows: - state = str(r.get("state") or "unknown") - label = _STATE_LABEL.get(state, state[:6]) - detail = str(r.get("detail") or r.get("error") or "") - tool = str(r.get("tool") or "") - if tool and state == "tool": - detail = f"{tool}: {detail}" if detail else tool - since = float(r.get("since") or r.get("updated_at") or time.time()) - age = _ago(max(0.0, time.time() - since)) - from_who = str(r.get("from") or "—")[:10] - lines.append( - f"{str(r.get('name') or '?'):<16} " - f"{str(r.get('npc_class') or '-'):<12} " - f"{label:<6} " - f"{from_who:<10} " - f"{age:<5} " - f"{detail[:80]}" - ) - return "\n".join(lines) - - -async def _fetch_one( - system: Any, - row: dict[str, Any], - *, - workspace_id: str, - timeout: float, -) -> dict[str, Any]: - name = str(row.get("name") or "") - base = { - "name": name, - "node_id": row.get("node_id"), - "instance_count": row.get("instance_count", 0), - } - if int(row.get("instance_count") or 0) <= 0: - return {**base, "state": "offline", "detail": "no live instance"} - try: - proxy = await resolve_agent( - system, - name, - workspace_id=workspace_id, - timeout=min(timeout, 15.0), - ) - act = await proxy.get_activity() - if isinstance(act, dict): - return {**base, **act} - return {**base, "state": "unknown", "detail": str(act)} - except Exception as e: - return {**base, "state": "unknown", "detail": repr(e)} - - -async def collect_cluster_activity( - system: Any, - *, - workspace_id: str, - local_node_only: bool = False, - timeout: float = 8.0, -) -> list[dict[str, Any]]: - rows = await list_cluster_agents( - system, - workspace_id=workspace_id, - local_node_only=local_node_only, - ) - seen: set[str] = set() - unique: list[dict[str, Any]] = [] - for row in rows: - name = str(row.get("name") or "") - if not name or name in seen: - continue - seen.add(name) - unique.append(row) - if not unique: - return [] - results = await asyncio.gather( - *( - _fetch_one(system, row, workspace_id=workspace_id, timeout=timeout) - for row in unique - ), - ) - out = list(results) - out.sort(key=lambda r: (r.get("state") != "idle", r.get("name") or "")) - return out diff --git a/python/pulsing/agent/cluster/constants.py b/python/pulsing/agent/cluster/constants.py deleted file mode 100644 index 5d841bb30..000000000 --- a/python/pulsing/agent/cluster/constants.py +++ /dev/null @@ -1,52 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Agent naming: workspace-scoped ``//``.""" - -from __future__ import annotations - -from pulsing.forge.naming import DEFAULT_WORKSPACE_PREFIX - -WS_AGENT_PREFIX = f"{DEFAULT_WORKSPACE_PREFIX.strip('/')}/" - - -def workspace_agent_name(workspace_id: str, short: str) -> str: - ws = (workspace_id or "").strip().strip("/") - s = (short or "").strip().strip("/") - if not ws: - raise ValueError("workspace_id must be non-empty") - if not s: - raise ValueError("agent name must be non-empty") - if s.startswith(WS_AGENT_PREFIX): - return s - if s.startswith(f"{WS_AGENT_PREFIX}{ws}/"): - return s - return f"{WS_AGENT_PREFIX}{ws}/{s}" - - -def full_agent_name(short: str, *, workspace_id: str) -> str: - return workspace_agent_name(workspace_id, short) - - -def is_public_npc_name(short: str) -> bool: - """True for player-visible NPC ids (exclude ``_engine``, ``tasks/…`` internals).""" - s = (short or "").strip() - if not s or s.startswith("_") or "/" in s: - return False - return True - - -def workspace_list_prefix(workspace_id: str) -> str: - return f"{WS_AGENT_PREFIX}{workspace_id.strip('/')}/" - - -def short_agent_name(full_or_short: str, *, workspace_id: str | None = None) -> str: - s = (full_or_short or "").strip() - if workspace_id: - pref = workspace_list_prefix(workspace_id) - if s.startswith(pref): - return s[len(pref) :] or s - if s.startswith(WS_AGENT_PREFIX): - rest = s[len(WS_AGENT_PREFIX) :] - if "/" in rest: - return rest.split("/", 1)[1] - return rest or s - return s diff --git a/python/pulsing/agent/cluster/discovery.py b/python/pulsing/agent/cluster/discovery.py deleted file mode 100644 index 0e6cc7fd5..000000000 --- a/python/pulsing/agent/cluster/discovery.py +++ /dev/null @@ -1,107 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Discover cc cluster agents via Pulsing gossip (``all_named_actors``).""" - -from __future__ import annotations - -from typing import Any - -from pulsing.agent.cluster.constants import ( - WS_AGENT_PREFIX, - is_public_npc_name, - workspace_list_prefix, -) - - -def _path_to_name(path_str: str) -> str: - if path_str.startswith("actors/"): - return path_str[7:] - return path_str - - -def _parse_ws_agent(name: str) -> tuple[str, str] | None: - if not name.startswith(WS_AGENT_PREFIX): - return None - rest = name[len(WS_AGENT_PREFIX) :] - if "/" not in rest: - return None - ws_id, short = rest.split("/", 1) - if not ws_id or not short: - return None - return ws_id, short - - -async def list_cluster_agents( - system: Any, - *, - workspace_id: str | None = None, - local_node_only: bool = False, -) -> list[dict[str, Any]]: - """Return agent rows; filter to one workspace when ``workspace_id`` is set.""" - all_named = await system.all_named_actors() - local_nid = str(system.node_id.id) - ws_prefix = workspace_list_prefix(workspace_id) if workspace_id else None - out: list[dict[str, Any]] = [] - - for info in all_named: - path_str = str(info.get("path", "")) - name = _path_to_name(path_str) - parsed = _parse_ws_agent(name) - if parsed is None: - continue - ws_id, short = parsed - if ws_prefix and not name.startswith(ws_prefix): - continue - if workspace_id and ws_id != workspace_id.strip("/"): - continue - if not is_public_npc_name(short): - continue - - instance_count = int(info.get("instance_count", 0) or 0) - if instance_count <= 0: - out.append( - { - "name": short, - "full_name": name, - "instance_count": 0, - "node_id": None, - "actor_id": None, - } - ) - continue - try: - instances = await system.get_named_instances(name) - except Exception: - instances = [] - for inst in instances: - nid = str(inst.get("node_id", "")) - if local_node_only and nid != local_nid: - continue - out.append( - { - "name": short, - "full_name": name, - "instance_count": instance_count, - "node_id": nid, - "actor_id": str(inst.get("actor_id", "")), - } - ) - out.sort(key=lambda r: (r.get("name") or "", r.get("node_id") or "")) - return out - - -def format_agent_table( - rows: list[dict[str, Any]], - *, - workspace_id: str | None = None, -) -> str: - if not rows: - if workspace_id: - return "(no agents in this workspace; try `pulsing agent spawn NAME` or `pulsing agent wake`)" - return "(no cluster agents registered)" - lines = [f"{'NAME':<20} {'NODE':<12} {'ACTOR_ID':<36} INST"] - for r in rows: - lines.append( - f"{r.get('name', ''):<20} {str(r.get('node_id') or '-'):<12} " - f"{str(r.get('actor_id') or '-'):<36} {r.get('instance_count', 0)}" - ) - return "\n".join(lines) diff --git a/python/pulsing/agent/cluster/resolve.py b/python/pulsing/agent/cluster/resolve.py deleted file mode 100644 index eb4f0bc3b..000000000 --- a/python/pulsing/agent/cluster/resolve.py +++ /dev/null @@ -1,136 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace agent resolve via ``pul.resolve`` (gossip names under ``craft/ws/``).""" - -from __future__ import annotations - -from typing import Any - -import pulsing as pul - -from pulsing.agent.cluster.constants import full_agent_name, short_agent_name -from pulsing.agent.cluster.discovery import format_agent_table, list_cluster_agents -from pulsing.agent.loop.tool_base import ToolResult - - -async def resolve_craft_agent( - system: Any, - target: str, - *, - workspace_id: str | None = None, - timeout: float = 120.0, -) -> Any: - _ = system - if not workspace_id: - raise ValueError("workspace_id is required") - from pulsing.agent.actors import Agent - - short = short_agent_name(target, workspace_id=workspace_id) - full = full_agent_name(short, workspace_id=workspace_id) - return await pul.resolve(full, cls=Agent, timeout=timeout) - - -def _tool_result_from_out(out: Any, *, wait: bool) -> ToolResult: - if isinstance(out, dict) and not out.get("ok", True): - return ToolResult(content=str(out.get("error", out)), is_error=True) - if isinstance(out, dict) and wait: - body = str(out.get("assistant_text") or "") - if not body and out.get("events"): - body = str(out.get("events"))[:8000] - return ToolResult(content=body or "(ok, empty reply)") - return ToolResult(content=str(out)) - - -async def message_cluster_agent( - system: Any, - *, - target: str, - message: str, - from_agent: str, - workspace_id: str | None = None, - timeout: float = 600.0, - wait: bool = False, -) -> ToolResult: - """LLM tool: ``resolve`` + ``deliver_message`` (Pulsing ask RPC).""" - text = (message or "").strip() - if not text: - return ToolResult(content="empty message", is_error=True) - try: - proxy = await resolve_agent( - system, - target, - workspace_id=workspace_id, - timeout=min(timeout, 120.0), - ) - except Exception as e: - return ToolResult(content=f"resolve {target!r} failed: {e!r}", is_error=True) - try: - out = await proxy.deliver_message( - from_agent, - text, - channel="whisper", - wait=wait, - timeout=timeout, - ) - except Exception as e: - return ToolResult(content=f"deliver_message failed: {e!r}", is_error=True) - return _tool_result_from_out(out, wait=wait) - - -async def dispatch_cluster_tool( - agent: Any, name: str, kwargs: dict[str, Any] -) -> ToolResult: - if name == "ListClusterAgents": - local_only = bool(kwargs.get("local_only", False)) - rows = await list_cluster_agents( - pul.get_system(), - workspace_id=agent._workspace_id, - local_node_only=local_only, - ) - return ToolResult( - content=format_agent_table(rows, workspace_id=agent._workspace_id) - ) - if name == "MessageClusterAgent": - target = str( - kwargs.get("agent") - or kwargs.get("target") - or kwargs.get("to") - or kwargs.get("name") - or "", - ).strip() - message = str(kwargs.get("message") or kwargs.get("text") or "").strip() - if not target: - return ToolResult( - content="MessageClusterAgent: agent/target/to/name is required.", - is_error=True, - ) - if not message: - return ToolResult( - content="MessageClusterAgent: message/text is required.", - is_error=True, - ) - wait = kwargs.get("wait", False) - if isinstance(wait, str): - wait = wait.strip().lower() not in ("0", "false", "no", "off") - timeout = float(kwargs.get("timeout", 600.0)) - from_name = agent._cluster_short_name or "anonymous" - return await message_cluster_agent( - pul.get_system(), - target=target, - message=message, - from_agent=from_name, - workspace_id=agent._workspace_id, - timeout=timeout, - wait=bool(wait), - ) - return ToolResult(content=f"unknown cluster tool: {name}", is_error=True) - - -# Preferred public name; ``resolve_craft_agent`` kept for backward compatibility. -resolve_agent = resolve_craft_agent - -__all__ = [ - "dispatch_cluster_tool", - "message_cluster_agent", - "resolve_agent", - "resolve_craft_agent", -] diff --git a/python/pulsing/agent/config.py b/python/pulsing/agent/config.py deleted file mode 100644 index 3c9703be6..000000000 --- a/python/pulsing/agent/config.py +++ /dev/null @@ -1,41 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Agent spawn configuration.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.agent.npc.config import ( - AgentConfig, - NpcConfig, - build_npc_prompt, - get_npc_class, - list_npc_classes, -) -from pulsing.agent.npc.loader import NpcClass - -# Public alias; NpcConfig remains for backward compatibility. -__all__ = [ - "AgentConfig", - "NpcClass", - "NpcConfig", - "build_npc_prompt", - "get_npc_class", - "list_npc_classes", - "spawn_agent", -] - - -async def spawn_agent( - config: AgentConfig, - *, - name: str | None = None, - public: bool = True, -) -> Any: - from pulsing.agent.actors import Agent - - return await Agent.spawn( - config=config, - name=name or config.full_name(), - public=public, - ) diff --git a/python/pulsing/agent/host.py b/python/pulsing/agent/host.py deleted file mode 100644 index 21a0653ee..000000000 --- a/python/pulsing/agent/host.py +++ /dev/null @@ -1,8 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace agent actor.""" - -from __future__ import annotations - -from pulsing.agent.actors import Agent, AgentActor, LlmChat, NpcAgent - -__all__ = ["Agent", "AgentActor", "NpcAgent", "LlmChat"] diff --git a/python/pulsing/agent/llm.py b/python/pulsing/agent/llm.py deleted file mode 100644 index e4a37873e..000000000 --- a/python/pulsing/agent/llm.py +++ /dev/null @@ -1,68 +0,0 @@ -"""LLM client management""" - -from __future__ import annotations - -import os -from typing import Any - -_default_llm = None - - -async def llm( - *, - model: str | None = None, - temperature: float = 0.7, - new: bool = False, - **kwargs: Any, -): - """ - Get LLM client (lazy loading). - - Args: - model: Model name, defaults to LLM_MODEL environment variable - temperature: Sampling temperature - new: Whether to create a new instance (instead of reusing singleton) - - Environment: - OPENAI_API_KEY: API key (required) - OPENAI_BASE_URL: API base URL (optional) - LLM_MODEL: Default model name (optional, default: gpt-4o-mini) - - Example: - from pulsing.agent import llm - - client = await llm() - resp = await client.ainvoke("Hello") - """ - global _default_llm - - if not new and _default_llm is not None: - return _default_llm - - try: - from langchain_openai import ChatOpenAI - except ImportError as e: - raise ImportError("pip install langchain-openai") from e - - api_key = os.getenv("OPENAI_API_KEY") - if not api_key: - raise ValueError("OPENAI_API_KEY not set (or use --mock mode)") - - instance = ChatOpenAI( - model=model or os.getenv("LLM_MODEL", "gpt-4o-mini"), - api_key=api_key, - base_url=os.getenv("OPENAI_BASE_URL"), - temperature=temperature, - **kwargs, - ) - - if not new: - _default_llm = instance - - return instance - - -def reset_llm(): - """Reset LLM singleton""" - global _default_llm - _default_llm = None diff --git a/python/pulsing/agent/loop/__init__.py b/python/pulsing/agent/loop/__init__.py deleted file mode 100644 index b82de5fba..000000000 --- a/python/pulsing/agent/loop/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""LLM turn loop, tool routing, and permissions.""" - -from __future__ import annotations - -__all__ = [ - "compact", - "llm_chat", - "llm_client", - "permissions", - "tool_base", - "tools_pkg", -] diff --git a/python/pulsing/agent/loop/cluster_tools.py b/python/pulsing/agent/loop/cluster_tools.py deleted file mode 100644 index 5cbe847b2..000000000 --- a/python/pulsing/agent/loop/cluster_tools.py +++ /dev/null @@ -1,83 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Anthropic tool schemas for cluster peer discovery and messaging.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.agent.loop.tool_base import Tool, ToolResult -from pulsing.agent.loop.tools_pkg import _json_schema_object - - -class ListClusterAgentsTool(Tool): - @property - def name(self) -> str: - return "ListClusterAgents" - - @property - def description(self) -> str: - return ( - "List other agents in the local Pulsing cluster (workspace gossip names). " - "Use before MessageClusterAgent to find peer ids." - ) - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "local_only": { - "type": "boolean", - "description": "If true, only list agents on this node.", - }, - }, - [], - ) - - def is_read_only(self) -> bool: - return False - - def execute(self, **kwargs: Any) -> ToolResult: - raise RuntimeError("ListClusterAgents runs on Agent._cluster_tool.") - - -class MessageClusterAgentTool(Tool): - @property - def name(self) -> str: - return "MessageClusterAgent" - - @property - def description(self) -> str: - return ( - "Send a message to another cluster agent by short name (e.g. coder). " - "The peer runs an LLM chat round; set wait=true to block for a reply." - ) - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "agent": { - "type": "string", - "description": "Target agent short name (also target/to/name).", - }, - "message": { - "type": "string", - "description": "User-style instruction for the peer agent.", - }, - "wait": { - "type": "boolean", - "description": "Block until peer finishes (default false; use true only when reply needed).", - }, - "timeout": { - "type": "number", - "description": "Max seconds to wait for peer reply (default 600).", - }, - }, - ["message"], - ) - - def is_read_only(self) -> bool: - return False - - def execute(self, **kwargs: Any) -> ToolResult: - raise RuntimeError("MessageClusterAgent runs on Agent._cluster_tool.") diff --git a/python/pulsing/agent/loop/compact.py b/python/pulsing/agent/loop/compact.py deleted file mode 100644 index 366eae4e0..000000000 --- a/python/pulsing/agent/loop/compact.py +++ /dev/null @@ -1,21 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""MVP transcript compaction by message count (not token-aware).""" - -from __future__ import annotations - - -def maybe_compact(messages: list[dict], max_messages: int = 40) -> list[dict]: - """Return a shallow-truncated copy when ``len(messages) > max_messages``. - - **MVP:** keep the first two entries (warm-up / system-like prefix) - and the most recent tail; drop a contiguous slice from the middle so the - result length is at most ``max_messages``. This preserves a short prefix and - fresh context without token-aware summarization. - """ - if len(messages) <= max_messages: - return messages - head_keep = min(2, max_messages) - tail_keep = max_messages - head_keep - if tail_keep < 1: - return messages[-max_messages:] - return list(messages[:head_keep]) + list(messages[-tail_keep:]) diff --git a/python/pulsing/agent/loop/constants.py b/python/pulsing/agent/loop/constants.py deleted file mode 100644 index ab94f6569..000000000 --- a/python/pulsing/agent/loop/constants.py +++ /dev/null @@ -1,21 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Shared tool name sets for craft runtime routing.""" - -from __future__ import annotations - -from pulsing.forge.integrated import ( - FORGE_HOST_TOOL_NAMES, - FORGE_ISOLATED_TOOL_NAMES, - FORGE_TOOL_NAMES, -) - -# Back-compat alias: all Forge tools that run in ToolWorkerActor. -ISOLATED_TOOL_NAMES: frozenset[str] = FORGE_ISOLATED_TOOL_NAMES - -CLUSTER_TOOL_NAMES: frozenset[str] = frozenset( - {"ListClusterAgents", "MessageClusterAgent"}, -) - -NPC_TOOL_NAMES: frozenset[str] = frozenset({"Summon"}) - -QUEST_TOOL_NAMES: frozenset[str] = frozenset({"QuestReport"}) diff --git a/python/pulsing/agent/loop/demo_llm.py b/python/pulsing/agent/loop/demo_llm.py deleted file mode 100644 index 68c5dbfbf..000000000 --- a/python/pulsing/agent/loop/demo_llm.py +++ /dev/null @@ -1,164 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Offline demo LLM — scripted replies and tool calls for ``pulsing agent demo``.""" - -from __future__ import annotations - -import re -import uuid -from typing import Any, Iterator - -from pulsing.agent.loop.llm_client import LLMMessage, LLMUsage - -_DEMO_PEERS = ("bard", "smith", "sage", "guide") - - -def _is_tool_result_user_message(msg: dict[str, Any]) -> bool: - content = msg.get("content") - if not isinstance(content, list) or not content: - return False - return all( - isinstance(block, dict) and block.get("type") == "tool_result" - for block in content - ) - - -def _last_user_text(messages: list[dict[str, Any]]) -> str: - for msg in reversed(messages): - if msg.get("role") != "user": - continue - content = msg.get("content") - if isinstance(content, str): - return content.strip() - if isinstance(content, list): - if _is_tool_result_user_message(msg): - continue - parts: list[str] = [] - for block in content: - if isinstance(block, dict) and block.get("type") == "text": - parts.append(str(block.get("text") or "")) - return " ".join(parts).strip() - return "" - - -def _tool_names(tools: list[dict[str, Any]]) -> set[str]: - out: set[str] = set() - for t in tools or []: - name = t.get("name") - if name: - out.add(str(name)) - return out - - -def plan_demo_turn( - messages: list[dict[str, Any]], - tools: list[dict[str, Any]], -) -> dict[str, Any]: - # After tool results, finish with a short text reply (avoid infinite tool loops). - if messages and _is_tool_result_user_message(messages[-1]): - original = _last_user_text(messages) - snippet = re.sub(r"\s+", " ", original)[:100] - return { - "kind": "text", - "text": f"(demo) Finished tool run for: {snippet or 'your request'}.", - } - - text = _last_user_text(messages) - lower = text.lower() - allowed = _tool_names(tools) - - if any(k in lower for k in ("glob", "files", "list project", "directory")): - if "Glob" in allowed: - return { - "kind": "tool", - "name": "Glob", - "input": {"pattern": "*", "path": "."}, - } - - if any(k in lower for k in ("read", "readme", "summary")): - if "Read" in allowed: - return { - "kind": "tool", - "name": "Read", - "input": {"file_path": "README.md"}, - } - - if any(k in lower for k in ("quest", "puzzle", "unit-test", "questreport")): - if "QuestReport" in allowed: - return { - "kind": "tool", - "name": "QuestReport", - "input": { - "quest_id": "unit-tests", - "status": "in_progress", - "note": "demo chatter", - }, - } - - if "messageclusteragent" in lower or "coordinate" in lower or "peer" in lower: - if "MessageClusterAgent" in allowed: - target = next((p for p in _DEMO_PEERS if p in lower), "smith") - return { - "kind": "tool", - "name": "MessageClusterAgent", - "input": { - "agent": target, - "message": "Demo ping — reply in one short sentence.", - "wait": False, - }, - } - - snippet = re.sub(r"\s+", " ", text)[:100] - return {"kind": "text", "text": f"(demo) Noted: {snippet or '(empty)'}"} - - -class _DemoStream: - """Anthropic-shaped stream context for :class:`LLMClient`.""" - - def __init__( - self, - *, - model: str, - max_tokens: int, - messages: list[dict[str, Any]], - system: str | None, - tools: list[dict[str, Any]], - ) -> None: - _ = model, max_tokens, system - self._plan = plan_demo_turn(messages, tools) - self._text = ( - self._plan.get("text", "") if self._plan.get("kind") == "text" else "" - ) - self.text_stream: Iterator[str] = iter(()) - - def __enter__(self) -> _DemoStream: - if self._text: - self.text_stream = iter([self._text]) - else: - self.text_stream = iter(()) - return self - - def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None: - return False - - def close(self) -> None: - pass - - def get_final_message(self) -> LLMMessage: - if self._plan.get("kind") == "tool": - content = [ - { - "type": "tool_use", - "id": f"demo-{uuid.uuid4().hex[:12]}", - "name": self._plan["name"], - "input": dict(self._plan.get("input") or {}), - }, - ] - stop = "tool_use" - else: - content = [{"type": "text", "text": self._text}] - stop = "end_turn" - return LLMMessage( - content=content, - usage=LLMUsage(input_tokens=1, output_tokens=max(1, len(self._text) // 4)), - stop_reason=stop, - ) diff --git a/python/pulsing/agent/loop/deps.py b/python/pulsing/agent/loop/deps.py deleted file mode 100644 index e8ca4c4c0..000000000 --- a/python/pulsing/agent/loop/deps.py +++ /dev/null @@ -1,38 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Optional dependency checks for Craft LLM providers.""" - -from __future__ import annotations - -import sys - - -def _require_anthropic() -> None: - try: - import anthropic # noqa: F401 - except ImportError: - print( - 'Missing optional dependency. Install with: pip install "pulsing[agent]"', - file=sys.stderr, - ) - sys.exit(1) - - -def _require_openai() -> None: - try: - import openai # noqa: F401 - except ImportError: - print( - 'OpenAI provider requires: pip install "pulsing[agent]"', - file=sys.stderr, - ) - sys.exit(1) - - -def require_provider_deps(provider: str) -> None: - p = (provider or "anthropic").strip().lower() - if p == "demo": - return - if p == "openai": - _require_openai() - else: - _require_anthropic() diff --git a/python/pulsing/agent/loop/forge_tools.py b/python/pulsing/agent/loop/forge_tools.py deleted file mode 100644 index 213033abf..000000000 --- a/python/pulsing/agent/loop/forge_tools.py +++ /dev/null @@ -1,704 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""LLM schemas for the unified Pulsing Forge tool surface.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.agent.loop.tool_base import Tool -from pulsing.agent.loop.tools_pkg import ( - BashTool, - EditTool, - GlobTool, - GrepTool, - ReadTool, - WriteTool, - _json_schema_object, -) -from pulsing.forge.integrated import FORGE_TOOL_NAMES - - -class ShellCommandTool(Tool): - @property - def name(self) -> str: - return "shell_command" - - @property - def description(self) -> str: - return "Run a shell command (Codex-compatible: command, workdir, timeout_ms, sandbox_permissions)." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "command": {"type": "string"}, - "workdir": {"type": "string"}, - "timeout_ms": {"type": "integer", "minimum": 1000}, - "login": {"type": "boolean"}, - "sandbox_permissions": { - "type": "string", - "enum": ["require_escalated", "with_additional_permissions"], - }, - }, - ["command"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("shell_command runs in Forge worker") - - -class ExecCommandTool(Tool): - @property - def name(self) -> str: - return "exec_command" - - @property - def description(self) -> str: - return "Start a unified exec session (PTY by default). Returns session_id while running." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "cmd": {"type": "string"}, - "workdir": {"type": "string"}, - "tty": {"type": "boolean"}, - "yield_time_ms": {"type": "integer"}, - "max_output_tokens": {"type": "integer"}, - }, - ["cmd"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("exec_command runs in Forge worker") - - -class WriteStdinTool(Tool): - @property - def name(self) -> str: - return "write_stdin" - - @property - def description(self) -> str: - return "Write to a unified exec session stdin (or send \\x03 to interrupt)." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "session_id": {"type": "integer"}, - "chars": {"type": "string"}, - "yield_time_ms": {"type": "integer"}, - }, - ["session_id", "chars"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("write_stdin runs in Forge worker") - - -class ApplyPatchTool(Tool): - @property - def name(self) -> str: - return "apply_patch" - - @property - def description(self) -> str: - return "Apply a structured patch to the workspace." - - @property - def input_schema(self) -> dict: - return _json_schema_object({"patch": {"type": "string"}}, ["patch"]) - - def execute(self, **kwargs: Any): - raise RuntimeError("apply_patch runs in Forge worker") - - -class ViewImageTool(Tool): - @property - def name(self) -> str: - return "view_image" - - @property - def description(self) -> str: - return "Attach a local image for the model (returns structured content_items)." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "path": {"type": "string"}, - "detail": {"type": "string", "enum": ["high", "original"]}, - }, - ["path"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("view_image runs in Forge worker") - - -class UpdatePlanTool(Tool): - @property - def name(self) -> str: - return "update_plan" - - @property - def description(self) -> str: - return "Update the collaborative task plan." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "explanation": {"type": "string"}, - "plan": { - "type": "array", - "items": { - "type": "object", - "properties": { - "step": {"type": "string"}, - "status": { - "type": "string", - "enum": ["pending", "in_progress", "completed"], - }, - }, - "required": ["step", "status"], - }, - }, - }, - ["plan"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("update_plan runs on Forge host") - - -class NewContextTool(Tool): - @property - def name(self) -> str: - return "new_context" - - @property - def description(self) -> str: - return "Request a fresh context window without summarizing history." - - @property - def input_schema(self) -> dict: - return _json_schema_object({}) - - def execute(self, **kwargs: Any): - raise RuntimeError("new_context runs on Forge host") - - -class GetContextRemainingTool(Tool): - @property - def name(self) -> str: - return "get_context_remaining" - - @property - def description(self) -> str: - return "Report remaining token budget if configured." - - @property - def input_schema(self) -> dict: - return _json_schema_object({}) - - def execute(self, **kwargs: Any): - raise RuntimeError("get_context_remaining runs on Forge host") - - -class RequestUserInputTool(Tool): - @property - def name(self) -> str: - return "request_user_input" - - @property - def description(self) -> str: - return "Ask the user structured questions and wait for answers (Codex-compatible schema)." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "questions": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": {"type": "string"}, - "header": {"type": "string"}, - "question": {"type": "string"}, - "isOther": {"type": "boolean"}, - "isSecret": {"type": "boolean"}, - "options": { - "type": "array", - "items": { - "type": "object", - "properties": { - "label": {"type": "string"}, - "description": {"type": "string"}, - }, - "required": ["label"], - }, - }, - }, - "required": ["id", "header", "question"], - }, - }, - "autoResolutionMs": { - "type": "integer", - "minimum": 60000, - "maximum": 240000, - "description": "Optional auto-resolve window (ms). On timeout, use first/recommended option per question.", - }, - }, - ["questions"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("request_user_input runs on Forge host") - - -class ToolSearchTool(Tool): - @property - def name(self) -> str: - return "tool_search" - - @property - def description(self) -> str: - return "Search deferred tools (BM25) before loading them into the session." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "query": {"type": "string"}, - "limit": {"type": "integer", "minimum": 1, "maximum": 32}, - }, - ["query"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("tool_search runs on Forge host") - - -class ListAvailablePluginsTool(Tool): - @property - def name(self) -> str: - return "list_available_plugins_to_install" - - @property - def description(self) -> str: - return ( - "List Codex-compatible plugins available to install from local plugin dirs." - ) - - @property - def input_schema(self) -> dict: - return _json_schema_object({}) - - def execute(self, **kwargs: Any): - raise RuntimeError("list_available_plugins_to_install runs on Forge host") - - -class RequestPluginInstallTool(Tool): - @property - def name(self) -> str: - return "request_plugin_install" - - @property - def description(self) -> str: - return "Request user approval to install a Codex-compatible plugin and register its tools." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "tool_type": {"type": "string", "enum": ["connector", "plugin"]}, - "action_type": {"type": "string", "enum": ["install", "enable"]}, - "tool_id": {"type": "string"}, - "suggest_reason": {"type": "string"}, - }, - ["tool_type", "action_type", "tool_id", "suggest_reason"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("request_plugin_install runs on Forge host") - - -class RequestPermissionsTool(Tool): - @property - def name(self) -> str: - return "request_permissions" - - @property - def description(self) -> str: - return "Request additional filesystem/network permissions (Codex-aligned)." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "reason": {"type": "string"}, - "permissions": { - "type": "object", - "properties": { - "network": {"type": "object"}, - "file_system": {"type": "object"}, - }, - }, - }, - ["permissions"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("request_permissions runs on Forge host") - - -class ListMcpResourcesTool(Tool): - @property - def name(self) -> str: - return "list_mcp_resources" - - @property - def description(self) -> str: - return "List MCP resources from configured servers." - - @property - def input_schema(self) -> dict: - return _json_schema_object({}) - - def execute(self, **kwargs: Any): - raise RuntimeError("list_mcp_resources runs on Forge host") - - -class ListMcpResourceTemplatesTool(Tool): - @property - def name(self) -> str: - return "list_mcp_resource_templates" - - @property - def description(self) -> str: - return "List MCP resource URI templates from configured servers." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "server": {"type": "string", "description": "MCP server name"}, - "cursor": {"type": "string", "description": "Pagination cursor"}, - }, - ["server"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("list_mcp_resource_templates runs on Forge host") - - -class ReadMcpResourceTool(Tool): - @property - def name(self) -> str: - return "read_mcp_resource" - - @property - def description(self) -> str: - return "Read an MCP resource by URI." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "server": {"type": "string", "description": "MCP server name"}, - "uri": {"type": "string", "description": "Resource URI"}, - }, - ["server", "uri"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("read_mcp_resource runs on Forge host") - - -class ExecTool(Tool): - @property - def name(self) -> str: - return "exec" - - @property - def description(self) -> str: - return "Run Python source in Code Mode (returns cell_id while running)." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "source": {"type": "string"}, - "yield_time_ms": {"type": "integer"}, - "max_output_tokens": {"type": "integer"}, - }, - ["source"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("exec runs on Forge host") - - -class WaitTool(Tool): - @property - def name(self) -> str: - return "wait" - - @property - def description(self) -> str: - return "Wait for a Code Mode cell or terminate it." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "cell_id": {"type": "string"}, - "yield_time_ms": {"type": "integer"}, - "max_tokens": {"type": "integer"}, - "terminate": {"type": "boolean"}, - }, - ["cell_id"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("wait runs on Forge host") - - -class WebRunTool(Tool): - @property - def name(self) -> str: - return "web.run" - - @property - def description(self) -> str: - return "Client web search / open / find (Codex SearchCommands wire)." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "search_query": {"type": "string"}, - "image_query": {"type": "string"}, - "open": { - "type": "array", - "items": { - "type": "object", - "properties": { - "ref_id": {"type": "string"}, - "url": {"type": "string"}, - }, - }, - }, - "find": {"type": "array", "items": {"type": "object"}}, - }, - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("web.run runs on Forge host") - - -class SkillsListTool(Tool): - @property - def name(self) -> str: - return "skills.list" - - @property - def description(self) -> str: - return "List available agent skills in the workspace." - - @property - def input_schema(self) -> dict: - return _json_schema_object({}) - - def execute(self, **kwargs: Any): - raise RuntimeError("skills.list runs on Forge host") - - -class SkillsReadTool(Tool): - @property - def name(self) -> str: - return "skills.read" - - @property - def description(self) -> str: - return "Read a skill prompt by name or path." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "name": {"type": "string"}, - "path": {"type": "string"}, - }, - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("skills.read runs on Forge host") - - -class MemoriesListTool(Tool): - @property - def name(self) -> str: - return "memories.list" - - @property - def description(self) -> str: - return "List memory files under the Codex memories root." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "path": {"type": "string"}, - "cursor": {"type": "string"}, - "max_results": {"type": "integer"}, - }, - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("memories.list runs on Forge host") - - -class MemoriesReadTool(Tool): - @property - def name(self) -> str: - return "memories.read" - - @property - def description(self) -> str: - return "Read a memory file with optional line/token limits." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "path": {"type": "string"}, - "line_offset": {"type": "integer"}, - "max_lines": {"type": "integer"}, - "max_tokens": {"type": "integer"}, - }, - ["path"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("memories.read runs on Forge host") - - -class MemoriesSearchTool(Tool): - @property - def name(self) -> str: - return "memories.search" - - @property - def description(self) -> str: - return "Search memory files by query." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "query": {"type": "string"}, - "queries": {"type": "array", "items": {"type": "string"}}, - "path": {"type": "string"}, - "cursor": {"type": "string"}, - "max_results": {"type": "integer"}, - }, - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("memories.search runs on Forge host") - - -class MemoriesAddAdHocNoteTool(Tool): - @property - def name(self) -> str: - return "memories.add_ad_hoc_note" - - @property - def description(self) -> str: - return "Append an ad-hoc note to the memories store." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "content": {"type": "string"}, - "path": {"type": "string"}, - }, - ["content"], - ) - - def execute(self, **kwargs: Any): - raise RuntimeError("memories.add_ad_hoc_note runs on Forge host") - - -class WebSearchTool(Tool): - @property - def name(self) -> str: - return "web_search" - - @property - def description(self) -> str: - return ( - "Hosted Provider web search (enable in model config; not executed locally)." - ) - - @property - def input_schema(self) -> dict: - return _json_schema_object({"query": {"type": "string"}}, ["query"]) - - def is_read_only(self) -> bool: - return True - - def execute(self, **kwargs: Any): - raise RuntimeError("web_search runs on the LLM provider") - - -def all_forge_tool_templates() -> list[Tool]: - return [ - ReadTool(), - GlobTool(), - GrepTool(), - EditTool(), - WriteTool(), - BashTool(), - ShellCommandTool(), - ExecCommandTool(), - WriteStdinTool(), - ApplyPatchTool(), - ViewImageTool(), - UpdatePlanTool(), - NewContextTool(), - GetContextRemainingTool(), - RequestUserInputTool(), - RequestPermissionsTool(), - ToolSearchTool(), - ListAvailablePluginsTool(), - RequestPluginInstallTool(), - ListMcpResourcesTool(), - ListMcpResourceTemplatesTool(), - ReadMcpResourceTool(), - ExecTool(), - WaitTool(), - WebRunTool(), - SkillsListTool(), - SkillsReadTool(), - MemoriesListTool(), - MemoriesReadTool(), - MemoriesSearchTool(), - MemoriesAddAdHocNoteTool(), - WebSearchTool(), - ] - - -def assert_forge_tool_coverage() -> None: - from pulsing.forge.tool_coverage import ( - assert_forge_tool_coverage as _assert_registry, - ) - - _assert_registry() - names = {t.name for t in all_forge_tool_templates()} - assert names == set(FORGE_TOOL_NAMES), (names, FORGE_TOOL_NAMES) diff --git a/python/pulsing/agent/loop/llm_blocks.py b/python/pulsing/agent/loop/llm_blocks.py deleted file mode 100644 index e95afe1b2..000000000 --- a/python/pulsing/agent/loop/llm_blocks.py +++ /dev/null @@ -1,49 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Shared LLM tool-use block helpers.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.agent.loop.tool_base import ToolResult - - -class AbortedError(Exception): - """Turn aborted via ``abort()`` (standard abort semantics).""" - - -def tool_result_dict(tid: str, result: ToolResult) -> dict[str, Any]: - d: dict[str, Any] = { - "type": "tool_result", - "tool_use_id": tid, - "content": result.content, - } - if result.is_error: - d["is_error"] = True - return d - - -def block_type(block: Any) -> str | None: - if isinstance(block, dict): - return str(block.get("type")) if block.get("type") is not None else None - return getattr(block, "type", None) - - -def block_name(block: Any) -> str: - if isinstance(block, dict): - return str(block.get("name", "")) - return str(getattr(block, "name", "")) - - -def block_id(block: Any) -> str: - if isinstance(block, dict): - return str(block.get("id", "")) - return str(getattr(block, "id", "")) - - -def block_input(block: Any) -> dict[str, Any]: - if isinstance(block, dict): - value = block.get("input", {}) - else: - value = getattr(block, "input", {}) - return dict(value) if isinstance(value, dict) else {} diff --git a/python/pulsing/agent/loop/llm_chat.py b/python/pulsing/agent/loop/llm_chat.py deleted file mode 100644 index c3e986c92..000000000 --- a/python/pulsing/agent/loop/llm_chat.py +++ /dev/null @@ -1,705 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""LLM multi-turn chat loop: streaming in a worker thread; tools via :class:`AgentToolBackend`.""" - -from __future__ import annotations - -import asyncio -import inspect -import json -import os -import random -import time -from collections.abc import Awaitable, Callable -from typing import Any, Protocol, runtime_checkable - -from pulsing.agent.loop.compact import maybe_compact -from pulsing.agent.loop.llm_blocks import ( - AbortedError, - block_id as _block_id, - block_input as _block_input, - block_name as _block_name, - block_type as _block_type, - tool_result_dict as _tool_result_dict, -) -from pulsing.agent.loop.llm_client import LLMClient -from pulsing.agent.loop.permissions import PermissionChecker -from pulsing.agent.loop.tool_base import Tool, ToolResult - -_MAX_RETRIES = 5 -_BASE_DELAY = 0.5 -_MAX_DELAY = 16.0 -_JITTER_FACTOR = 0.25 - - -def _compute_retry_delay(attempt: int) -> float: - delay = min(_BASE_DELAY * (2**attempt), _MAX_DELAY) - jitter = delay * random.uniform(0, _JITTER_FACTOR) - return delay + jitter - - -@runtime_checkable -class AgentToolBackend(Protocol): - async def call_tool(self, name: str, kwargs: dict[str, Any]) -> ToolResult: ... - - -TextStreamCallback = Callable[[str], Awaitable[None] | None] - -# Optional per-event hook for :meth:`respond` (e.g. ``chat_stream`` over RPC). -StreamEventSink = Callable[[dict[str, Any]], Any] - - -class LlmChat: - """LLM chat loop: optional incremental assistant streaming via thread → ``asyncio.Queue``. - - Anthropic ``messages.stream`` stays synchronous; a worker thread pushes text chunks into - an asyncio queue while the event loop consumes chunks and invokes ``text_stream_callback``. - """ - - def __init__( - self, - backend: AgentToolBackend, - tools: dict[str, Tool], - permission_checker: PermissionChecker, - *, - provider: str = "anthropic", - model: str, - max_tokens: int = 8192, - api_key: str | None = None, - base_url: str | None = None, - system_prompt: str = "", - session_store: Any | None = None, - stream_assistant: bool = True, - text_stream_callback: TextStreamCallback | None = None, - ) -> None: - self._backend = backend - self._tools = tools - self._permissions = permission_checker - self._provider = provider - self._model = model - self._max_tokens = max_tokens - self._client = LLMClient(provider=provider, api_key=api_key, base_url=base_url) - self._system_prompt = system_prompt - self._messages: list[dict[str, Any]] = [] - self._aborted = False - self._user_msg_start: int | None = None - self._session_store = session_store - self._stream_assistant = stream_assistant - self._text_stream_callback = text_stream_callback - - @classmethod - def from_agent( - cls, agent: Any, *, text_stream_callback: TextStreamCallback | None - ) -> LlmChat: - if agent._provider == "demo": - ak = None - bu = None - elif agent._provider == "openai": - ak = agent._api_key or os.environ.get("OPENAI_API_KEY") - bu = agent._base_url or os.environ.get("OPENAI_BASE_URL") - else: - ak = agent._api_key or os.environ.get("ANTHROPIC_API_KEY") - bu = agent._base_url or os.environ.get("ANTHROPIC_BASE_URL") - - return cls( - agent, - agent._tools_by_name, - agent._checker, - provider=agent._provider, - model=agent._model, - api_key=ak, - base_url=bu, - system_prompt=agent._system_prompt, - session_store=agent._session, - stream_assistant=agent._stream_assistant, - text_stream_callback=text_stream_callback, - ) - - def get_messages(self) -> list[dict[str, Any]]: - return list(self._messages) - - def set_messages(self, messages: list[dict[str, Any]]) -> None: - self._messages = [ - {"role": m["role"], "content": m.get("content", "")} for m in messages - ] - - def _persist(self, message: dict[str, Any]) -> None: - if self._session_store is not None: - try: - self._session_store.append_message(message) - except Exception: - pass - - def rollback_pending(self) -> None: - if self._user_msg_start is not None: - del self._messages[self._user_msg_start :] - self._user_msg_start = None - - def set_stream_assistant( - self, - enabled: bool, - text_stream_callback: TextStreamCallback | None, - ) -> None: - self._stream_assistant = enabled - self._text_stream_callback = text_stream_callback - - def set_system_prompt(self, text: str) -> None: - """Update system / role instructions for subsequent LLM calls.""" - self._system_prompt = (text or "").strip() - - def register_tool(self, tool: Tool) -> None: - """Add a deferred/discovered tool for subsequent LLM turns.""" - self._tools[tool.name] = tool - - def estimate_tokens_remaining(self, context_window: int = 200_000) -> int | None: - """Rough token budget estimate from transcript size.""" - used = 0 - for msg in self._messages: - content = msg.get("content", "") - if isinstance(content, str): - used += max(1, len(content) // 4) - elif isinstance(content, list): - used += max(1, len(json.dumps(content, default=str)) // 4) - remaining = context_window - used - self._max_tokens - return max(0, remaining) - - def append_synthetic_user_message(self, content: str) -> None: - """Append a user message (e.g. inter-agent note) before the next LLM round.""" - msg = {"role": "user", "content": content} - self._messages.append(msg) - self._persist(msg) - - def _sync_llm_round(self) -> tuple[Any | None, list[Any], list[str]]: - """Run one assistant generation (with retries) in a sync context. - - Returns ``(final, tool_uses, sidecar_errors)`` where ``sidecar_errors`` are - non-fatal notices (e.g. max_tokens truncation). - """ - sidecar: list[str] = [] - final = None - tool_uses: list[Any] = [] - - for attempt in range(_MAX_RETRIES): - tool_uses = [] - try: - self._messages = maybe_compact(self._messages) - tool_schemas = [t.to_api_schema() for t in self._tools.values()] - stream_obj = self._client.stream_messages( - model=self._model, - max_tokens=self._max_tokens, - system=self._system_prompt, - tools=tool_schemas, - messages=self._messages, - ) - with stream_obj as stream: - acc: list[str] = [] - for text in stream.text_stream: - if self._aborted: - raise AbortedError - acc.append(text) - _ = "".join(acc) - if self._aborted: - raise AbortedError - final_msg = stream.get_final_message() - final = final_msg - if final.stop_reason == "max_tokens": - sidecar.append("Response truncated: max_tokens.") - for block in final.content: - if _block_type(block) == "tool_use": - tool_uses.append(block) - break - except AbortedError: - raise - except Exception as e: - if self._client.is_authentication_error(e): - self._messages.pop() - raise _FatalLLM(str(e), pop_user=True, kind="auth") from e - if self._client.is_retryable_error(e): - if attempt < _MAX_RETRIES - 1: - wait = _compute_retry_delay(attempt) - sidecar.append( - f"API error, retrying in {wait:.1f}s… ({self._client.error_message(e)})", - ) - time.sleep(wait) - continue - self._messages.pop() - raise _FatalLLM( - f"API error after {_MAX_RETRIES} retries: {self._client.error_message(e)}", - pop_user=True, - kind="api", - ) from e - if self._client.is_api_error(e): - self._messages.pop() - raise _FatalLLM( - f"API error: {self._client.error_message(e)}", - pop_user=True, - kind="api", - ) from e - if self._aborted: - raise AbortedError from e - raise - return final, tool_uses, sidecar - - def _sync_produce_llm_to_queue( - self, - loop: asyncio.AbstractEventLoop, - q: asyncio.Queue[Any], - ) -> None: - """Run retrying LLM stream in a worker thread; forward chunks via ``call_soon_threadsafe``.""" - - def _put(item: Any) -> None: - try: - loop.call_soon_threadsafe(q.put_nowait, item) - except RuntimeError: - pass - - for attempt in range(_MAX_RETRIES): - tool_uses: list[Any] = [] - sidecar: list[str] = [] - try: - self._messages = maybe_compact(self._messages) - tool_schemas = [t.to_api_schema() for t in self._tools.values()] - stream_obj = self._client.stream_messages( - model=self._model, - max_tokens=self._max_tokens, - system=self._system_prompt, - tools=tool_schemas, - messages=self._messages, - ) - with stream_obj as stream: - for text in stream.text_stream: - if self._aborted: - _put(("abort",)) - return - _put(("chunk", text)) - if self._aborted: - _put(("abort",)) - return - final_msg = stream.get_final_message() - final = final_msg - if final.stop_reason == "max_tokens": - sidecar.append("Response truncated: max_tokens.") - for block in final.content: - if _block_type(block) == "tool_use": - tool_uses.append(block) - _put(("done", final, tool_uses, sidecar)) - return - except AbortedError: - _put(("abort",)) - return - except Exception as e: - if self._client.is_authentication_error(e): - _put(("fatal", _FatalLLM(str(e), pop_user=True, kind="auth"))) - return - if self._client.is_retryable_error(e): - if attempt < _MAX_RETRIES - 1: - wait = _compute_retry_delay(attempt) - sidecar.append( - f"API error, retrying in {wait:.1f}s… ({self._client.error_message(e)})", - ) - for msg in sidecar: - _put(("sidecar", msg)) - sidecar.clear() - time.sleep(wait) - continue - _put( - ( - "fatal", - _FatalLLM( - f"API error after {_MAX_RETRIES} retries: {self._client.error_message(e)}", - pop_user=True, - kind="api", - ), - ), - ) - return - if self._client.is_api_error(e): - _put( - ( - "fatal", - _FatalLLM( - f"API error: {self._client.error_message(e)}", - pop_user=True, - kind="api", - ), - ), - ) - return - if self._aborted: - _put(("abort",)) - return - _put(("fatal", e)) - return - - async def _consume_llm_stream( - self, - q: asyncio.Queue[Any], - assistant_chunks: list[str], - event_sink: StreamEventSink | None = None, - ) -> tuple[Any | None, list[Any], list[str]]: - sidecar: list[str] = [] - while True: - item = await q.get() - kind = item[0] - if kind == "chunk": - _, text = item - assistant_chunks.append(text) - if event_sink is not None: - try: - r = event_sink({"kind": "assistant_delta", "text": text}) - if inspect.isawaitable(r): - await r - except Exception: - pass - cb = self._text_stream_callback - if cb is not None: - try: - r = cb(text) - if inspect.isawaitable(r): - await r - except Exception: - pass - elif kind == "sidecar": - sidecar.append(str(item[1])) - elif kind == "done": - _, final, tool_uses, extra = item - sidecar.extend(list(extra)) - return final, tool_uses, sidecar - elif kind == "abort": - raise AbortedError - elif kind == "fatal": - raise item[1] - else: - raise RuntimeError(f"unknown stream item: {item!r}") - - async def _run_llm_in_thread( - self, - assistant_chunks: list[str], - event_sink: StreamEventSink | None = None, - ) -> tuple[Any | None, list[Any], list[str]]: - if self._stream_assistant: - q: asyncio.Queue[Any] = asyncio.Queue() - loop = asyncio.get_running_loop() - producer = asyncio.create_task( - asyncio.to_thread(self._sync_produce_llm_to_queue, loop, q), - ) - try: - return await self._consume_llm_stream( - q, assistant_chunks, event_sink=event_sink - ) - finally: - await producer - return await asyncio.to_thread(self._sync_llm_round) - - async def _append_stream_event( - self, - events: list[dict[str, Any]], - ev: dict[str, Any], - sink: StreamEventSink | None, - ) -> None: - events.append(ev) - if sink is None: - return - try: - r = sink(ev) - if inspect.isawaitable(r): - await r - except Exception: - pass - - async def _execute_one_tool(self, tu: Any, *, skip_permission: bool) -> ToolResult: - tn = _block_name(tu) - ti = _block_input(tu) - tool = self._tools.get(tn) - if tool is None: - return ToolResult(content=f"Unknown tool: {tn}", is_error=True) - if not skip_permission and self._permissions.check(tool, ti) == "deny": - return ToolResult(content="Permission denied.", is_error=True) - try: - return await self._backend.call_tool(tn, ti) - except Exception as e: - return ToolResult(content=f"Tool execution error: {e}", is_error=True) - - async def respond( - self, - user_input: str, - *, - event_sink: StreamEventSink | None = None, - ) -> dict[str, Any]: - """Execute one user message round; returns JSON-serializable summary (events list, text). - - If ``event_sink`` is set, each event dict (and ``assistant_delta`` chunks when - streaming) is passed to the sink as it is produced (for RPC streaming). - """ - self._aborted = False - self._user_msg_start = len(self._messages) - events: list[dict[str, Any]] = [] - assistant_chunks: list[str] = [] - - self._messages.append({"role": "user", "content": user_input}) - self._persist(self._messages[-1]) - - try: - while True: - if self._aborted: - raise AbortedError - - try: - final, tool_uses, sidecar = await self._run_llm_in_thread( - assistant_chunks, - event_sink=event_sink, - ) - except _FatalLLM as fe: - if fe.pop_user: - self.rollback_pending() - await self._append_stream_event( - events, - {"kind": "error", "message": str(fe)}, - event_sink, - ) - return { - "events": events, - "assistant_text": "", - "ok": False, - "streamed_assistant": bool( - self._stream_assistant and self._text_stream_callback, - ), - } - except AbortedError: - raise - except Exception as e: - await self._append_stream_event( - events, - {"kind": "error", "message": str(e)}, - event_sink, - ) - return { - "events": events, - "assistant_text": "".join(assistant_chunks), - "ok": False, - "streamed_assistant": bool( - self._stream_assistant and self._text_stream_callback, - ), - } - - for msg in sidecar: - await self._append_stream_event( - events, - {"kind": "error", "message": msg}, - event_sink, - ) - - if final is None: - self._messages.pop() - await self._append_stream_event( - events, - {"kind": "error", "message": "empty model response"}, - event_sink, - ) - return { - "events": events, - "assistant_text": "", - "ok": False, - "streamed_assistant": bool( - self._stream_assistant and self._text_stream_callback, - ), - } - - self._messages.append({"role": "assistant", "content": final.content}) - self._persist(self._messages[-1]) - if not self._stream_assistant: - for block in final.content: - if _block_type(block) == "text": - if isinstance(block, dict): - assistant_chunks.append(str(block.get("text", ""))) - else: - assistant_chunks.append( - str(getattr(block, "text", "")), - ) - - if not tool_uses: - break - - tool_results: list[dict[str, Any]] = [] - batches: list[tuple[bool, list[Any]]] = [] - for tu in tool_uses: - t = self._tools.get(_block_name(tu)) - is_concurrent = t is not None and t.is_read_only() - if batches and batches[-1][0] == is_concurrent and is_concurrent: - batches[-1][1].append(tu) - else: - batches.append((is_concurrent, [tu])) - - for is_concurrent, batch in batches: - if self._aborted: - raise AbortedError - - if is_concurrent and len(batch) > 1: - approved: list[Any] = [] - denied: dict[str, ToolResult] = {} - for tu in batch: - tn = _block_name(tu) - ti = _block_input(tu) - tool = self._tools.get(tn) - act = tool.get_activity_description(**ti) if tool else None - await self._append_stream_event( - events, - { - "kind": "tool_call", - "name": tn, - "input": ti, - "activity": act, - }, - event_sink, - ) - if tool and self._permissions.check(tool, ti) == "deny": - denied[_block_id(tu)] = ToolResult( - content="Permission denied.", - is_error=True, - ) - else: - approved.append(tu) - - executed: dict[str, ToolResult] = {} - if approved: - for tu in approved: - tn = _block_name(tu) - ti = _block_input(tu) - tool = self._tools.get(tn) - act = ( - tool.get_activity_description(**ti) - if tool - else None - ) - await self._append_stream_event( - events, - { - "kind": "tool_executing", - "name": tn, - "input": ti, - "activity": act, - }, - event_sink, - ) - async_results = await asyncio.gather( - *( - self._execute_one_tool(tu, skip_permission=True) - for tu in approved - ), - return_exceptions=True, - ) - for tu, res in zip(approved, async_results, strict=True): - tid = _block_id(tu) - if isinstance(res, BaseException): - executed[tid] = ToolResult( - content=f"Tool execution error: {res}", - is_error=True, - ) - else: - executed[tid] = res - - for tu in batch: - tid = _block_id(tu) - tn = _block_name(tu) - ti = _block_input(tu) - result = denied.get(tid) or executed.get(tid) - if result is None: - result = ToolResult(content="No result", is_error=True) - await self._append_stream_event( - events, - { - "kind": "tool_result", - "name": tn, - "input": ti, - "content": result.content, - "is_error": result.is_error, - }, - event_sink, - ) - tool_results.append(_tool_result_dict(tid, result)) - else: - for tu in batch: - if self._aborted: - raise AbortedError - tn = _block_name(tu) - ti = _block_input(tu) - tool = self._tools.get(tn) - act = tool.get_activity_description(**ti) if tool else None - await self._append_stream_event( - events, - { - "kind": "tool_call", - "name": tn, - "input": ti, - "activity": act, - }, - event_sink, - ) - if tool and self._permissions.check(tool, ti) == "deny": - result = ToolResult( - content="Permission denied.", - is_error=True, - ) - else: - await self._append_stream_event( - events, - { - "kind": "tool_executing", - "name": tn, - "input": ti, - "activity": act, - }, - event_sink, - ) - result = await self._execute_one_tool( - tu, - skip_permission=True, - ) - await self._append_stream_event( - events, - { - "kind": "tool_result", - "name": tn, - "input": ti, - "content": result.content, - "is_error": result.is_error, - }, - event_sink, - ) - tool_results.append( - _tool_result_dict(_block_id(tu), result) - ) - - self._messages.append({"role": "user", "content": tool_results}) - self._persist(self._messages[-1]) - - except AbortedError: - self.rollback_pending() - await self._append_stream_event( - events, - {"kind": "aborted"}, - event_sink, - ) - return { - "events": events, - "assistant_text": "".join(assistant_chunks), - "ok": True, - "streamed_assistant": bool( - self._stream_assistant and self._text_stream_callback, - ), - } - - return { - "events": events, - "assistant_text": "".join(assistant_chunks), - "ok": True, - "streamed_assistant": bool( - self._stream_assistant and self._text_stream_callback, - ), - } - - -class _FatalLLM(Exception): - def __init__(self, message: str, *, pop_user: bool, kind: str) -> None: - super().__init__(message) - self.pop_user = pop_user - self.kind = kind diff --git a/python/pulsing/agent/loop/llm_client.py b/python/pulsing/agent/loop/llm_client.py deleted file mode 100644 index 4d9ce2e66..000000000 --- a/python/pulsing/agent/loop/llm_client.py +++ /dev/null @@ -1,6 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""LLM streaming — re-export Forge Rust client.""" - -from pulsing.forge.llm_client import LLMClient, LLMMessage, LLMUsage, RUST_LLM_AVAILABLE - -__all__ = ["LLMClient", "LLMMessage", "LLMUsage", "RUST_LLM_AVAILABLE"] diff --git a/python/pulsing/agent/loop/permissions.py b/python/pulsing/agent/loop/permissions.py deleted file mode 100644 index 4daa559c9..000000000 --- a/python/pulsing/agent/loop/permissions.py +++ /dev/null @@ -1,142 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Permission checks: read-only, auto-approve, exec approval (Codex-aligned).""" - -from __future__ import annotations - -import json -from collections.abc import Callable -from typing import Any, Literal - -from pulsing.agent.loop.tool_base import Tool - -PermissionDecision = Literal["allow", "deny"] -CallbackDecision = Literal["allow", "deny", "once"] -ExecApprovalDecision = Literal[ - "approved", - "denied", - "approved_for_session", - "approved_with_amendment", - "abort", -] - - -class PermissionChecker: - """Read-only tools auto-allow; mutating tools and shell exec need approval.""" - - def __init__( - self, - *, - auto_approve: bool = False, - prompt_callback: Callable[[str, str], CallbackDecision] | None = None, - user_input_callback: Callable[[dict[str, Any]], dict[str, Any]] | None = None, - plugin_install_callback: Callable[[dict[str, Any]], bool | str] | None = None, - exec_approval_callback: ( - Callable[[dict[str, Any]], ExecApprovalDecision] | None - ) = None, - permissions_callback: Callable[[dict[str, Any]], dict[str, Any]] | None = None, - ) -> None: - self._auto_approve = auto_approve - self._prompt_callback = prompt_callback - self._user_input_callback = user_input_callback - self._plugin_install_callback = plugin_install_callback - self._exec_approval_callback = exec_approval_callback - self._permissions_callback = permissions_callback - self._always_allow: set[str] = set() - - @property - def auto_approve(self) -> bool: - return self._auto_approve - - def check(self, tool: Tool, inputs: dict) -> PermissionDecision: - if tool.is_read_only(): - return "allow" - if self._auto_approve: - return "allow" - if tool.name in self._always_allow: - return "allow" - - if self._prompt_callback is None: - return "deny" - - summary = json.dumps(inputs, ensure_ascii=False, default=str)[:4000] - choice = self._prompt_callback(tool.name, summary) - if choice == "allow": - self._always_allow.add(tool.name) - return "allow" - if choice == "once": - return "allow" - return "deny" - - def prompt_exec_approval(self, request: dict[str, Any]) -> ExecApprovalDecision: - if self._auto_approve: - return "approved" - if self._exec_approval_callback is not None: - return self._exec_approval_callback(request) - if self._prompt_callback is not None: - cmd = " ".join(str(x) for x in (request.get("command") or [])) - reason = str(request.get("reason") or request.get("justification") or "") - summary = f"shell exec: {cmd}\n{reason}".strip() - choice = self._prompt_callback("shell_command", summary) - if choice == "allow": - return "approved_with_amendment" - if choice == "once": - return "approved" - return "denied" - return "denied" - - def prompt_request_permissions(self, args: dict[str, Any]) -> dict[str, Any]: - if self._auto_approve: - perms = args.get("permissions") or {} - return { - "permissions": perms, - "scope": "session", - "strict_auto_review": False, - } - if self._permissions_callback is not None: - return self._permissions_callback(args) - if self._prompt_callback is not None: - summary = json.dumps(args, ensure_ascii=False, default=str)[:4000] - choice = self._prompt_callback("request_permissions", summary) - if choice in ("allow", "once"): - return { - "permissions": args.get("permissions") or {}, - "scope": "session", - "strict_auto_review": choice == "allow", - } - return {"permissions": {}, "scope": "turn", "strict_auto_review": False} - - def prompt_user_input(self, args: dict[str, Any]) -> dict[str, Any]: - from pulsing.forge.session_input import ( - resolve_user_input, - validate_request_user_input, - ) - - validated = validate_request_user_input(args) - return resolve_user_input( - validated, - auto_approve=self._auto_approve, - user_input_callback=self._user_input_callback, - prompt_callback=self._prompt_callback, - ) - - def prompt_plugin_install(self, args: dict[str, Any]) -> bool: - if self._auto_approve: - return True - if self._plugin_install_callback is not None: - out = self._plugin_install_callback(args) - if isinstance(out, bool): - return out - return str(out).strip().lower() in ( - "approved", - "allow", - "once", - "yes", - "true", - ) - if self._prompt_callback is not None: - name = str(args.get("tool_name") or args.get("tool_id") or "plugin") - reason = str(args.get("suggest_reason") or "") - summary = f"Install plugin {name}?\n{reason}".strip() - choice = self._prompt_callback("request_plugin_install", summary) - return choice in ("allow", "once") - return False diff --git a/python/pulsing/agent/loop/quest_tools.py b/python/pulsing/agent/loop/quest_tools.py deleted file mode 100644 index b1d2b6483..000000000 --- a/python/pulsing/agent/loop/quest_tools.py +++ /dev/null @@ -1,90 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""QuestReport tool — agents update puzzle status in cluster.json.""" - -from __future__ import annotations - -import json -from pathlib import Path -from typing import Any - -from pulsing.agent.loop.tool_base import Tool, ToolResult -from pulsing.agent.loop.tools_pkg import _json_schema_object -from pulsing.agent.workspace.quest import ( - QUEST_STATUSES, - format_quest_brief, - update_quest_status, -) - - -class QuestReportTool(Tool): - @property - def name(self) -> str: - return "QuestReport" - - @property - def description(self) -> str: - return ( - "Report progress on a workspace quest (puzzle). " - "Updates status in .pulsing/cluster.json." - ) - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "quest_id": { - "type": "string", - "description": "Quest id (puzzle id from cluster.json).", - }, - "status": { - "type": "string", - "enum": sorted(QUEST_STATUSES), - "description": "New quest status.", - }, - "note": { - "type": "string", - "description": "Optional progress note.", - }, - }, - ["quest_id", "status"], - ) - - def is_read_only(self) -> bool: - return False - - def execute(self, **kwargs: Any) -> ToolResult: - raise RuntimeError("QuestReport runs on Agent.") - - -async def tool_quest_report(agent: Any, kwargs: dict[str, Any]) -> ToolResult: - qid = str(kwargs.get("quest_id") or kwargs.get("id") or "").strip() - status = str(kwargs.get("status") or "").strip().lower() - note = str(kwargs.get("note") or "").strip() - if not qid: - return ToolResult(content="QuestReport: quest_id required.", is_error=True) - if not status: - return ToolResult(content="QuestReport: status required.", is_error=True) - root = Path(agent._cwd) - reporter = agent._cluster_short_name or "agent" - try: - updated = update_quest_status( - root, - qid, - status=status, - note=note, - reporter=reporter, - ) - except KeyError as e: - return ToolResult(content=str(e), is_error=True) - except ValueError as e: - return ToolResult(content=str(e), is_error=True) - except OSError as e: - return ToolResult(content=f"QuestReport failed: {e!r}", is_error=True) - payload = { - "quest_id": qid, - "status": updated.get("status"), - "summary": format_quest_brief(qid, updated), - } - if note: - payload["note"] = note - return ToolResult(content=json.dumps(payload, ensure_ascii=False)) diff --git a/python/pulsing/agent/loop/sandbox.py b/python/pulsing/agent/loop/sandbox.py deleted file mode 100644 index dedd8033f..000000000 --- a/python/pulsing/agent/loop/sandbox.py +++ /dev/null @@ -1,6 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Re-export sandbox helpers from Forge (single source of truth).""" - -from pulsing.forge.sandbox import build_bash_exec, normalize_policy - -__all__ = ["build_bash_exec", "normalize_policy"] diff --git a/python/pulsing/agent/loop/sandbox_manager.py b/python/pulsing/agent/loop/sandbox_manager.py deleted file mode 100644 index 92738f256..000000000 --- a/python/pulsing/agent/loop/sandbox_manager.py +++ /dev/null @@ -1,46 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Hub-side sandbox view (policy + static Bash risk hints — MVP sandbox summary only).""" - -from __future__ import annotations - -import re -from dataclasses import dataclass - -from pulsing.agent.loop.sandbox import normalize_policy - - -@dataclass -class SandboxManager: - """Aggregates effective Bash policy for status lines and lightweight heuristics.""" - - policy: str - dangerously_disable_sandbox: bool = False - - def effective_policy(self) -> str: - if self.dangerously_disable_sandbox: - return "off" - return normalize_policy(self.policy) - - def describe(self) -> str: - pol = self.effective_policy() - bits = [ - f"bash_policy={pol}", - "exec=argv list (no shell=True)", - ] - if pol == "bwrap": - bits.append("bubblewrap minimal profile (Linux)") - elif pol == "restricted": - bits.append("env -i + bash --norc/--noprofile") - return "; ".join(bits) - - def bash_warnings(self, command: str) -> list[str]: - """Static heuristics only (does not parse shell robustly).""" - c = (command or "").strip() - out: list[str] = [] - if re.search(r"\brm\s+(-[rfRF]*\s*)*[/~]", c): - out.append("possible broad rm — review paths") - if "curl" in c and re.search(r"\|\s*sh", c): - out.append("curl|sh pattern — high risk") - if ">/" in c or ">>/" in c: - out.append("redirect to absolute path — confirm target") - return out diff --git a/python/pulsing/agent/loop/split_tools.py b/python/pulsing/agent/loop/split_tools.py deleted file mode 100644 index fe6473186..000000000 --- a/python/pulsing/agent/loop/split_tools.py +++ /dev/null @@ -1,133 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Build mixed tool list: isolated (schema-only) + parent-local tools.""" - -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from pulsing.agent.npc.loader import list_npc_classes -from pulsing.agent.loop.cluster_tools import ( - ListClusterAgentsTool, - MessageClusterAgentTool, -) -from pulsing.agent.loop.constants import ( - FORGE_HOST_TOOL_NAMES, - FORGE_ISOLATED_TOOL_NAMES, -) -from pulsing.agent.loop.forge_tools import all_forge_tool_templates -from pulsing.agent.loop.permissions import PermissionChecker -from pulsing.agent.loop.quest_tools import QuestReportTool -from pulsing.agent.loop.tool_base import Tool, ToolResult -from pulsing.agent.loop.tools_pkg import ( - FetchUrlTool, - _json_schema_object, -) -from pulsing.core.proxy import ActorProxy - - -class SummonTool(Tool): - @property - def name(self) -> str: - return "Summon" - - @property - def description(self) -> str: - return "Summon another NPC to help. Set wait=false to spawn without blocking." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "goal": {"type": "string"}, - "npc_class": { - "type": "string", - "description": "Npc class id (see .pulsing/npcs/*.json).", - }, - "name": {"type": "string"}, - "personality": {"type": "string"}, - "task_id": {"type": "string"}, - "wait": { - "type": "boolean", - "description": "Block for child reply (default true).", - }, - "timeout": { - "type": "number", - "description": "Max seconds when wait=true (default 600).", - }, - }, - ["goal"], - ) - - def is_read_only(self) -> bool: - return False - - def execute(self, **kwargs: Any) -> ToolResult: - raise RuntimeError("Summon runs on Agent.") - - -class _IsolatedSchemaTool(Tool): - def __init__(self, template: Tool) -> None: - self._t = template - - @property - def name(self) -> str: - return self._t.name - - @property - def description(self) -> str: - return self._t.description - - @property - def input_schema(self) -> dict: - return self._t.input_schema - - def is_read_only(self) -> bool: - return self._t.is_read_only() - - def get_activity_description(self, **kwargs: Any) -> str | None: - return self._t.get_activity_description(**kwargs) - - def execute(self, **kwargs: Any) -> ToolResult: - raise RuntimeError(f"{self.name} runs in the isolated worker.") - - -def build_tools_for_agent( - checker: PermissionChecker, - proxy: ActorProxy | None = None, - *, - cwd: str = ".", - cluster_enabled: bool = False, - summon_enabled: bool = False, - quest_enabled: bool = True, - tool_allowlist: set[str] | None = None, - tool_forbid: set[str] | None = None, -) -> list[Tool]: - _ = checker, proxy, cwd - out: list[Tool] = [_IsolatedSchemaTool(t) for t in all_forge_tool_templates()] - out.append(FetchUrlTool()) - if quest_enabled: - out.append(QuestReportTool()) - if cluster_enabled: - out.extend([ListClusterAgentsTool(), MessageClusterAgentTool()]) - if summon_enabled: - out.append(SummonTool()) - if tool_allowlist: - out = [t for t in out if t.name in tool_allowlist] - if tool_forbid: - out = [t for t in out if t.name not in tool_forbid] - return out - - -def local_tool_names(tools: list[Tool]) -> set[str]: - return { - t.name - for t in tools - if t.name not in FORGE_ISOLATED_TOOL_NAMES - and t.name not in FORGE_HOST_TOOL_NAMES - } - - -def npc_class_names(workspace_root: Path | str | None = None) -> list[str]: - root = Path(workspace_root) if workspace_root else None - return list_npc_classes(root) diff --git a/python/pulsing/agent/loop/tool_base.py b/python/pulsing/agent/loop/tool_base.py deleted file mode 100644 index 835d5ba3b..000000000 --- a/python/pulsing/agent/loop/tool_base.py +++ /dev/null @@ -1,59 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tool protocol: ``ToolResult`` and abstract ``Tool`` (standard tool API).""" - -from __future__ import annotations - -from abc import ABC, abstractmethod -from dataclasses import dataclass -from typing import Any - - -@dataclass -class ToolResult: - content: str - is_error: bool = False - - -def tool_result_from_worker_value(raw: Any) -> ToolResult: - """Map isolated worker dict (``content`` / ``is_error``) to :class:`ToolResult`.""" - if isinstance(raw, dict) and "content" in raw: - return ToolResult( - content=str(raw["content"]), - is_error=bool(raw.get("is_error", False)), - ) - if hasattr(raw, "content") and hasattr(raw, "is_error"): - return ToolResult( - content=str(raw.content), - is_error=bool(getattr(raw, "is_error", False)), - ) - return ToolResult(content=str(raw), is_error=False) - - -class Tool(ABC): - @property - @abstractmethod - def name(self) -> str: ... - - @property - @abstractmethod - def description(self) -> str: ... - - @property - @abstractmethod - def input_schema(self) -> dict: ... - - @abstractmethod - def execute(self, **kwargs) -> ToolResult: ... - - def get_activity_description(self, **kwargs) -> str | None: - return None - - def is_read_only(self) -> bool: - return False - - def to_api_schema(self) -> dict: - return { - "name": self.name, - "description": self.description, - "input_schema": self.input_schema, - } diff --git a/python/pulsing/agent/loop/tools_impl.py b/python/pulsing/agent/loop/tools_impl.py deleted file mode 100644 index 8dd4409b8..000000000 --- a/python/pulsing/agent/loop/tools_impl.py +++ /dev/null @@ -1,215 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Pure tool implementations returning :class:`ToolResult` (shared by agent + worker).""" - -from __future__ import annotations - -import fnmatch -import os -import re -import subprocess -from pathlib import Path -from typing import Any -from urllib.error import HTTPError, URLError -from urllib.parse import urlparse -from urllib.request import Request, urlopen - -from pulsing.agent.paths import agent_env -from pulsing.agent.loop.sandbox import build_bash_exec, normalize_policy -from pulsing.agent.loop.tool_base import ToolResult - -_READ_CAP = 2 * 1024 * 1024 -_BASH_MAX_OUT = 256 * 1024 -_GREP_MAX = 200 - - -def impl_read(**kwargs: Any) -> ToolResult: - path = Path(str(kwargs.get("file_path", ""))) - try: - data = path.read_bytes() - except OSError as e: - return ToolResult(content=str(e), is_error=True) - if len(data) > _READ_CAP: - return ToolResult(content="File too large for Read tool.", is_error=True) - try: - text = data.decode("utf-8") - except UnicodeDecodeError: - return ToolResult(content="Not valid UTF-8.", is_error=True) - return ToolResult(content=text) - - -def impl_glob(**kwargs: Any) -> ToolResult: - pattern = str(kwargs.get("pattern", "")) - base = Path(str(kwargs.get("path", "."))).resolve() - if not base.exists(): - return ToolResult(content="path does not exist", is_error=True) - try: - matches = sorted(str(p) for p in base.glob(pattern))[:500] - except OSError as e: - return ToolResult(content=str(e), is_error=True) - return ToolResult(content="\n".join(matches) if matches else "(no matches)") - - -def impl_grep(**kwargs: Any) -> ToolResult: - raw_pat = str(kwargs.get("pattern", "")) - root = Path(str(kwargs.get("path", "."))).resolve() - glob_pat = kwargs.get("glob") - try: - cre = re.compile(raw_pat) - except re.error as e: - return ToolResult(content=f"Invalid regex: {e}", is_error=True) - hits: list[str] = [] - - def consider_file(fp: Path) -> None: - if glob_pat and not fnmatch.fnmatch(fp.name, str(glob_pat)): - return - try: - text = fp.read_text(encoding="utf-8", errors="replace") - except OSError: - return - for i, line in enumerate(text.splitlines(), 1): - if cre.search(line): - hits.append(f"{fp}:{i}:{line[:500]}") - if len(hits) >= _GREP_MAX: - return - - if not root.exists(): - return ToolResult(content="path not found", is_error=True) - if root.is_file(): - consider_file(root) - else: - for fp in root.rglob("*"): - if fp.is_file() and len(hits) < _GREP_MAX: - consider_file(fp) - if len(hits) >= _GREP_MAX: - break - if not hits: - return ToolResult(content="(no matches)") - extra = "\n… truncated …" if len(hits) >= _GREP_MAX else "" - return ToolResult(content="\n".join(hits) + extra) - - -def impl_edit(**kwargs: Any) -> ToolResult: - fp = Path(str(kwargs.get("file_path", ""))) - old = str(kwargs.get("old_string", "")) - new = str(kwargs.get("new_string", "")) - try: - text = fp.read_text(encoding="utf-8") - except OSError as e: - return ToolResult(content=str(e), is_error=True) - count = text.count(old) - if count == 0: - return ToolResult(content="old_string not found", is_error=True) - if count > 1: - return ToolResult( - content="old_string is not unique; refusing ambiguous edit", - is_error=True, - ) - updated = text.replace(old, new, 1) - try: - fp.write_text(updated, encoding="utf-8") - except OSError as e: - return ToolResult(content=str(e), is_error=True) - return ToolResult(content="ok") - - -def impl_write(**kwargs: Any) -> ToolResult: - fp = Path(str(kwargs.get("file_path", ""))) - content = str(kwargs.get("content", "")) - try: - fp.parent.mkdir(parents=True, exist_ok=True) - fp.write_text(content, encoding="utf-8") - except OSError as e: - return ToolResult(content=str(e), is_error=True) - return ToolResult(content="ok") - - -def impl_bash(**kwargs: Any) -> ToolResult: - cmd = str(kwargs.get("command", "")) - timeout = int(kwargs.get("timeout_sec", 120)) - cwd = kwargs.get("cwd") - if cwd is not None: - cwd = str(cwd) - policy = normalize_policy(str(kwargs.get("sandbox_policy", "off"))) - dangerous = bool(kwargs.get("dangerously_disable_sandbox", False)) - argv, extra_env, label = build_bash_exec( - cmd, - cwd=cwd, - policy=policy, - dangerously_disable_sandbox=dangerous, - timeout=timeout, - ) - run_kw: dict[str, Any] = { - "args": argv, - "capture_output": True, - "text": True, - "timeout": timeout, - } - if cwd: - run_kw["cwd"] = cwd - if extra_env is not None: - run_kw["env"] = extra_env - try: - proc = subprocess.run(**run_kw) - except subprocess.TimeoutExpired: - return ToolResult(content="timed out", is_error=True) - except Exception as e: - return ToolResult(content=str(e), is_error=True) - out = (proc.stdout or "") + (proc.stderr or "") - if len(out) > _BASH_MAX_OUT: - out = out[:_BASH_MAX_OUT] + "\n… truncated …" - tail = f"\nexit={proc.returncode}\n[{label}]" - return ToolResult(content=out + tail, is_error=proc.returncode != 0) - - -_FETCH_CAP = 256 * 1024 - - -def impl_fetch_url(**kwargs: Any) -> ToolResult: - """HTTP(S) GET with host allowlist (``PULSING_CRAFT_FETCH_ALLOW`` comma-separated hostnames).""" - - url = str(kwargs.get("url", "")).strip() - max_bytes = int(kwargs.get("max_bytes", _FETCH_CAP)) - max_bytes = max(1024, min(max_bytes, _FETCH_CAP)) - if not url: - return ToolResult(content="url required", is_error=True) - parsed = urlparse(url) - if parsed.scheme not in ("http", "https"): - return ToolResult(content="only http/https URLs", is_error=True) - host = (parsed.hostname or "").lower() - if not host: - return ToolResult(content="missing host", is_error=True) - allow = agent_env("FETCH_ALLOW").strip() - if not allow: - return ToolResult( - content=( - "FetchUrl disabled: set env PULSING_CRAFT_FETCH_ALLOW to a comma-separated " - "hostname allowlist (e.g. api.github.com,example.com)." - ), - is_error=True, - ) - allowed = {h.strip().lower() for h in allow.split(",") if h.strip()} - if host not in allowed: - return ToolResult( - content=f"host {host!r} not in PULSING_CRAFT_FETCH_ALLOW", - is_error=True, - ) - req = Request(url, headers={"User-Agent": "pulsing-craft-fetch/1.0"}) - try: - with urlopen(req, timeout=30) as resp: # noqa: S310 — host allowlisted - data = resp.read(max_bytes + 1) - except HTTPError as e: - return ToolResult(content=f"HTTP {e.code}: {e.reason}", is_error=True) - except URLError as e: - return ToolResult(content=str(e.reason), is_error=True) - except Exception as e: - return ToolResult(content=str(e), is_error=True) - if len(data) > max_bytes: - return ToolResult( - content="response larger than max_bytes", - is_error=True, - ) - try: - text = data.decode("utf-8") - except UnicodeDecodeError: - text = data.decode("utf-8", errors="replace") - return ToolResult(content=text) diff --git a/python/pulsing/agent/loop/tools_pkg.py b/python/pulsing/agent/loop/tools_pkg.py deleted file mode 100644 index cc482bbda..000000000 --- a/python/pulsing/agent/loop/tools_pkg.py +++ /dev/null @@ -1,205 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Built-in filesystem / network tools.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.agent.loop.permissions import PermissionChecker -from pulsing.agent.loop.tool_base import Tool, ToolResult -from pulsing.agent.loop.tools_impl import ( - impl_bash, - impl_edit, - impl_fetch_url, - impl_glob, - impl_grep, - impl_read, - impl_write, -) - - -def _json_schema_object( - properties: dict[str, Any], - required: list[str] | None = None, -) -> dict: - req = list(properties.keys()) if required is None else required - return { - "type": "object", - "properties": properties, - "required": req, - "additionalProperties": False, - } - - -class ReadTool(Tool): - @property - def name(self) -> str: - return "Read" - - @property - def description(self) -> str: - return "Read a UTF-8 text file from disk (size-capped)." - - @property - def input_schema(self) -> dict: - return _json_schema_object({"file_path": {"type": "string"}}, ["file_path"]) - - def is_read_only(self) -> bool: - return True - - def get_activity_description(self, **kwargs: Any) -> str | None: - return f"Read {kwargs.get('file_path', '')}" - - def execute(self, **kwargs: Any) -> ToolResult: - return impl_read(**kwargs) - - -class GlobTool(Tool): - @property - def name(self) -> str: - return "Glob" - - @property - def description(self) -> str: - return "Glob files under a directory (non-recursive segments via pathlib)." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "pattern": {"type": "string"}, - "path": {"type": "string", "description": "Base directory"}, - }, - ["pattern", "path"], - ) - - def is_read_only(self) -> bool: - return True - - def execute(self, **kwargs: Any) -> ToolResult: - return impl_glob(**kwargs) - - -class GrepTool(Tool): - @property - def name(self) -> str: - return "Grep" - - @property - def description(self) -> str: - return "Search files with a regex (Python ``re``), capped matches." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "pattern": {"type": "string"}, - "path": {"type": "string"}, - "glob": {"type": "string", "description": "Optional fnmatch filter"}, - }, - ["pattern", "path"], - ) - - def is_read_only(self) -> bool: - return True - - def execute(self, **kwargs: Any) -> ToolResult: - return impl_grep(**kwargs) - - -class EditTool(Tool): - @property - def name(self) -> str: - return "Edit" - - @property - def description(self) -> str: - return "Replace exactly one occurrence of old_string with new_string in a file." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "file_path": {"type": "string"}, - "old_string": {"type": "string"}, - "new_string": {"type": "string"}, - }, - ) - - def execute(self, **kwargs: Any) -> ToolResult: - return impl_edit(**kwargs) - - -class WriteTool(Tool): - @property - def name(self) -> str: - return "Write" - - @property - def description(self) -> str: - return "Write UTF-8 text to a file (creates parent directories)." - - @property - def input_schema(self) -> dict: - return _json_schema_object( - {"file_path": {"type": "string"}, "content": {"type": "string"}}, - ) - - def execute(self, **kwargs: Any) -> ToolResult: - return impl_write(**kwargs) - - -class BashTool(Tool): - @property - def name(self) -> str: - return "Bash" - - @property - def description(self) -> str: - return ( - "Run a shell command in the isolated worker. " - "Sandbox policy is configured on the agent (off / restricted / bwrap); " - "the worker uses subprocess without shell=True." - ) - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "command": {"type": "string"}, - "timeout_sec": {"type": "integer", "minimum": 1, "maximum": 3600}, - }, - ["command"], - ) - - def execute(self, **kwargs: Any) -> ToolResult: - return impl_bash(**kwargs) - - -class FetchUrlTool(Tool): - @property - def name(self) -> str: - return "FetchUrl" - - @property - def description(self) -> str: - return ( - "HTTP(S) GET for a small text response. Requires env PULSING_CRAFT_FETCH_ALLOW " - "comma-separated hostname allowlist. Capped size." - ) - - @property - def input_schema(self) -> dict: - return _json_schema_object( - { - "url": {"type": "string"}, - "max_bytes": {"type": "integer", "minimum": 1024, "maximum": 262144}, - }, - ["url"], - ) - - def is_read_only(self) -> bool: - return True - - def execute(self, **kwargs: Any) -> ToolResult: - return impl_fetch_url(**kwargs) diff --git a/python/pulsing/agent/npc/__init__.py b/python/pulsing/agent/npc/__init__.py deleted file mode 100644 index 6c05f6041..000000000 --- a/python/pulsing/agent/npc/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace NPC spawn (lazy-imports actor).""" - -from __future__ import annotations - -from typing import Any - -from pulsing.agent.npc.config import NpcConfig, get_npc_class, list_npc_classes -from pulsing.agent.npc.loader import NpcClass, seed_npc_defs - -__all__ = [ - "NpcClass", - "NpcConfig", - "spawn_npc", - "get_npc_class", - "list_npc_classes", - "seed_npc_defs", -] - - -async def spawn_npc( - config: NpcConfig, - *, - name: str | None = None, - public: bool = True, -) -> Any: - from pulsing.agent.actors import Agent - - return await Agent.spawn( - config=config, - name=name or config.full_name(), - public=public, - ) diff --git a/python/pulsing/agent/npc/config.py b/python/pulsing/agent/npc/config.py deleted file mode 100644 index 74a0b90f4..000000000 --- a/python/pulsing/agent/npc/config.py +++ /dev/null @@ -1,143 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Agent spawn configuration.""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from pulsing.agent.cluster.constants import full_agent_name, short_agent_name -from pulsing.agent.npc.loader import ( - NpcClass, - load_npc_class, - list_npc_classes as _list_npc_classes, -) -from pulsing.agent.workspace.quest import quest_context_for_agent -from pulsing.agent.workspace.config import load_config - - -def build_npc_prompt( - *, - short_name: str, - workspace_id: str, - cls: NpcClass, - role: str = "", - personality: str = "", - description: str = "", - cwd: str, - quest_context: str = "", -) -> str: - lines = [ - f"You are {short_name} in world {workspace_id}.", - f"Class: {cls.name} — {cls.description}", - ] - if role: - lines.append(f"Role: {role}.") - if personality: - lines.append(f"Personality: {personality}.") - if description: - lines.append(description) - if cls.prompt_extra: - lines.append(cls.prompt_extra) - if quest_context: - lines.append(quest_context) - lines.append(f"Working directory: {cwd}") - return "\n".join(lines) - - -def get_npc_class(name: str, workspace_root: Path | str | None = None) -> NpcClass: - root = Path(workspace_root) if workspace_root else None - return load_npc_class(name, root) - - -def list_npc_classes(workspace_root: Path | str | None = None) -> list[str]: - root = Path(workspace_root) if workspace_root else None - return _list_npc_classes(root) - - -@dataclass -class NpcConfig: - model: str - cwd: str - agent_name: str - workspace_id: str - provider: str = "anthropic" - api_key: str | None = None - base_url: str | None = None - auto_approve: bool = False - system_prompt: str | None = None - prompt_callback: Any | None = None - sandbox_policy: str = "off" - dangerously_disable_sandbox: bool = False - agent_role: str = "" - agent_description: str = "" - summon_depth: int = 0 - max_summon_depth: int = 3 - tool_allowlist: list[str] | None = None - tool_forbid: list[str] = field(default_factory=list) - npc_class: str = "artisan" - personality: str = "" - shared_tool_worker: bool = False - - @property - def short_name(self) -> str: - return short_agent_name(self.agent_name, workspace_id=self.workspace_id) - - @property - def workspace_root(self) -> Path: - return Path(self.cwd) - - def full_name(self) -> str: - return full_agent_name(self.short_name, workspace_id=self.workspace_id.strip()) - - def resolved_class(self) -> NpcClass: - return load_npc_class(self.npc_class or "artisan", self.workspace_root) - - def resolved_profile(self) -> tuple[str, list[str], set[str], str, str]: - """Return (system_prompt, tool_allowlist, tool_forbid, npc_class_name, personality).""" - cls_def = self.resolved_class() - npc_class_name = cls_def.name - personality = (self.personality or cls_def.default_personality).strip() - ws = self.workspace_id.strip() - short = self.short_name - quest_ctx = "" - cluster_path = self.workspace_root / ".pulsing" / "cluster.json" - if cluster_path.is_file(): - try: - quest_ctx = quest_context_for_agent( - load_config(self.workspace_root), short - ) - except OSError: - pass - system_prompt = (self.system_prompt or "").strip() - if not system_prompt: - system_prompt = build_npc_prompt( - short_name=short, - workspace_id=ws, - cls=cls_def, - role=self.agent_role.strip(), - personality=personality, - description=self.agent_description.strip(), - cwd=self.cwd, - quest_context=quest_ctx, - ) - allow = ( - list(self.tool_allowlist) - if self.tool_allowlist is not None - else list(cls_def.default_tools) - ) - forbid = set(self.tool_forbid) | set(cls_def.forbidden_tools) - return system_prompt, allow, forbid, npc_class_name, personality - - -AgentConfig = NpcConfig - -__all__ = [ - "AgentConfig", - "NpcClass", - "NpcConfig", - "build_npc_prompt", - "get_npc_class", - "list_npc_classes", -] diff --git a/python/pulsing/agent/npc/loader.py b/python/pulsing/agent/npc/loader.py deleted file mode 100644 index f5b77bcdf..000000000 --- a/python/pulsing/agent/npc/loader.py +++ /dev/null @@ -1,130 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Load NpcClass from ``.pulsing/npcs/*.json`` with built-in defaults.""" - -from __future__ import annotations - -import json -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from pulsing.agent.workspace.root import PULSING_DIR - -NPCS_SUBDIR = "npcs" - -_READ = ["Read", "Glob", "Grep"] -_WRITE = ["Edit", "Write", "Bash"] -_PEER = ["Summon", "MessageClusterAgent", "ListClusterAgents", "QuestReport"] - -_BUILTIN: dict[str, dict[str, Any]] = { - "artisan": { - "name": "artisan", - "description": "工匠 — 读写文件、执行命令。", - "default_personality": "helpful and precise", - "prompt_extra": "", - "default_tools": _READ + _WRITE, - "forbidden_tools": [], - "model_hint": None, - }, - "quest_giver": { - "name": "quest_giver", - "description": "任务发布者 — 召唤与协调其他 NPC。", - "default_personality": "organized and strategic", - "prompt_extra": "Use Summon to spawn helpers, MessageClusterAgent to coordinate peers, QuestReport to track quests.", - "default_tools": _PEER + _READ, - "forbidden_tools": [], - "model_hint": None, - }, - "scholar": { - "name": "scholar", - "description": "学者 — 只读审查。", - "default_personality": "critical and detail-oriented", - "prompt_extra": "", - "default_tools": _READ + ["FetchUrl", "QuestReport"], - "forbidden_tools": _WRITE, - "model_hint": None, - }, - "oracle": { - "name": "oracle", - "description": "先知 — 信息收集。", - "default_personality": "curious and resourceful", - "prompt_extra": "", - "default_tools": _READ + ["FetchUrl"], - "forbidden_tools": _WRITE + ["Summon"], - "model_hint": None, - }, -} - - -@dataclass -class NpcClass: - name: str - description: str - default_personality: str = "" - prompt_extra: str = "" - default_tools: list[str] = field(default_factory=list) - forbidden_tools: list[str] = field(default_factory=list) - model_hint: str | None = None - - -def npcs_dir(workspace_root: Path | None) -> Path | None: - if workspace_root is None: - return None - return workspace_root / PULSING_DIR / NPCS_SUBDIR - - -def _from_dict(data: dict[str, Any]) -> NpcClass: - name = str(data.get("name") or "artisan").strip().lower() - return NpcClass( - name=name, - description=str(data.get("description") or ""), - default_personality=str(data.get("default_personality") or ""), - prompt_extra=str(data.get("prompt_extra") or ""), - default_tools=[str(t) for t in (data.get("default_tools") or [])], - forbidden_tools=[str(t) for t in (data.get("forbidden_tools") or [])], - model_hint=( - (str(data["model_hint"]).strip() or None) - if data.get("model_hint") - else None - ), - ) - - -def load_npc_class(name: str, workspace_root: Path | None = None) -> NpcClass: - key = (name or "artisan").strip().lower() - nd = npcs_dir(workspace_root) - if nd is not None: - path = nd / f"{key}.json" - if path.is_file(): - try: - data = json.loads(path.read_text(encoding="utf-8")) - if isinstance(data, dict): - return _from_dict(data) - except (OSError, json.JSONDecodeError): - pass - raw = _BUILTIN.get(key) or _BUILTIN["artisan"] - return _from_dict(raw) - - -def list_npc_classes(workspace_root: Path | None = None) -> list[str]: - names: set[str] = set(_BUILTIN.keys()) - nd = npcs_dir(workspace_root) - if nd is not None and nd.is_dir(): - for path in nd.glob("*.json"): - names.add(path.stem.lower()) - return sorted(names) - - -def seed_npc_defs(workspace_root: Path) -> None: - """Write bundled npc json files when missing.""" - nd = npcs_dir(workspace_root) - assert nd is not None - nd.mkdir(parents=True, exist_ok=True) - for key, data in _BUILTIN.items(): - path = nd / f"{key}.json" - if path.is_file(): - continue - path.write_text( - json.dumps(data, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8", - ) diff --git a/python/pulsing/agent/paths.py b/python/pulsing/agent/paths.py deleted file mode 100644 index a28bef119..000000000 --- a/python/pulsing/agent/paths.py +++ /dev/null @@ -1,15 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Agent user config paths and environment variables.""" - -from __future__ import annotations - -import os - - -def agent_env(name: str, default: str = "") -> str: - """Read ``PULSING_AGENT_{name}``, with fallback to legacy ``PULSING_CRAFT_{name}``.""" - return ( - os.environ.get(f"PULSING_AGENT_{name}") - or os.environ.get(f"PULSING_CRAFT_{name}") - or default - ) diff --git a/python/pulsing/agent/tools.py b/python/pulsing/agent/tools.py deleted file mode 100644 index c4f433c51..000000000 --- a/python/pulsing/agent/tools.py +++ /dev/null @@ -1,16 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge tool routing constants (canonical source: ``pulsing.forge.integrated``).""" - -from __future__ import annotations - -from pulsing.forge.integrated import ( - FORGE_HOST_TOOL_NAMES, - FORGE_ISOLATED_TOOL_NAMES, - FORGE_TOOL_NAMES, -) - -__all__ = [ - "FORGE_HOST_TOOL_NAMES", - "FORGE_ISOLATED_TOOL_NAMES", - "FORGE_TOOL_NAMES", -] diff --git a/python/pulsing/agent/workspace/__init__.py b/python/pulsing/agent/workspace/__init__.py deleted file mode 100644 index 2c83ebd54..000000000 --- a/python/pulsing/agent/workspace/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace-local cc cluster: one working directory = one agent fleet.""" - -from pulsing.agent.workspace.config import WorkspaceConfig, load_config, save_config -from pulsing.agent.workspace.root import find_workspace_root, workspace_cluster_id - -__all__ = [ - "WorkspaceConfig", - "find_workspace_root", - "load_config", - "save_config", - "workspace_cluster_id", -] diff --git a/python/pulsing/agent/workspace/config.py b/python/pulsing/agent/workspace/config.py deleted file mode 100644 index 7a9905540..000000000 --- a/python/pulsing/agent/workspace/config.py +++ /dev/null @@ -1,127 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace = world: ``.pulsing/cluster.json`` holds cluster + puzzles.""" - -from __future__ import annotations - -import json -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from pulsing.agent.workspace.root import ( - CLUSTER_FILE, - NODE_FILE, - PULSING_DIR, - workspace_cluster_id, -) - -DEFAULT_PUZZLES: dict[str, dict[str, str]] = { - "unit-tests": { - "title": "Unit test suite", - "kind": "test", - "path": "tests", - "blurb": "Run pytest; keep green.", - "status": "open", - "assign_to": "", - }, -} - - -@dataclass -class WorkspaceConfig: - root: str - cluster_id: str - name: str = "" - provider: str = "anthropic" - model: str | None = None - auto_approve: bool = False - sandbox: str = "off" - default_agents: list[str] = field(default_factory=lambda: ["guide"]) - shared_tool_worker: bool = False - puzzles: dict[str, dict[str, str]] = field( - default_factory=lambda: {k: dict(v) for k, v in DEFAULT_PUZZLES.items()}, - ) - - @property - def pulsing_dir(self) -> Path: - return Path(self.root) / PULSING_DIR - - @property - def cluster_path(self) -> Path: - return self.pulsing_dir / CLUSTER_FILE - - @property - def node_path(self) -> Path: - return self.pulsing_dir / NODE_FILE - - def seed_addr(self) -> str | None: - p = self.node_path - if not p.is_file(): - return None - try: - data = json.loads(p.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return None - addr = str(data.get("addr") or "").strip() - return addr or None - - -def default_config(root: Path) -> WorkspaceConfig: - root = root.resolve() - return WorkspaceConfig( - root=str(root), - cluster_id=workspace_cluster_id(root), - name=root.name or "workspace", - ) - - -def load_config(root: Path) -> WorkspaceConfig: - path = root / PULSING_DIR / CLUSTER_FILE - data = json.loads(path.read_text(encoding="utf-8")) - puzzles = data.get("puzzles") or DEFAULT_PUZZLES - return WorkspaceConfig( - root=str(root.resolve()), - cluster_id=str(data.get("cluster_id") or workspace_cluster_id(root)), - name=str(data.get("name") or root.name or ""), - provider=str(data.get("provider") or "anthropic"), - model=data.get("model"), - auto_approve=bool(data.get("auto_approve", False)), - sandbox=str(data.get("sandbox") or "off"), - default_agents=list(data.get("default_agents") or ["guide"]), - shared_tool_worker=bool(data.get("shared_tool_worker", False)), - puzzles={k: dict(v) for k, v in puzzles.items()}, - ) - - -def save_config(cfg: WorkspaceConfig) -> None: - cfg.pulsing_dir.mkdir(parents=True, exist_ok=True) - payload: dict[str, Any] = { - "cluster_id": cfg.cluster_id, - "name": cfg.name, - "provider": cfg.provider, - "model": cfg.model, - "auto_approve": cfg.auto_approve, - "sandbox": cfg.sandbox, - "default_agents": cfg.default_agents, - "shared_tool_worker": cfg.shared_tool_worker, - "puzzles": cfg.puzzles, - } - cfg.cluster_path.write_text( - json.dumps(payload, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8", - ) - - -def write_node_record(cfg: WorkspaceConfig, *, addr: str, pid: int) -> None: - cfg.pulsing_dir.mkdir(parents=True, exist_ok=True) - cfg.node_path.write_text( - json.dumps({"addr": addr, "pid": pid}, indent=2) + "\n", - encoding="utf-8", - ) - - -def clear_node_record(cfg: WorkspaceConfig) -> None: - try: - cfg.node_path.unlink(missing_ok=True) - except OSError: - pass diff --git a/python/pulsing/agent/workspace/quest.py b/python/pulsing/agent/workspace/quest.py deleted file mode 100644 index 9c9b1c354..000000000 --- a/python/pulsing/agent/workspace/quest.py +++ /dev/null @@ -1,84 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Quest (puzzle) state: assign_to, status, agent reports.""" - -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from pulsing.agent.workspace.config import WorkspaceConfig, load_config, save_config - -QUEST_STATUSES = frozenset({"open", "in_progress", "solved", "failed"}) - - -def normalize_quest(puzzle: dict[str, Any]) -> dict[str, str]: - out = {k: str(v) for k, v in puzzle.items()} - status = (out.get("status") or "open").strip().lower() - if status not in QUEST_STATUSES: - status = "open" - out["status"] = status - out.setdefault("assign_to", "") - return out - - -def quests_for_agent( - cfg: WorkspaceConfig, agent_name: str -) -> list[tuple[str, dict[str, str]]]: - short = (agent_name or "").strip() - if not short: - return [] - out: list[tuple[str, dict[str, str]]] = [] - for qid, raw in cfg.puzzles.items(): - p = normalize_quest(raw) - assign = (p.get("assign_to") or "").strip() - if assign and assign == short: - out.append((qid, p)) - return sorted(out) - - -def format_quest_brief(qid: str, puzzle: dict[str, str]) -> str: - title = puzzle.get("title") or qid - status = puzzle.get("status") or "open" - kind = puzzle.get("kind") or "task" - path = puzzle.get("path") or "." - line = f"{qid} [{kind}/{status}] {title} @ {path}" - if puzzle.get("blurb"): - line += f" — {puzzle['blurb']}" - return line - - -def quest_context_for_agent(cfg: WorkspaceConfig, agent_name: str) -> str: - assigned = quests_for_agent(cfg, agent_name) - if not assigned: - return "" - lines = ["Assigned quests:"] - for qid, p in assigned: - lines.append(f"- {format_quest_brief(qid, p)}") - lines.append("Use QuestReport to update status when progress changes.") - return "\n".join(lines) - - -def update_quest_status( - root: Path, - quest_id: str, - *, - status: str, - note: str = "", - reporter: str = "", -) -> dict[str, str]: - st = (status or "").strip().lower() - if st not in QUEST_STATUSES: - raise ValueError(f"invalid status {status!r}") - cfg = load_config(root) - puzzle = cfg.puzzles.get(quest_id) - if puzzle is None: - raise KeyError(f"unknown quest {quest_id!r}") - updated = normalize_quest(puzzle) - updated["status"] = st - if note.strip(): - updated["last_note"] = note.strip() - if reporter.strip(): - updated["last_reporter"] = reporter.strip() - cfg.puzzles[quest_id] = updated - save_config(cfg) - return updated diff --git a/python/pulsing/agent/workspace/root.py b/python/pulsing/agent/workspace/root.py deleted file mode 100644 index c5c6abe96..000000000 --- a/python/pulsing/agent/workspace/root.py +++ /dev/null @@ -1,36 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Find workspace root (the world) via ``.pulsing/cluster.json``.""" - -from __future__ import annotations - -import hashlib -from pathlib import Path - -PULSING_DIR = ".pulsing" -CLUSTER_FILE = "cluster.json" -NODE_FILE = "node.json" - - -def workspace_cluster_id(root: Path) -> str: - """Stable 12-char id from absolute workspace path.""" - return hashlib.sha256(str(root.resolve()).encode()).hexdigest()[:12] - - -def find_workspace_root(start: Path | None = None) -> Path | None: - """Return directory containing ``.pulsing/cluster.json``, or None.""" - cur = (start or Path.cwd()).resolve() - while True: - if (cur / PULSING_DIR / CLUSTER_FILE).is_file(): - return cur - if cur.parent == cur: - return None - cur = cur.parent - - -def require_workspace_root(start: Path | None = None) -> Path: - root = find_workspace_root(start) - if root is None: - raise SystemExit( - "not a workspace yet — run `pulsing init` in this project directory first", - ) - return root diff --git a/python/pulsing/agent/workspace/session.py b/python/pulsing/agent/workspace/session.py deleted file mode 100644 index 760449691..000000000 --- a/python/pulsing/agent/workspace/session.py +++ /dev/null @@ -1,42 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Connect to workspace cluster (seed from ``.pulsing/node.json``).""" - -from __future__ import annotations - -import os -from contextlib import asynccontextmanager -from typing import AsyncIterator, Any - -import pulsing as pul - -from pulsing.agent.workspace.config import WorkspaceConfig - - -def require_seed(cfg: WorkspaceConfig) -> str: - seed = cfg.seed_addr() - if not seed: - raise SystemExit( - f"world asleep — run `pulsing agent wake` in {cfg.root}", - ) - return seed - - -@asynccontextmanager -async def workspace_session( - cfg: WorkspaceConfig, - *, - bind_addr: str | None = None, -) -> AsyncIterator[Any]: - """Join workspace gossip; ``bind_addr`` set only for ``pulsing agent wake`` (local node).""" - seeds: list[str] | None = None - if bind_addr is None: - seeds = [require_seed(cfg)] - try: - system = await pul.init( - addr=bind_addr, - seeds=seeds, - passphrase=os.environ.get("PULSING_PASSPHRASE"), - ) - yield system - finally: - await pul.shutdown() diff --git a/python/pulsing/agent/workspace/tool_pool.py b/python/pulsing/agent/workspace/tool_pool.py deleted file mode 100644 index 3ddb44cb3..000000000 --- a/python/pulsing/agent/workspace/tool_pool.py +++ /dev/null @@ -1,26 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Optional workspace-level shared isolated tool worker.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.agent.workspace.config import WorkspaceConfig -from pulsing.forge.backend import spawn_shared_tool_worker as _spawn_shared -from pulsing.forge.backend import resolve_shared_tool_worker as _resolve_shared - -SHARED_WORKER_SHORT = "_tools" - - -async def spawn_shared_tool_worker(cfg: WorkspaceConfig) -> Any: - return await _spawn_shared( - workspace_id=cfg.cluster_id, - cwd=cfg.root, - sandbox_policy=cfg.sandbox, - ) - - -async def resolve_shared_tool_worker( - workspace_id: str, *, timeout: float = 120.0 -) -> Any: - return await _resolve_shared(workspace_id, timeout=timeout) diff --git a/python/pulsing/agent/workspace/world_view.py b/python/pulsing/agent/workspace/world_view.py deleted file mode 100644 index 802fffbe6..000000000 --- a/python/pulsing/agent/workspace/world_view.py +++ /dev/null @@ -1,113 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Player / look / puzzles — thin view over :class:`WorkspaceConfig`.""" - -from __future__ import annotations - -import os -from pathlib import Path -from typing import Any - -from pulsing.agent.workspace.config import WorkspaceConfig -from pulsing.agent.workspace.quest import normalize_quest - - -def player_name() -> str: - return ( - os.environ.get("PLAYER") - or os.environ.get("HERO") - or os.environ.get("USER") - or "player" - ).strip() or "player" - - -def rel_path(root: Path, cwd: Path | None = None) -> str: - base = root.resolve() - here = (cwd or Path.cwd()).resolve() - try: - r = here.relative_to(base) - except ValueError: - return "." - return "." if not r.parts else r.as_posix() - - -def puzzles_at( - cfg: WorkspaceConfig, cwd: Path | None = None -) -> list[tuple[str, dict[str, str]]]: - """Puzzles whose ``path`` matches current directory.""" - here = rel_path(Path(cfg.root), cwd).strip("./") - out: list[tuple[str, dict[str, str]]] = [] - for pid, raw in cfg.puzzles.items(): - p = normalize_quest(raw) - pp = (p.get("path") or ".").strip().strip("/") - if ( - not pp - or pp == "." - or here == pp - or here.startswith(pp + "/") - or pp.startswith(here + "/") - ): - out.append((pid, p)) - return out - - -def _quest_line(pid: str, p: dict[str, str]) -> str: - kind = p.get("kind") or "task" - title = p.get("title") or pid - path = p.get("path") or "." - status = p.get("status") or "open" - assign = p.get("assign_to") or "" - line = f" {pid} [{kind}/{status}] {title} @ {path}" - if assign: - line += f" → {assign}" - return line - - -def format_puzzles( - cfg: WorkspaceConfig, *, cwd: Path | None = None, all_: bool = False -) -> str: - items = sorted(cfg.puzzles.items()) if all_ else puzzles_at(cfg, cwd) - if not items: - return "(no puzzles — add to .pulsing/cluster.json)" - lines = [f"Puzzles ({cfg.name}):"] - for pid, raw in items: - p = normalize_quest(raw) - lines.append(_quest_line(pid, p)) - if p.get("blurb"): - lines.append(f" {p['blurb']}") - return "\n".join(lines) - - -def render_look( - cfg: WorkspaceConfig, - *, - cwd: Path | None = None, - npc_rows: list[dict[str, Any]] | None = None, -) -> str: - root = Path(cfg.root) - here = rel_path(root, cwd) - player = player_name() - seed = cfg.seed_addr() - lines = [ - f"═══ {cfg.name} ═══", - f"player: {player} · path: {here} · {root if here == '.' else root / here}", - ] - if cfg.shared_tool_worker: - lines.append("tools: shared isolated worker") - lines.append( - f"node: {seed}" if seed else "node: (sleeping — run `pulsing agent wake`)", - ) - local = puzzles_at(cfg, cwd) - if local: - lines.append("\nQuests here:") - for pid, raw in local: - lines.append(_quest_line(pid, normalize_quest(raw))) - if npc_rows: - lines.append("\nNPCs:") - for r in npc_rows: - lines.append(f" {r.get('name', '?')}") - elif seed: - lines.append( - "\nAgents: (none — `pulsing agent wake` or `pulsing agent spawn NAME`)" - ) - lines.append("\nCommands: pulsing agent dashboard · watch · say …") - return "\n".join(lines) diff --git a/python/pulsing/cli/__main__.py b/python/pulsing/cli/__main__.py index ceb4d1b2d..b26677324 100644 --- a/python/pulsing/cli/__main__.py +++ b/python/pulsing/cli/__main__.py @@ -8,7 +8,7 @@ @hp.param("actor") def actor( - actor_type: str, # Positional argument: full class path (e.g., 'pulsing.serving.worker.TransformersWorker') + actor_type: str, # Positional argument: full class path (e.g., 'my_app.Counter') addr: str | None = None, seeds: str | None = None, name: str = "worker", # Actor name (default: "worker") @@ -23,9 +23,7 @@ def actor( Actor type must be a full class path: - Format: 'module.path.ClassName' - - Example: 'pulsing.serving.Router' - - Example: 'pulsing.serving.TransformersWorker' - - Example: 'pulsing.serving.VllmWorker' + - Example: 'my_app.Counter' - Example: 'my_module.my_actor.MyCustomActor' Parameter separation (avoids name collision): @@ -35,7 +33,7 @@ def actor( Note: To list actors, use 'pulsing inspect actors' instead. Args: - actor_type: Full class path (positional), e.g. pulsing.serving.Router + actor_type: Full class path (positional), e.g. my_app.Counter addr: Bind address (e.g. 0.0.0.0:8000) seeds: Comma-separated seed nodes (e.g. 192.168.1.1:8000,192.168.1.2:8000) name: Actor name (default: worker). Use different names for multiple workers. @@ -43,17 +41,11 @@ def actor( Examples: # Actor-level before \"--\", constructor args after (no collision) - pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 --name my-llm -- --model_name my-llm --http_port 8080 - - # Start a Transformers worker - pulsing actor pulsing.serving.TransformersWorker --addr 0.0.0.0:8000 -- --model_name gpt2 --device cpu - - # Start a Router (constructor args after --) - pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 --name my-llm -- --http_host 0.0.0.0 --http_port 8080 --model_name my-llm --worker_name worker + pulsing actor my_app.Counter --addr 0.0.0.0:8000 --name counter -- --initial 10 # Multiple workers - pulsing actor pulsing.serving.TransformersWorker --name worker-1 --seeds 127.0.0.1:8000 -- --model_name gpt2 - pulsing actor pulsing.serving.TransformersWorker --name worker-2 --seeds 127.0.0.1:8000 -- --model_name gpt2 + pulsing actor my_app.Counter --name counter-1 --seeds 127.0.0.1:8000 + pulsing actor my_app.Counter --name counter-2 --seeds 127.0.0.1:8000 """ from .actors import start_generic_actor @@ -68,9 +60,9 @@ def actor( # Check if actor_type is a valid class path (must contain dots) if "." not in actor_type: raise ValueError( - f"Error: Actor type must be a full class path (e.g., 'pulsing.serving.worker.TransformersWorker').\n" + f"Error: Actor type must be a full class path (e.g., 'my_app.Counter').\n" f"Received: '{actor_type}'\n" - f"Example: pulsing actor pulsing.serving.worker.TransformersWorker --model_name gpt2" + f"Example: pulsing actor my_app.Counter --name counter" ) # Parse seeds @@ -195,79 +187,6 @@ def inspect( print("Supported subcommands: cluster, actors, metrics, watch") -@hp.param("bench") -def bench( - model: str, # Positional argument - url: str = "http://localhost:8000", - api_key: str = "", - tokenizer: str | None = None, - hf_token: str | None = None, - max_vus: int = 128, - duration: str = "120s", - warmup: str = "30s", - benchmark_kind: str = "throughput", - num_rates: int = 10, - rates: list | None = None, - num_workers: int = 4, -): - """ - Run inference benchmarks. - - This command runs the pulsing benchmark tool to test LLM inference endpoints. - It uses an Actor-based architecture for real-time metrics and high performance. - - Args: - model: The name of the model to benchmark (positional, required) - url: Backend URL (default: "http://localhost:8000") - api_key: API key for authentication (default: "") - tokenizer: HuggingFace tokenizer name for accurate token counting (default: same as model) - hf_token: HuggingFace token for private models (default: from HF_TOKEN env) - max_vus: Maximum number of virtual users / concurrent requests (default: 128) - duration: Duration of each benchmark phase (default: "120s") - warmup: Warmup duration (default: "30s") - benchmark_kind: Kind of benchmark (default: "throughput") - - throughput: Max throughput test with constant VUs - - sweep: Auto-discover max rate then sweep rates - - csweep: Concurrency sweep (vary VUs) - - rate: Test specific rates - num_rates: Number of rate steps for sweep (default: 10) - rates: Specific rates for rate benchmark (comma-separated) - num_workers: Number of worker actors (default: 4) - - Examples: - # Basic throughput test (uses model name for tokenizer) - pulsing bench gpt2 --url http://localhost:8080 - - # Use different tokenizer - pulsing bench gpt-4 --tokenizer gpt2 --url http://api.openai.com - - # Concurrency sweep test - pulsing bench gpt2 --benchmark_kind csweep --max_vus 64 - - # Rate test with specific rates - pulsing bench gpt2 --benchmark_kind rate --rates 1,5,10,20 - - # Long duration test with more workers - pulsing bench gpt2 --duration 300s --num_workers 8 - """ - from .bench import run_benchmark - - run_benchmark( - model_name=model, - url=url, - api_key=api_key, - tokenizer_name=tokenizer, - hf_token=hf_token, - max_vus=max_vus, - duration=duration, - warmup=warmup, - benchmark_kind=benchmark_kind, - num_rates=num_rates, - rates=rates, - num_workers=num_workers, - ) - - @hp.param("examples") def examples(name: str | None = None): """ @@ -332,18 +251,6 @@ def main(): args.func(args) return - if len(sys.argv) >= 2 and sys.argv[1] == "agent": - from pulsing.cli.agent.main import main as main_agent - - main_agent(sys.argv[2:], prog="pulsing agent") - return - - if len(sys.argv) >= 2 and sys.argv[1] == "forge": - from pulsing.forge.cli import main_pulsing_forge - - main_pulsing_forge(sys.argv[2:]) - return - if len(sys.argv) == 1 or ( len(sys.argv) == 2 and sys.argv[1] in ("-h", "--help", "help") ): diff --git a/python/pulsing/cli/actor_loader.py b/python/pulsing/cli/actor_loader.py index ffb85f461..95ac105f0 100644 --- a/python/pulsing/cli/actor_loader.py +++ b/python/pulsing/cli/actor_loader.py @@ -10,7 +10,7 @@ def load_actor_class(class_path: str) -> Union[type[Actor], Any]: """Load Actor 或 @remote 类 Args: - class_path: 完整类路径,如 'pulsing.serving.worker.TransformersWorker' + class_path: 完整类路径,如 'my_app.Counter' Returns: Actor 子类或带 .spawn 的 @remote 类 @@ -22,7 +22,7 @@ def load_actor_class(class_path: str) -> Union[type[Actor], Any]: if "." not in class_path: raise ValueError( f"Invalid class path '{class_path}'. Expected format: 'module.path.ClassName'\n" - f"Example: pulsing.serving.worker.TransformersWorker" + f"Example: my_app.Counter" ) parts = class_path.rsplit(".", 1) diff --git a/python/pulsing/cli/actors.py b/python/pulsing/cli/actors.py index d48ec343e..533d430dd 100644 --- a/python/pulsing/cli/actors.py +++ b/python/pulsing/cli/actors.py @@ -15,7 +15,7 @@ def start_generic_actor( """Start a generic Actor class by full module path Args: - actor_type: Full class path, e.g., 'pulsing.serving.worker.TransformersWorker' + actor_type: Full class path, e.g., 'my_app.Counter' addr: Actor System bind address seeds: List of seed node addresses name: Actor name diff --git a/python/pulsing/cli/agent/__init__.py b/python/pulsing/cli/agent/__init__.py deleted file mode 100644 index 8da2197b4..000000000 --- a/python/pulsing/cli/agent/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""``pulsing agent`` CLI.""" diff --git a/python/pulsing/cli/agent/__main__.py b/python/pulsing/cli/agent/__main__.py deleted file mode 100644 index b4513914b..000000000 --- a/python/pulsing/cli/agent/__main__.py +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""``python -m pulsing.cli.agent`` entry.""" - -from pulsing.cli.agent.main import main - -if __name__ == "__main__": - main() diff --git a/python/pulsing/cli/agent/commands/__init__.py b/python/pulsing/cli/agent/commands/__init__.py deleted file mode 100644 index 53aa87df9..000000000 --- a/python/pulsing/cli/agent/commands/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""``pulsing agent`` subcommand handlers.""" diff --git a/python/pulsing/cli/agent/commands/agent_cmd.py b/python/pulsing/cli/agent/commands/agent_cmd.py deleted file mode 100644 index 61eec95f4..000000000 --- a/python/pulsing/cli/agent/commands/agent_cmd.py +++ /dev/null @@ -1,51 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tail one agent's in-memory log stream.""" - -from __future__ import annotations - -import asyncio -from argparse import Namespace - -import pulsing as pul - -from pulsing.agent.cluster.resolve import resolve_agent -from pulsing.cli.agent.helpers import DEFAULT_PROG, load_cfg, with_session - - -async def run_logs(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - name = (args.name or "").strip() - if not name: - raise SystemExit(f"usage: {prog} logs [-f]") - cfg = load_cfg() - follow = bool(getattr(args, "follow", False)) - interval = max(0.2, float(getattr(args, "interval", 0.8))) - since = max(0, int(getattr(args, "since", 0))) - - async def _tail_once() -> int: - proxy = await resolve_agent( - pul.get_system(), - name, - workspace_id=cfg.cluster_id, - timeout=30.0, - ) - chunk = await proxy.get_logs(since=since) - if not isinstance(chunk, dict): - return since - for line in chunk.get("lines") or []: - print(line, flush=True) - return int(chunk.get("next") or since) - - async def _go() -> None: - nonlocal since - if not follow: - since = await _tail_once() - return - print(f"── {name} log (follow) ──", flush=True) - while True: - since = await _tail_once() - await asyncio.sleep(interval) - - try: - await with_session(cfg, _go) - except KeyboardInterrupt: - print("\n(stopped)") diff --git a/python/pulsing/cli/agent/commands/dashboard.py b/python/pulsing/cli/agent/commands/dashboard.py deleted file mode 100644 index 90fa19752..000000000 --- a/python/pulsing/cli/agent/commands/dashboard.py +++ /dev/null @@ -1,318 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Split-terminal dashboard via Zellij (Rust) or tmux fallback.""" - -from __future__ import annotations - -import os -import re -import shlex -import shutil -import subprocess -import sys -from argparse import Namespace -from pathlib import Path - -from pulsing.cli.agent.helpers import DEFAULT_PROG, load_cfg -from pulsing.agent.workspace.config import WorkspaceConfig - -DASHBOARD_LAYOUT = "dashboard.kdl" -DEMO_LAYOUT = "demo.kdl" -ZELLIJ_SESSION = "pulsing-agent-dashboard" -ZELLIJ_DEMO_SESSION = "pulsing-agent-demo" -TMUX_SESSION = "pulsing-agent-dashboard" -DEMO_WORKER_ENV = "PULSING_AGENT_DEMO_WORKER" - - -def agent_cli_argv(*args: str) -> list[str]: - exe = shutil.which("pulsing-agent") - if exe: - return [exe, *args] - return [sys.executable, "-m", "pulsing.cli.agent", *args] - - -def _kdl_str(value: str) -> str: - return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' - - -def _follow_shell_cmd(argv: list[str], interval: float) -> str: - cmd = " ".join(shlex.quote(part) for part in argv) - return f"while [ ! -f .pulsing/node.json ]; do sleep 0.5; done; exec {cmd}" - - -def _agent_names(cfg: WorkspaceConfig) -> list[str]: - names = [n.strip() for n in (cfg.default_agents or []) if n.strip()] - return names or ["guide"] - - -def _agent_log_panes( - agent_names: list[str], - *, - interval: float, - indent: str = " ", -) -> list[str]: - names = [n.strip() for n in agent_names if n.strip()] or ["guide"] - log_interval = max(0.5, interval) - lines: list[str] = [f'{indent}pane split_direction="vertical" {{'] - inner = indent + " " - for name in names: - logs = agent_cli_argv("logs", name, "-f", "-i", str(log_interval)) - run = _follow_shell_cmd(logs, log_interval) - lines.extend( - [ - f'{inner}pane name="{name}" command="bash" {{', - f" {inner}args {_kdl_str('-c')} {_kdl_str(run)}", - f"{inner}}}", - ], - ) - lines.append(f"{indent}}}") - return lines - - -def write_zellij_layout( - cfg: WorkspaceConfig, - *, - interval: float = 0.8, - agent_names: list[str] | None = None, -) -> Path: - root = Path(cfg.root).resolve() - cfg.pulsing_dir.mkdir(parents=True, exist_ok=True) - path = cfg.pulsing_dir / DASHBOARD_LAYOUT - names = agent_names if agent_names is not None else _agent_names(cfg) - - lines = [ - "// Generated by pulsing agent dashboard — per-agent log panes", - "layout {", - f" cwd {_kdl_str(str(root))}", - ' pane split_direction="vertical" {', - ' pane size="70%" {', - ] - lines.extend(_agent_log_panes(names, interval=interval)) - lines.extend( - [ - " }", - ' pane name="player" command="bash" {', - f" args {_kdl_str('-c')} {_kdl_str(_player_shell_hint(DEFAULT_PROG))}", - " }", - " }", - "}", - "", - ], - ) - path.write_text("\n".join(lines), encoding="utf-8") - return path - - -def write_zellij_demo_layout( - cfg: WorkspaceConfig, - *, - demo_shell: str, - interval: float = 0.8, - agent_names: list[str] | None = None, -) -> Path: - root = Path(cfg.root).resolve() - cfg.pulsing_dir.mkdir(parents=True, exist_ok=True) - path = cfg.pulsing_dir / DEMO_LAYOUT - names = agent_names if agent_names is not None else _agent_names(cfg) - - lines = [ - "// Generated by pulsing agent demo — demo worker + per-agent logs", - "layout {", - f" cwd {_kdl_str(str(root))}", - ' pane split_direction="horizontal" {', - ' pane size="38%" name="demo" command="bash" {', - f" args {_kdl_str('-c')} {_kdl_str(demo_shell)}", - " }", - ] - lines.extend(_agent_log_panes(names, interval=interval, indent=" ")) - lines.extend([" }", "}", ""]) - path.write_text("\n".join(lines), encoding="utf-8") - return path - - -def _player_shell_hint(prog: str) -> str: - return ( - f"echo 'Craft player shell — run {prog} npc say \"...\" here'; " - f"echo 'Agents log in panes above; wake world: {prog} wake'; " - "exec $SHELL" - ) - - -def find_backend(preferred: str = "auto") -> str: - choice = (preferred or "auto").strip().lower() - if choice == "zellij": - if shutil.which("zellij"): - return "zellij" - raise SystemExit( - "zellij not found — install: https://zellij.dev/documentation/installation.html " - "(Rust multiplexer; brew install zellij)", - ) - if choice == "tmux": - if shutil.which("tmux"): - return "tmux" - raise SystemExit("tmux not found") - if shutil.which("zellij"): - return "zellij" - if shutil.which("tmux"): - return "tmux" - raise SystemExit( - "no split-terminal backend found.\n" - " Recommended: zellij (Rust) — brew install zellij\n" - " Fallback: tmux — brew install tmux\n" - "Or run: pulsing agent logs -f", - ) - - -def _strip_ansi(text: str) -> str: - return re.sub(r"\x1b\[[0-9;]*m", "", text) - - -def _parse_zellij_session_line(line: str, session: str) -> str | None: - """Return 'active', 'exited', or None for one ``list-sessions`` line.""" - plain = _strip_ansi(line.strip()) - if not plain: - return None - name = (plain.split() or [""])[0] - if name != session: - return None - if "EXITED" in plain.upper(): - return "exited" - return "active" - - -def _zellij_session_state(session: str) -> str | None: - zellij = shutil.which("zellij") - if not zellij: - return None - out = subprocess.run( - [zellij, "list-sessions"], - capture_output=True, - text=True, - check=False, - ) - if out.returncode != 0: - return None - for line in out.stdout.splitlines(): - state = _parse_zellij_session_line(line, session) - if state is not None: - return state - return None - - -def _zellij_delete_session(session: str) -> None: - zellij = shutil.which("zellij") - if not zellij: - return - subprocess.run( - [zellij, "delete-session", "-f", session], - capture_output=True, - check=False, - ) - - -def _zellij_session_running(session: str) -> bool: - return _zellij_session_state(session) == "active" - - -def launch_zellij( - layout_path: Path, - *, - session: str = ZELLIJ_SESSION, - attach_only: bool = False, -) -> None: - zellij = shutil.which("zellij") - assert zellij - state = _zellij_session_state(session) - if state == "active": - os.execvp(zellij, [zellij, "attach", session]) - if state == "exited": - _zellij_delete_session(session) - if attach_only: - raise SystemExit(f"no zellij session {session!r} — start it first") - if not sys.stdin.isatty() or not sys.stdout.isatty(): - raise SystemExit( - "zellij needs an interactive terminal — run `pulsing agent dashboard` or `pulsing agent demo` " - "directly in your terminal (not from a background subprocess)", - ) - os.execvp( - zellij, - [zellij, "--new-session-with-layout", str(layout_path), "-s", session], - ) - - -def launch_tmux( - cfg: WorkspaceConfig, - *, - interval: float = 0.8, - prog: str = DEFAULT_PROG, - agent_names: list[str] | None = None, -) -> None: - tmux = shutil.which("tmux") - if not tmux: - raise SystemExit("tmux not found") - - root = str(Path(cfg.root).resolve()) - names = agent_names if agent_names is not None else _agent_names(cfg) - log_interval = max(0.5, interval) - hint = shlex.quote(_player_shell_hint(prog)) - - pane_cmds: list[str] = [] - for name in names: - logs = shlex.quote( - _follow_shell_cmd( - agent_cli_argv("logs", name, "-f", "-i", str(log_interval)), - log_interval, - ), - ) - pane_cmds.append(logs) - - script_lines = [ - "set -e", - f"if tmux has-session -t {TMUX_SESSION} 2>/dev/null; then", - f" exec tmux attach -t {TMUX_SESSION}", - "fi", - f"tmux new-session -d -s {TMUX_SESSION} -c {shlex.quote(root)} -n dash", - ] - if pane_cmds: - script_lines.append( - f"tmux send-keys -t {TMUX_SESSION}:0.0 {pane_cmds[0]} Enter" - ) - for i, cmd in enumerate(pane_cmds[1:], start=1): - script_lines.append( - f"tmux split-window -h -t {TMUX_SESSION}:0 -c {shlex.quote(root)}" - ) - script_lines.append(f"tmux send-keys -t {TMUX_SESSION}:0.{i} {cmd} Enter") - script_lines.append( - f"tmux split-window -v -t {TMUX_SESSION}:0 -c {shlex.quote(root)}" - ) - player_idx = len(pane_cmds) - script_lines.append( - f"tmux send-keys -t {TMUX_SESSION}:0.{player_idx} {hint} Enter" - ) - script_lines.append(f"tmux select-pane -t {TMUX_SESSION}:0.{player_idx}") - else: - script_lines.append(f"tmux send-keys -t {TMUX_SESSION}:0.0 {hint} Enter") - script_lines.append(f"exec tmux attach -t {TMUX_SESSION}") - subprocess.run(["bash", "-c", "\n".join(script_lines)], check=True) - - -def run_dashboard(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - cfg = load_cfg() - backend = find_backend(getattr(args, "backend", "auto")) - interval = float(getattr(args, "interval", 0.8)) - - if not cfg.seed_addr(): - print( - f"note: world asleep — start `{prog} wake` or `{prog} demo` first", - file=sys.stderr, - ) - - if backend == "zellij": - layout = write_zellij_layout(cfg, interval=interval) - print(f"opening Zellij dashboard ({layout})", file=sys.stderr) - launch_zellij(layout) - return - - print( - "opening tmux dashboard (install zellij for Rust multiplexer)", file=sys.stderr - ) - launch_tmux(cfg, interval=interval, prog=prog) diff --git a/python/pulsing/cli/agent/commands/demo.py b/python/pulsing/cli/agent/commands/demo.py deleted file mode 100644 index d99fc2021..000000000 --- a/python/pulsing/cli/agent/commands/demo.py +++ /dev/null @@ -1,222 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""One-shot demo: three chattering NPCs + optional Zellij split UI.""" - -from __future__ import annotations - -import asyncio -import os -import shlex -import shutil -import signal -import sys -from argparse import Namespace -from pathlib import Path - -import pulsing as pul - -from pulsing.agent.cluster.resolve import resolve_agent -from pulsing.cli.agent.commands.dashboard import ( - DEMO_WORKER_ENV, - ZELLIJ_DEMO_SESSION, - agent_cli_argv, - launch_zellij, - write_zellij_demo_layout, -) -from pulsing.cli.agent.helpers import DEFAULT_PROG, spawn_npc -from pulsing.agent.npc.loader import seed_npc_defs -from pulsing.agent.workspace.config import ( - WorkspaceConfig, - clear_node_record, - default_config, - load_config, - save_config, - write_node_record, -) -from pulsing.agent.workspace.root import find_workspace_root -from pulsing.agent.workspace.session import workspace_session -from pulsing.agent.workspace.tool_pool import spawn_shared_tool_worker - -DEMO_AGENTS: list[tuple[str, str, str]] = [ - ("bard", "quest_giver", "storyteller"), - ("smith", "artisan", "builder"), - ("sage", "scholar", "reviewer"), -] - -CHATTER_SCRIPT: list[tuple[str, str, str]] = [ - ("bard", "smith", "List project files with Glob under ."), - ("smith", "sage", "Glob under tests — one line summary."), - ("sage", "bard", "Update unit-tests quest — use QuestReport in_progress."), - ("bard", "smith", "MessageClusterAgent to sage: coordinate on tests path."), - ("smith", "bard", "Glob the tests directory and report."), - ("sage", "smith", "Peer review: any blockers for unit-tests quest?"), -] - - -def _demo_llm_options(cfg: WorkspaceConfig, args: Namespace) -> dict: - if getattr(args, "real_llm", False): - from pulsing.cli.agent.helpers import llm_options - - return llm_options(cfg, args) - from pulsing.forge.host.llm import llm_runtime_options - - return llm_runtime_options( - provider="demo", - model="demo", - auto_approve=True, - sandbox=cfg.sandbox, - ) - - -def prepare_demo_workspace(root: Path, *, prog: str = DEFAULT_PROG) -> WorkspaceConfig: - root = root.resolve() - existing = find_workspace_root(root) - if existing: - cfg = load_config(existing) - else: - cfg = default_config(root) - seed_npc_defs(root) - cfg.default_agents = [a[0] for a in DEMO_AGENTS] - cfg.shared_tool_worker = True - cfg.auto_approve = True - puzzles = dict(cfg.puzzles) - unit = dict(puzzles.get("unit-tests") or {}) - unit["assign_to"] = "sage" - unit["status"] = "open" - puzzles["unit-tests"] = unit - cfg.puzzles = puzzles - save_config(cfg) - return cfg - - -def demo_worker_shell(args: Namespace, *, prog: str = DEFAULT_PROG) -> str: - argv = list(agent_cli_argv("demo", "--no-dashboard")) - if getattr(args, "real_llm", False): - argv.append("--real-llm") - argv.extend(["--interval", str(float(getattr(args, "interval", 6.0)))]) - addr = getattr(args, "addr", None) - if addr: - argv.extend(["--addr", str(addr)]) - cmd = " ".join(shlex.quote(p) for p in argv) - return f"export {DEMO_WORKER_ENV}=1; {cmd}" - - -def try_exec_demo_zellij( - cfg: WorkspaceConfig, - args: Namespace, - *, - prog: str = DEFAULT_PROG, - log_interval: float = 0.8, -) -> None: - if getattr(args, "no_dashboard", False): - return - if os.environ.get(DEMO_WORKER_ENV): - return - if not shutil.which("zellij"): - print( - f"tip: install zellij for split-screen — brew install zellij; or `{prog} agent logs bard -f`", - file=sys.stderr, - ) - return - if not sys.stdin.isatty() or not sys.stdout.isatty(): - print( - f"non-interactive shell — run `{prog} agent logs bard -f` in another terminal", - file=sys.stderr, - ) - return - layout = write_zellij_demo_layout( - cfg, - demo_shell=demo_worker_shell(args, prog=prog), - interval=log_interval, - agent_names=[a[0] for a in DEMO_AGENTS], - ) - print(f"opening Zellij demo ({layout})", file=sys.stderr) - launch_zellij(layout, session=ZELLIJ_DEMO_SESSION) - - -async def _chatter_loop( - cfg: WorkspaceConfig, - *, - interval: float, - stop: asyncio.Event, -) -> None: - i = 0 - while not stop.is_set(): - from_name, to_name, message = CHATTER_SCRIPT[i % len(CHATTER_SCRIPT)] - i += 1 - try: - proxy = await resolve_agent( - pul.get_system(), - to_name, - workspace_id=cfg.cluster_id, - timeout=30.0, - ) - await proxy.deliver_message( - from_name, - message, - channel="whisper", - wait=False, - ) - except Exception as e: - print(f"chatter {from_name}→{to_name}: {e!r}", file=sys.stderr) - try: - await asyncio.wait_for(stop.wait(), timeout=max(2.0, interval)) - except asyncio.TimeoutError: - pass - - -async def run_demo(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - root = Path.cwd().resolve() - cfg = prepare_demo_workspace(root, prog=prog) - try_exec_demo_zellij(cfg, args, prog=prog) - - llm = _demo_llm_options(cfg, args) - interval = float(getattr(args, "interval", 6.0)) - - stop = asyncio.Event() - loop = asyncio.get_running_loop() - for sig in (signal.SIGINT, signal.SIGTERM): - try: - loop.add_signal_handler(sig, stop.set) - except NotImplementedError: - signal.signal(sig, lambda *_: stop.set()) - - print( - f"demo world {cfg.cluster_id} — agents: {', '.join(a[0] for a in DEMO_AGENTS)}", - file=sys.stderr, - ) - if llm["provider"] == "demo": - print( - "using demo LLM (no API key) — pass --real-llm for live models", - file=sys.stderr, - ) - - try: - async with workspace_session( - cfg, bind_addr=getattr(args, "addr", "127.0.0.1:0") - ) as system: - write_node_record(cfg, addr=str(system.addr), pid=os.getpid()) - await spawn_shared_tool_worker(cfg) - for name, npc_class, role in DEMO_AGENTS: - await spawn_npc( - cfg, - name, - llm, - role=role, - npc_class=npc_class, - shared_tool_worker=True, - ) - chatter = asyncio.create_task( - _chatter_loop(cfg, interval=interval, stop=stop), - ) - print( - f"awake at {system.addr} — chattering every {interval}s (Ctrl+C to stop)", - file=sys.stderr, - ) - await stop.wait() - chatter.cancel() - try: - await chatter - except asyncio.CancelledError: - pass - finally: - clear_node_record(cfg) diff --git a/python/pulsing/cli/agent/commands/follow.py b/python/pulsing/cli/agent/commands/follow.py deleted file mode 100644 index 366d2e957..000000000 --- a/python/pulsing/cli/agent/commands/follow.py +++ /dev/null @@ -1,45 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Append-only follow loops for dashboard panes.""" - -from __future__ import annotations - -import asyncio -import sys -from collections.abc import Awaitable, Callable -from datetime import datetime - -PrintFn = Callable[[], Awaitable[str]] - - -def should_emit(prev: str, text: str, *, delta: bool) -> bool: - return (not delta) or (text != prev) - - -async def follow_output( - produce: PrintFn, - *, - interval: float, - scroll: bool = True, - delta: bool = True, -) -> None: - """Poll ``produce``; append to terminal (scroll) instead of full-screen refresh.""" - prev = "" - sec = max(0.1, interval) - try: - while True: - text = (await produce()).rstrip() - if should_emit(prev, text, delta=delta): - stamp = datetime.now().strftime("%H:%M:%S") - print(f"── {stamp} ──") - print(text) - print(flush=True) - prev = text - elif not scroll: - # fixed viewport: overwrite last block (unused today) - pass - await asyncio.sleep(sec) - except asyncio.CancelledError: - raise - except KeyboardInterrupt: - if scroll: - print("\n(stopped)") diff --git a/python/pulsing/cli/agent/commands/npc.py b/python/pulsing/cli/agent/commands/npc.py deleted file mode 100644 index dcc2d9fa9..000000000 --- a/python/pulsing/cli/agent/commands/npc.py +++ /dev/null @@ -1,71 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""NPC commands: who, summon, say.""" - -from __future__ import annotations - -from argparse import Namespace - -import pulsing as pul - -from pulsing.agent.cluster.discovery import list_cluster_agents -from pulsing.agent.cluster.resolve import resolve_agent -from pulsing.agent.workspace.world_view import player_name -from pulsing.cli.agent.helpers import ( - DEFAULT_PROG, - llm_options, - load_cfg, - spawn_npc, - with_session, -) - - -async def run_who(_args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - cfg = load_cfg() - - async def _go() -> None: - rows = await list_cluster_agents(pul.get_system(), workspace_id=cfg.cluster_id) - if not rows: - print("(no NPCs)") - return - for row in rows: - print(row.get("name", "?")) - - await with_session(cfg, _go) - - -async def run_summon(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - cfg = load_cfg() - llm = llm_options(cfg, args) - - async def _go() -> None: - await spawn_npc(cfg, args.name, llm, role=args.role) - - await with_session(cfg, _go) - print(f"summoned {args.name}") - - -async def run_say(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - cfg = load_cfg() - msg = " ".join(args.message or []).strip() - if not msg: - raise SystemExit(f"usage: {prog} npc say message…") - - async def _go() -> None: - proxy = await resolve_agent( - pul.get_system(), - args.name, - workspace_id=cfg.cluster_id, - ) - out = await proxy.deliver_message( - from_sender=player_name(), - message=msg, - channel="say", - ) - body = ( - out.get("assistant_text") or out.get("error") - if isinstance(out, dict) - else out - ) - print(f"\n{args.name} › {body}") - - await with_session(cfg, _go) diff --git a/python/pulsing/cli/agent/commands/puzzle.py b/python/pulsing/cli/agent/commands/puzzle.py deleted file mode 100644 index c24423fc1..000000000 --- a/python/pulsing/cli/agent/commands/puzzle.py +++ /dev/null @@ -1,85 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Puzzle commands: list, show, mark.""" - -from __future__ import annotations - -import asyncio -from argparse import Namespace -from pathlib import Path - -from pulsing.agent.workspace.config import WorkspaceConfig, load_config, save_config -from pulsing.agent.workspace.quest import ( - QUEST_STATUSES, - normalize_quest, - update_quest_status, -) -from pulsing.agent.workspace.world_view import format_puzzles -from pulsing.cli.agent.helpers import DEFAULT_PROG, load_cfg - - -def _format_one(cfg: WorkspaceConfig, pid: str) -> str: - puzzle = normalize_quest(cfg.puzzles.get(pid, {})) - if pid not in cfg.puzzles: - raise SystemExit(f"unknown puzzle {pid!r}") - kind = puzzle.get("kind") or "task" - title = puzzle.get("title") or pid - path = puzzle.get("path") or "." - status = puzzle.get("status") or "open" - assign = puzzle.get("assign_to") or "" - lines = [f"{pid} [{kind}/{status}] {title} @ {path}"] - if assign: - lines.append(f" assign_to: {assign}") - if puzzle.get("blurb"): - lines.append(f" {puzzle['blurb']}") - if puzzle.get("last_note"): - lines.append(f" note: {puzzle['last_note']}") - return "\n".join(lines) - - -async def run_list(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - if not getattr(args, "follow", False): - print(format_puzzles(load_cfg(), all_=True)) - return - - from pulsing.cli.agent.commands.follow import follow_output - - interval = max(0.5, float(getattr(args, "interval", 5.0))) - - async def produce() -> str: - return format_puzzles(load_cfg(), all_=True) - - try: - await follow_output( - produce, - interval=interval, - scroll=True, - delta=not getattr(args, "no_delta", False), - ) - except asyncio.CancelledError: - raise - except KeyboardInterrupt: - print("\n(stopped)") - - -async def run_show(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - print(_format_one(load_cfg(), args.id)) - - -async def run_mark(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - cfg = load_cfg() - pid = args.id - if pid not in cfg.puzzles: - raise SystemExit(f"unknown puzzle {pid!r}") - status = args.status - if status not in QUEST_STATUSES: - raise SystemExit(f"invalid status {status!r}") - root = Path(cfg.root) - updated = update_quest_status(root, pid, status=status, reporter="player") - if args.assign_to is not None: - cfg = load_config(root) - p = normalize_quest(cfg.puzzles[pid]) - p["assign_to"] = args.assign_to.strip() - cfg.puzzles[pid] = p - save_config(cfg) - updated = p - print(_format_one(load_config(root), pid)) diff --git a/python/pulsing/cli/agent/commands/watch.py b/python/pulsing/cli/agent/commands/watch.py deleted file mode 100644 index a1682d3cd..000000000 --- a/python/pulsing/cli/agent/commands/watch.py +++ /dev/null @@ -1,67 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Watch cluster NPC activity.""" - -from __future__ import annotations - -import asyncio -import sys -from argparse import Namespace -from datetime import datetime - -import pulsing as pul - -from pulsing.agent.cluster.activity import ( - collect_cluster_activity, - format_activity_table, -) -from pulsing.cli.agent.commands.follow import follow_output -from pulsing.cli.agent.helpers import DEFAULT_PROG, load_cfg, with_session - - -async def _activity_text(args: Namespace) -> str: - cfg = load_cfg() - buf = "" - - async def _go() -> None: - nonlocal buf - rows = await collect_cluster_activity( - pul.get_system(), - workspace_id=cfg.cluster_id, - local_node_only=bool(getattr(args, "local", False)), - ) - title = f"{cfg.name} activity" - buf = format_activity_table(rows, title=title) - - await with_session(cfg, _go) - return buf - - -async def run_watch(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - if not getattr(args, "follow", False): - print(await _activity_text(args)) - return - - interval = max(0.5, float(getattr(args, "interval", 2.0))) - scroll = bool(getattr(args, "scroll", False)) - delta = not getattr(args, "no_delta", False) - - try: - if scroll: - await follow_output( - lambda: _activity_text(args), - interval=interval, - scroll=True, - delta=delta, - ) - return - while True: - if sys.stdout.isatty(): - print("\033[2J\033[H", end="") - stamp = datetime.now().strftime("%H:%M:%S") - print(f"{load_cfg().name} @ {stamp}") - print(await _activity_text(args)) - await asyncio.sleep(interval) - except asyncio.CancelledError: - raise - except KeyboardInterrupt: - print("\n(stopped)") diff --git a/python/pulsing/cli/agent/commands/world.py b/python/pulsing/cli/agent/commands/world.py deleted file mode 100644 index 370df40f8..000000000 --- a/python/pulsing/cli/agent/commands/world.py +++ /dev/null @@ -1,115 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace commands: init, wake, look, sleep.""" - -from __future__ import annotations - -import asyncio -import os -import signal -import sys -from argparse import Namespace -from pathlib import Path - -from pulsing.agent.workspace.config import ( - clear_node_record, - load_config, - save_config, -) -from pulsing.agent.workspace.config import write_node_record -from pulsing.agent.workspace.root import find_workspace_root -from pulsing.agent.workspace.session import workspace_session -from pulsing.agent.workspace.tool_pool import spawn_shared_tool_worker -from pulsing.agent.workspace.world_view import render_look -from pulsing.cli.agent.helpers import DEFAULT_PROG, list_npcs, llm_options, spawn_npc - - -async def run_init(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - from pulsing.workspace.bootstrap import init_workspace - - root = Path.cwd().resolve() - template = getattr(args, "template", "agent") or "agent" - force = bool(getattr(args, "force", False)) - guide_flag = getattr(args, "guide", None) - guide_words = getattr(args, "guide_words", None) or [] - if guide_flag and str(guide_flag).strip(): - guide = str(guide_flag).strip() - elif guide_words: - guide = " ".join(guide_words) - else: - guide = None - result = init_workspace( - root, - template=template, - force=force, - guide=guide, - provider=getattr(args, "provider", None), - model=getattr(args, "model", None), - ) - if result.created: - print(f"initialized {result.root} → {prog} wake · {prog} dashboard") - else: - print(f"already initialized: {result.root}") - - -async def run_look(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - root = find_workspace_root() - if not root: - print(f"no workspace — run `{prog} init`") - return - - async def produce() -> str: - cfg = load_config(root) - rows = await list_npcs(cfg) - return render_look(cfg, npc_rows=rows) - - if not getattr(args, "follow", False): - print(await produce()) - return - - from pulsing.cli.agent.commands.follow import follow_output - - interval = max(0.5, float(getattr(args, "interval", 5.0))) - try: - await follow_output( - produce, - interval=interval, - scroll=True, - delta=not getattr(args, "no_delta", False), - ) - except asyncio.CancelledError: - raise - except KeyboardInterrupt: - print("\n(stopped)") - - -async def run_wake(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - from pulsing.cli.agent.helpers import load_cfg - - cfg = load_cfg() - llm = llm_options(cfg, args) - shared = bool(getattr(args, "shared_tool_worker", False) or cfg.shared_tool_worker) - if shared and not cfg.shared_tool_worker: - cfg.shared_tool_worker = True - save_config(cfg) - stop = asyncio.Event() - loop = asyncio.get_running_loop() - for sig in (signal.SIGINT, signal.SIGTERM): - try: - loop.add_signal_handler(sig, stop.set) - except NotImplementedError: - signal.signal(sig, lambda *_: stop.set()) - async with workspace_session(cfg, bind_addr=args.addr) as system: - write_node_record(cfg, addr=str(system.addr), pid=os.getpid()) - if shared: - await spawn_shared_tool_worker(cfg) - for part in (args.agents or ",".join(cfg.default_agents)).split(","): - name = part.strip() - if name: - await spawn_npc(cfg, name, llm, shared_tool_worker=shared) - print(f"awake at {system.addr} — try: {prog} dashboard", file=sys.stderr) - await stop.wait() - clear_node_record(cfg) - - -async def run_sleep(_args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - raise SystemExit(f"{prog} sleep is not implemented yet") diff --git a/python/pulsing/cli/agent/helpers.py b/python/pulsing/cli/agent/helpers.py deleted file mode 100644 index 1e21f110f..000000000 --- a/python/pulsing/cli/agent/helpers.py +++ /dev/null @@ -1,79 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Shared ``pulsing agent`` CLI helpers.""" - -from __future__ import annotations - -import os -from typing import Any - -import pulsing as pul - -from pulsing.agent.cluster.constants import full_agent_name -from pulsing.agent.cluster.discovery import list_cluster_agents -from pulsing.agent.npc import spawn_npc as _spawn_npc -from pulsing.agent.npc.config import NpcConfig -from pulsing.forge.host.llm import llm_runtime_options -from pulsing.agent.workspace.config import WorkspaceConfig, load_config -from pulsing.agent.workspace.root import require_workspace_root -from pulsing.agent.workspace.session import workspace_session - -DEFAULT_PROG = "pulsing agent" - - -def load_cfg() -> WorkspaceConfig: - return load_config(require_workspace_root()) - - -def llm_options(cfg: WorkspaceConfig, args: Any) -> dict[str, Any]: - from pulsing.agent.loop.deps import require_provider_deps - - provider = getattr(args, "provider", None) or cfg.provider - require_provider_deps(provider) - return llm_runtime_options( - provider=provider, - model=getattr(args, "model", None) or cfg.model, - auto_approve=bool(getattr(args, "auto_approve", False) or cfg.auto_approve), - sandbox=cfg.sandbox, - ) - - -async def spawn_npc( - cfg: WorkspaceConfig, - name: str, - llm: dict[str, Any], - *, - role: str = "", - npc_class: str = "artisan", - shared_tool_worker: bool | None = None, -) -> Any: - config = NpcConfig( - model=llm["model"], - cwd=cfg.root, - agent_name=name, - workspace_id=cfg.cluster_id, - provider=llm["provider"], - auto_approve=llm["auto_approve"], - sandbox_policy=llm["sandbox"], - agent_role=role, - npc_class=npc_class, - shared_tool_worker=( - cfg.shared_tool_worker if shared_tool_worker is None else shared_tool_worker - ), - ) - return await _spawn_npc( - config, - name=full_agent_name(name, workspace_id=cfg.cluster_id), - public=True, - ) - - -async def with_session(cfg: WorkspaceConfig, fn: Any) -> None: - async with workspace_session(cfg): - await fn() - - -async def list_npcs(cfg: WorkspaceConfig) -> list[dict[str, Any]] | None: - if not cfg.seed_addr(): - return None - async with workspace_session(cfg): - return await list_cluster_agents(pul.get_system(), workspace_id=cfg.cluster_id) diff --git a/python/pulsing/cli/agent/main.py b/python/pulsing/cli/agent/main.py deleted file mode 100644 index 0db9e014d..000000000 --- a/python/pulsing/cli/agent/main.py +++ /dev/null @@ -1,252 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Agent CLI: ``pulsing agent``.""" - -from __future__ import annotations - -import argparse -import asyncio -import sys -from argparse import Namespace -from collections.abc import Sequence - -from pulsing.cli.agent.commands import ( - agent_cmd, - dashboard, - demo, - npc, - puzzle, - watch, - world, -) - -DEFAULT_PROG = "pulsing agent" - - -def _build_parser(prog: str = DEFAULT_PROG) -> argparse.ArgumentParser: - p = argparse.ArgumentParser( - prog=prog, - description="Agent workspace CLI (init, wake, spawn, task).", - ) - sub = p.add_subparsers(dest="cmd") - - init_p = sub.add_parser("init", help="create .pulsing/ workspace") - init_p.add_argument( - "guide_words", - nargs="*", - help="natural-language goal for LLM-guided bootstrap", - ) - init_p.add_argument( - "-g", - "--guide", - default=None, - help="same as trailing guide words", - ) - init_p.add_argument( - "--template", - choices=("minimal", "agent"), - default="agent", - ) - init_p.add_argument("--force", action="store_true") - init_p.add_argument( - "--provider", choices=("demo", "anthropic", "openai"), default=None - ) - init_p.add_argument("--model", default=None) - - w = sub.add_parser("wake", help="start node and run NPCs (blocking)") - w.add_argument("--agents", default=None) - w.add_argument("--addr", default="127.0.0.1:0") - w.add_argument("--auto-approve", action="store_true") - w.add_argument("--provider", choices=("anthropic", "openai", "demo")) - w.add_argument("--model") - w.add_argument( - "--shared-tool-worker", - action="store_true", - help="one isolated worker for all NPCs", - ) - - look_p = sub.add_parser("look", help="show workspace summary (default command)") - look_p.add_argument( - "-f", "--follow", action="store_true", help="append snapshots (scroll log)" - ) - look_p.add_argument("-i", "--interval", type=float, default=5.0) - look_p.add_argument( - "--no-delta", action="store_true", help="print every tick even if unchanged" - ) - - sub.add_parser("list", help="list agent names in the cluster") - - s = sub.add_parser("spawn", help="spawn an agent") - s.add_argument("name") - s.add_argument("--role", default="") - s.add_argument("--provider", choices=("anthropic", "openai", "demo")) - s.add_argument("--model") - - y = sub.add_parser("say", help="send a message to an agent") - y.add_argument("name") - y.add_argument("message", nargs=argparse.REMAINDER) - - sub.add_parser("sleep", help="snapshot and stop node (not implemented)") - - logs_p = sub.add_parser("logs", help="tail one agent's in-memory log") - logs_p.add_argument("name", help="agent short name (e.g. guide)") - logs_p.add_argument( - "-f", "--follow", action="store_true", help="stream until Ctrl+C" - ) - logs_p.add_argument( - "-i", "--interval", type=float, default=0.8, help="poll interval with --follow" - ) - logs_p.add_argument( - "--since", type=int, default=0, help="start after log sequence id" - ) - - dash = sub.add_parser( - "dashboard", - help="split-terminal UI (Zellij/tmux): one pane per agent log + player shell", - ) - dash.add_argument( - "--backend", - choices=("auto", "zellij", "tmux"), - default="auto", - help="auto prefers Zellij (Rust multiplexer)", - ) - dash.add_argument( - "-i", - "--interval", - type=float, - default=0.8, - help="agent log poll interval (seconds)", - ) - - wch = sub.add_parser("watch", help="show what each agent is doing in the cluster") - wch.add_argument("-f", "--follow", action="store_true", help="refresh until Ctrl+C") - wch.add_argument( - "--scroll", action="store_true", help="append updates (no full-screen clear)" - ) - wch.add_argument( - "--no-delta", action="store_true", help="print every tick even if unchanged" - ) - wch.add_argument( - "-i", - "--interval", - type=float, - default=2.0, - help="refresh seconds (with --follow)", - ) - wch.add_argument("--local", action="store_true", help="only agents on this node") - - demo_p = sub.add_parser( - "demo", - help="one-shot: 3 chattering demo agents + optional dashboard (no API key by default)", - ) - demo_p.add_argument("--addr", default="127.0.0.1:0") - demo_p.add_argument( - "--interval", type=float, default=6.0, help="seconds between chatter messages" - ) - demo_p.add_argument( - "--no-dashboard", action="store_true", help="do not spawn dashboard" - ) - demo_p.add_argument( - "--real-llm", - action="store_true", - help="use configured LLM provider instead of offline demo LLM", - ) - - task_p = sub.add_parser("task", help="task commands (alias for puzzle)") - task_sub = task_p.add_subparsers(dest="task_cmd") - plist = task_sub.add_parser("list", help="list tasks") - plist.add_argument( - "-f", "--follow", action="store_true", help="append snapshots (scroll log)" - ) - plist.add_argument("-i", "--interval", type=float, default=5.0) - plist.add_argument("--no-delta", action="store_true") - show = task_sub.add_parser("show", help="show one task") - show.add_argument("id") - mark = task_sub.add_parser("mark", help="update task status (not implemented)") - mark.add_argument("id") - mark.add_argument( - "--status", choices=("open", "in_progress", "solved", "failed"), required=True - ) - mark.add_argument("--assign-to", default=None, help="assign task to agent name") - - return p - - -def _parse(argv: Sequence[str], *, prog: str = DEFAULT_PROG) -> Namespace: - args = _build_parser(prog=prog).parse_args(list(argv)) - if args.cmd is None: - args.cmd = "look" - if args.cmd == "task" and args.task_cmd is None: - raise SystemExit(f"usage: {prog} task list|show|mark …") - return args - - -async def _dispatch(args: Namespace, *, prog: str = DEFAULT_PROG) -> None: - cmd = args.cmd - - if cmd == "init": - await world.run_init(args, prog=prog) - return - if cmd == "look": - await world.run_look(args, prog=prog) - return - if cmd == "watch": - await watch.run_watch(args, prog=prog) - return - if cmd == "dashboard": - dashboard.run_dashboard(args, prog=prog) - return - if cmd == "logs": - await agent_cmd.run_logs(args, prog=prog) - return - if cmd == "demo": - await demo.run_demo(args, prog=prog) - return - if cmd == "wake": - await world.run_wake(args, prog=prog) - return - if cmd == "sleep": - await world.run_sleep(args, prog=prog) - return - if cmd == "list": - await npc.run_who(args, prog=prog) - return - if cmd == "spawn": - await npc.run_summon(args, prog=prog) - return - if cmd == "say": - await npc.run_say(args, prog=prog) - return - if cmd == "task": - if args.task_cmd == "list": - await puzzle.run_list(args, prog=prog) - return - if args.task_cmd == "show": - await puzzle.run_show(args, prog=prog) - return - if args.task_cmd == "mark": - await puzzle.run_mark(args, prog=prog) - return - raise SystemExit(f"usage: {prog} task list|show|mark …") - - raise SystemExit(f"unknown command {cmd!r}") - - -async def async_main( - argv: Sequence[str] | None = None, *, prog: str = DEFAULT_PROG -) -> None: - tokens = list(argv) if argv is not None else [] - args = _parse(tokens, prog=prog) - await _dispatch(args, prog=prog) - - -def main(argv: Sequence[str] | None = None, *, prog: str = DEFAULT_PROG) -> None: - if argv is None: - argv = sys.argv[1:] - try: - asyncio.run(async_main(argv, prog=prog)) - except KeyboardInterrupt: - print("\n(interrupted)", file=sys.stderr) - - -if __name__ == "__main__": - main() diff --git a/python/pulsing/cli/bench.py b/python/pulsing/cli/bench.py deleted file mode 100644 index 9801f5c0c..000000000 --- a/python/pulsing/cli/bench.py +++ /dev/null @@ -1,100 +0,0 @@ -"""Pulsing CLI - Benchmark commands""" - -import asyncio -import os - - -def run_benchmark( - model_name: str, - url: str = "http://localhost:8000", - api_key: str = "", - tokenizer_name: str | None = None, - hf_token: str | None = None, - max_vus: int = 128, - duration: str = "120s", - warmup: str = "30s", - benchmark_kind: str = "throughput", - num_rates: int = 10, - rates: list | None = None, - num_workers: int = 4, -): - """Run inference benchmarks - - Args: - model_name: The name of the model to benchmark (required) - url: Backend URL (default: "http://localhost:8000") - api_key: API key for authentication (default: "") - tokenizer_name: HuggingFace tokenizer name (default: same as model_name) - hf_token: HuggingFace token for private models (default: from HF_TOKEN env) - max_vus: Maximum number of virtual users (default: 128) - duration: Duration of each benchmark step (default: "120s") - warmup: Warmup duration (default: "30s") - benchmark_kind: Kind of benchmark - throughput, sweep, csweep, rate (default: "throughput") - num_rates: Number of rates to sweep (default: 10) - rates: List of rates for rate benchmark - num_workers: Number of worker actors (default: 4) - """ - try: - from pulsing._bench import benchmark_main - except ImportError: - print( - "Error: 'pulsing._bench' module not found.\n" - "The benchmark tools are optional and need to be installed separately.\n\n" - "To install them, please run:\n" - " maturin develop --manifest-path crates/pulsing-bench-py/Cargo.toml" - ) - return - - # Get HF token from environment if not provided - if hf_token is None: - hf_token = os.environ.get("HF_TOKEN") - - config = { - "model_name": model_name, - "url": url, - "api_key": api_key, - "max_vus": max_vus, - "duration": duration, - "warmup": warmup, - "benchmark_kind": benchmark_kind, - "num_rates": num_rates, - "num_workers": num_workers, - } - - if tokenizer_name is not None: - config["tokenizer_name"] = tokenizer_name - - if hf_token is not None: - config["hf_token"] = hf_token - - if rates is not None: - config["rates"] = rates - - # Run the async benchmark - async def _run(): - return await benchmark_main(config) - - # Try to use uvloop for better performance - try: - import uvloop - - uvloop.install() - except ImportError: - pass - - result = asyncio.run(_run()) - - # Result is a JSON string with the benchmark report - if result: - import json - - print("\n" + "=" * 80) - print("BENCHMARK REPORT (JSON)") - print("=" * 80) - try: - report = json.loads(result) - print(json.dumps(report, indent=2)) - except json.JSONDecodeError: - print(result) - - return result diff --git a/python/pulsing/cli/help_text.py b/python/pulsing/cli/help_text.py index d20fcfef0..7aa701c62 100644 --- a/python/pulsing/cli/help_text.py +++ b/python/pulsing/cli/help_text.py @@ -15,15 +15,8 @@ def print_top_level_help() -> None: Runtime: actor Start an Actor service (cluster member) inspect Observe cluster via HTTP (non-member) - bench LLM inference benchmark examples List or show built-in examples -Agent (workspace): - agent Workspace wake, spawn, task, watch, demo - -Forge (tools): - forge Session REPL and tool debugging (`pulsing forge repl`) - Run `pulsing --help` for command-specific help. """ ) diff --git a/python/pulsing/cli/workspace_cmd.py b/python/pulsing/cli/workspace_cmd.py index 639f7385e..3441adbba 100644 --- a/python/pulsing/cli/workspace_cmd.py +++ b/python/pulsing/cli/workspace_cmd.py @@ -14,29 +14,16 @@ def _add_init(sub: argparse._SubParsersAction) -> None: p = sub.add_parser("init", help="Bootstrap a Pulsing workspace") p.add_argument("dir", nargs="?", type=Path, default=None, help="target directory") - p.add_argument( - "guide_words", - nargs="*", - help="natural-language goal for LLM-guided bootstrap", - ) - p.add_argument( - "-g", - "--guide", - default=None, - help="same as trailing guide words", - ) p.add_argument( "--template", - choices=("minimal", "agent"), - default="agent", - help="workspace template (default: agent)", + choices=("minimal",), + default="minimal", + help="workspace template (default: minimal)", ) p.add_argument("--name", default=None, help="display name in cluster.json") p.add_argument( "--force", action="store_true", help="re-initialize existing workspace" ) - p.add_argument("--provider", choices=("demo", "anthropic", "openai"), default=None) - p.add_argument("--model", default=None) p.set_defaults(func=cmd_init) @@ -66,31 +53,15 @@ def register_workspace_commands(sub: argparse._SubParsersAction) -> None: _add_rollback(sub) -def _merge_guide(flag: str | None, words: list[str]) -> str | None: - if flag and flag.strip(): - return flag.strip() - if not words: - return None - return " ".join(words) - - def cmd_init(args: argparse.Namespace) -> None: - guide = _merge_guide( - getattr(args, "guide", None), getattr(args, "guide_words", []) or [] - ) result = init_workspace( args.dir, template=args.template, name=args.name, force=args.force, - guide=guide, - provider=getattr(args, "provider", None), - model=getattr(args, "model", None), ) if result.created: print(f"initialized {result.root} (cluster_id={result.cluster_id})") - if args.template == "agent": - print(" pulsing agent wake # start agents") print(" pulsing history # list checkpoints") print(" pulsing checkpoint # save workspace snapshot") else: diff --git a/python/pulsing/forge/README.md b/python/pulsing/forge/README.md deleted file mode 100644 index 939f73429..000000000 --- a/python/pulsing/forge/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# Pulsing Forge - -**Agent 工具与环境运行时** — 在可配置沙箱中执行 shell、文件、Session 工具、MCP 与插件。 - -```python -from pulsing.forge import ForgeEnvironment, LocalToolSession - -env = ForgeEnvironment(cwd=".", session=LocalToolSession()) -rt = env.runtime() -rt.call_tool("Read", {"file_path": "README.md"}) -``` - ---- - -## 文档 - -| 文档 | 说明 | -|------|------| -| **[Pulsing 文档 · Forge 章节](https://github.com/DeepLink-org/pulsing/tree/main/docs/src/forge)** | 用户指南(概述、快速开始、部署、集成) | -| **本地预览** | `cd docs && uv run mkdocs serve` → 导航 **Pulsing Forge** | -| **设计与实现** | [`docs/src/design/forge/`](https://github.com/DeepLink-org/pulsing/tree/main/docs/src/design/forge) | - ---- - -## 安装 - -```bash -pip install pulsing -uv run maturin develop # Rust Hybrid 路径(仓库开发) -``` - ---- - -## 核心 API - -| 类型 | 作用 | -|------|------| -| `ForgeEnvironment` | 推荐入口:工作区 + 沙箱 + `ToolSession` | -| `ForgeBackend` | Pulsing 部署统一入口(LOCAL / DEDICATED / SHARED) | -| `ToolWorkerActor` | 隔离 worker(`@remote` + `new_process`) | -| `ToolSession` | Host 实现 plan / 用户输入 / token | -| `ToolResult` | `{content, is_error}` | - ---- - -## 工具(32) - -| 域 | 示例 | -|----|------| -| 隔离(11) | `Read`, `shell_command`, `apply_patch`, … | -| Host(21) | Session×5, MCP×3, `exec`/`wait`, Extension×8 | - -详见文档 [工具清单](https://github.com/DeepLink-org/pulsing/blob/main/docs/src/forge/tools.zh.md)。 - ---- - -## Pulsing Actor 示例 - -```python -import pulsing as pul -from pulsing.forge import ToolWorkerActor, ToolWorkerConfig - -await pul.init() -worker = await ToolWorkerActor.spawn(ToolWorkerConfig(cwd="."), public=False) -await worker.shell_command(cmd="pytest -q", workdir=".") -await pul.shutdown() -``` - -共享 worker gossip 名:`craft/ws/{workspace_id}/_tools` - ---- - -## 生态 - -```text -Pulsing → Actor 运行时 -Forge → 工具与环境(本包 pulsing.forge) -Craft → Multi-Agent 参考应用 -``` - ---- - -## 测试 - -```bash -pytest tests/python/test_pulsing_forge.py tests/python/test_hybrid_forge_callable.py -q -cargo test -p pulsing-forge -``` - ---- - -## 许可 - -Apache-2.0 · `crates/pulsing-forge/NOTICE` diff --git a/python/pulsing/forge/__init__.py b/python/pulsing/forge/__init__.py deleted file mode 100644 index 85744c003..000000000 --- a/python/pulsing/forge/__init__.py +++ /dev/null @@ -1,105 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Pulsing Forge — agent tool & environment runtime (``pulsing.forge``). - -Provides a sandboxed execution environment for AI agents: shell, filesystem, -and session collaboration tools. See ``docs/src/forge/`` (MkDocs **Pulsing Forge** chapter). -""" - -from __future__ import annotations - -from pulsing.forge.backend import ( - ForgeBackend, - ForgeBackendMode, - ForgeHostConfig, - ForgeIsolatedWorker, - create_host_runtime, - resolve_shared_tool_worker, - spawn_shared_tool_worker, -) -from pulsing.forge.config import ToolWorkerConfig -from pulsing.forge.context import ToolCallContext -from pulsing.forge.client import ForgeClient, RUST_FORGE_CLIENT_AVAILABLE -from pulsing.forge.environment import ForgeEnvironment -from pulsing.forge.events import ForgeEvent, ForgeEventKind -from pulsing.forge.host import CliEventSink, ForgeAgent, LegacyPythonForgeAgent -from pulsing.forge.hybrid_runtime import HybridForgeRuntime -from pulsing.forge.integrated import ( - FORGE_HOST_TOOL_NAMES, - FORGE_ISOLATED_TOOL_NAMES, - FORGE_TOOL_NAMES, - ForgeHostLink, -) -from pulsing.forge.naming import shared_tool_worker_name -from pulsing.forge.p2p_session import P2PToolSession -from pulsing.forge.p2p_transport import ForgeEventPump, tell_forge_event -from pulsing.forge.result import ToolResult -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.session import ( - LocalToolSession, - NullToolSession, - PlanItem, - StepStatus, - ToolSession, - UpdatePlanArgs, -) -from pulsing.forge.tool_calls import ( - OpenAIToolCallAccumulator, - ParsedToolCall, - anthropic_tool_result_block, - anthropic_tool_results_message, - extract_tool_calls, - forge_tool_definitions, - openai_tool_message, - parse_tool_arguments, - to_anthropic_tools, - to_openai_tools, -) -from pulsing.forge.worker import ToolWorkerActor - -__all__ = [ - "CliEventSink", - "ForgeAgent", - "ForgeClient", - "ForgeBackend", - "ForgeBackendMode", - "ForgeEnvironment", - "ForgeEvent", - "ForgeEventKind", - "ForgeEventPump", - "ForgeHostConfig", - "ForgeHostLink", - "ForgeIsolatedWorker", - "FORGE_HOST_TOOL_NAMES", - "FORGE_ISOLATED_TOOL_NAMES", - "FORGE_TOOL_NAMES", - "HybridForgeRuntime", - "LegacyPythonForgeAgent", - "LocalToolRuntime", - "LocalToolSession", - "NullToolSession", - "OpenAIToolCallAccumulator", - "P2PToolSession", - "RUST_FORGE_CLIENT_AVAILABLE", - "ParsedToolCall", - "PlanItem", - "StepStatus", - "ToolCallContext", - "ToolResult", - "ToolSession", - "ToolWorkerActor", - "ToolWorkerConfig", - "UpdatePlanArgs", - "anthropic_tool_result_block", - "anthropic_tool_results_message", - "create_host_runtime", - "extract_tool_calls", - "forge_tool_definitions", - "openai_tool_message", - "parse_tool_arguments", - "resolve_shared_tool_worker", - "shared_tool_worker_name", - "spawn_shared_tool_worker", - "tell_forge_event", - "to_anthropic_tools", - "to_openai_tools", -] diff --git a/python/pulsing/forge/approval_bridge.py b/python/pulsing/forge/approval_bridge.py deleted file mode 100644 index a93d56e72..000000000 --- a/python/pulsing/forge/approval_bridge.py +++ /dev/null @@ -1,42 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge approval helpers for worker ↔ host RPC.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.forge.events import ForgeEvent -from pulsing.forge.permissions import is_permission_profile_effectively_empty -from pulsing.forge.p2p_transport import ( - ask_exec_approval_sync, - ask_request_permissions_sync, - tell_forge_event_sync, -) - - -def _parse_exec_decision(raw: dict[str, Any]) -> str: - return str(raw.get("decision") or "denied") - - -def make_worker_exec_approval_callback(sink_name: str | None): - def _cb(request: dict[str, Any]) -> str: - if sink_name: - tell_forge_event_sync(sink_name, ForgeEvent.exec_approval_request(request)) - return _parse_exec_decision(ask_exec_approval_sync(sink_name, request)) - return "denied" - - return _cb - - -def make_worker_permissions_callback(sink_name: str | None): - def _cb(args: dict[str, Any]) -> dict[str, Any]: - if not sink_name: - raise RuntimeError("request_permissions requires approval sink") - tell_forge_event_sync(sink_name, ForgeEvent.request_permissions(args)) - out = ask_request_permissions_sync(sink_name, args) - perms = out.get("permissions") or {} - if is_permission_profile_effectively_empty(perms): - raise RuntimeError("permissions denied by host") - return out - - return _cb diff --git a/python/pulsing/forge/backend.py b/python/pulsing/forge/backend.py deleted file mode 100644 index 1db4ad5c2..000000000 --- a/python/pulsing/forge/backend.py +++ /dev/null @@ -1,382 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge deployment backends on Pulsing Actor (local host + isolated/remote worker).""" - -from __future__ import annotations - -import asyncio -import logging -from dataclasses import dataclass -from enum import Enum -from typing import Any, Callable - -from pulsing.core.isolated_bridge import IsolatedSpawnHandle -from pulsing.core.proxy import ActorProxy -from pulsing.core.remote import resolve - -from pulsing.forge.approval_bridge import ( - make_worker_exec_approval_callback, - make_worker_permissions_callback, -) -from pulsing.forge.config import ToolWorkerConfig -from pulsing.forge.events import ForgeEvent -from pulsing.forge.hybrid_runtime import HybridForgeRuntime -from pulsing.forge.integrated import FORGE_HOST_TOOL_NAMES, FORGE_ISOLATED_TOOL_NAMES -from pulsing.forge.mcp.naming import is_mcp_dynamic_tool -from pulsing.forge.naming import shared_tool_worker_name -from pulsing.forge.p2p_transport import ForgeEventPump, tell_forge_event_sync -from pulsing.forge.result import ToolResult -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.session import LocalToolSession, ToolSession -from pulsing.forge.worker import ToolWorkerActor -from pulsing.forge.worker_supervisor import ForgeWorkerSupervisor - -logger = logging.getLogger(__name__) - - -class ForgeBackendMode(str, Enum): - """How isolated Forge tools are executed.""" - - LOCAL = "local" # in-process only (no worker) - DEDICATED = "dedicated" # private ToolWorkerActor per host (new_process spawn) - SHARED = "shared" # resolve gossip-named workspace worker - - -@dataclass -class ForgeHostConfig: - cwd: str = "." - sandbox_policy: str = "off" - dangerously_disable_sandbox: bool = False - auto_approve: bool = False - session: ToolSession | None = None - - -ForgeHostRuntime = HybridForgeRuntime | LocalToolRuntime - - -def create_host_runtime( - cfg: ForgeHostConfig, - *, - event_callback: Callable[[dict[str, Any]], None] | None = None, - user_input_callback: Callable[[dict[str, Any]], dict[str, Any]] | None = None, - exec_approval_callback: Callable[[dict[str, Any]], str] | None = None, - request_permissions_callback: ( - Callable[[dict[str, Any]], dict[str, Any]] | None - ) = None, - tokens_remaining_callback: Callable[[], int | None] | None = None, - plugin_install_callback: Callable[[dict[str, Any]], bool | str] | None = None, -) -> ForgeHostRuntime: - """In-process Host runtime (Hybrid when ``pulsing._core`` is available).""" - if RUST_FORGE_AVAILABLE: - return HybridForgeRuntime.create( - cwd=cfg.cwd, - sandbox_policy=cfg.sandbox_policy, - dangerously_disable_sandbox=cfg.dangerously_disable_sandbox, - auto_approve=cfg.auto_approve, - session=cfg.session or LocalToolSession(), - event_callback=event_callback, - user_input_callback=user_input_callback, - exec_approval_callback=exec_approval_callback, - request_permissions_callback=request_permissions_callback, - tokens_remaining_callback=tokens_remaining_callback, - plugin_install_callback=plugin_install_callback, - ) - return LocalToolRuntime( - cwd=cfg.cwd, - sandbox_policy=cfg.sandbox_policy, - dangerously_disable_sandbox=cfg.dangerously_disable_sandbox, - session=cfg.session or LocalToolSession(), - ) - - -def _event_callback_for_sink( - sink: str | None, - pump: ForgeEventPump, - default_sink: str | None, -) -> Any: - if not sink: - return None - - def _cb(raw: dict[str, Any]) -> None: - event = ForgeEvent.from_dict(raw) - if sink == default_sink and pump.enabled: - pump.emit_sync(event) - else: - tell_forge_event_sync(sink, event) - - return _cb - - -class ForgeIsolatedWorker: - """``ToolWorkerActor`` lifecycle via Pulsing spawn / resolve.""" - - def __init__( - self, - worker_cfg: ToolWorkerConfig, - *, - mode: ForgeBackendMode = ForgeBackendMode.DEDICATED, - remote_name: str | None = None, - ) -> None: - if mode == ForgeBackendMode.SHARED and not remote_name: - raise ValueError("SHARED mode requires remote_name") - if mode == ForgeBackendMode.LOCAL: - raise ValueError("LOCAL mode does not use ForgeIsolatedWorker") - self._cfg = worker_cfg - self._mode = mode - self._remote_name = remote_name - self._pump = ForgeEventPump(worker_cfg.event_sink_name) - self._spawn: IsolatedSpawnHandle | None = None - self._proxy: ActorProxy | None = None - self._supervisor: ForgeWorkerSupervisor | None = None - self._lock = asyncio.Lock() - - @classmethod - def dedicated(cls, worker_cfg: ToolWorkerConfig) -> ForgeIsolatedWorker: - return cls(worker_cfg, mode=ForgeBackendMode.DEDICATED) - - @classmethod - def shared( - cls, worker_cfg: ToolWorkerConfig, *, workspace_id: str - ) -> ForgeIsolatedWorker: - return cls( - worker_cfg, - mode=ForgeBackendMode.SHARED, - remote_name=shared_tool_worker_name(workspace_id), - ) - - @property - def mode(self) -> ForgeBackendMode: - return self._mode - - @property - def proxy(self) -> ActorProxy | None: - return self._proxy - - def is_dead(self) -> bool: - if self._mode == ForgeBackendMode.SHARED: - return self._proxy is None - if self._supervisor is not None: - return self._supervisor.proxy is None - if self._spawn is None: - return True - return self._spawn.process.returncode is not None - - async def ensure_ready(self, *, reason: str = "startup") -> None: - async with self._lock: - if self._mode == ForgeBackendMode.SHARED: - if self._proxy is not None: - return - assert self._remote_name is not None - logger.info( - "resolving shared tool worker %s (%s)", self._remote_name, reason - ) - self._proxy = await resolve( - self._remote_name, - cls=ToolWorkerActor, - timeout=120.0, - ) - return - if not self.is_dead(): - return - await self._spawn_dedicated_locked(reason=reason) - - async def respawn(self, *, reason: str) -> None: - async with self._lock: - if self._mode == ForgeBackendMode.SHARED: - self._proxy = None - await self.ensure_ready(reason=reason) - return - await self._teardown_spawn_locked() - await self._spawn_dedicated_locked(reason=reason) - - async def close(self) -> None: - async with self._lock: - await self._pump.stop() - if self._supervisor is not None: - await self._supervisor.close() - self._supervisor = None - await self._teardown_spawn_locked() - - def terminate_process(self) -> None: - if self._mode == ForgeBackendMode.SHARED: - return - if self._supervisor is not None: - self._supervisor.terminate_process() - return - if self._spawn is None: - return - proc = self._spawn.process - if proc.returncode is None: - proc.terminate() - - async def call_tool( - self, - name: str, - arguments: dict[str, Any] | None = None, - *, - event_sink: str | None = None, - ) -> dict[str, Any]: - await self.ensure_ready(reason=f"tool {name!r}") - if self._supervisor is not None: - return await self._supervisor.call_tool( - name, arguments, event_sink=event_sink - ) - assert self._proxy is not None - kw = dict(arguments or {}) - sink = (event_sink or self._cfg.event_sink_name or "").strip() or None - kw["_event_sink"] = sink - caller = getattr(self._proxy, name, None) - if caller is not None: - return await caller(**kw) - return await self._proxy.as_any().call_tool(name, kw, event_sink=sink) - - async def _spawn_dedicated_locked(self, *, reason: str) -> None: - import pulsing as pul - - host = (self._cfg.host_name or "").strip() - if host: - logger.info("starting in-process worker supervisor (%s)", reason) - self._supervisor = ForgeWorkerSupervisor(self._cfg) - await self._supervisor.ensure_ready(reason=reason) - self._spawn = None - self._proxy = self._supervisor.proxy - return - await self._pump.start() - logger.info("spawning ToolWorkerActor (%s)", reason) - actor = ToolWorkerActor(self._cfg) - h = await pul.spawn( - actor, - new_process=True, - name="pulsing_forge_worker", - public=False, - restart_policy="never", - ) - if not isinstance(h, IsolatedSpawnHandle): - raise TypeError("expected IsolatedSpawnHandle from isolated spawn") - self._spawn = h - self._supervisor = None - self._proxy = ActorProxy( - h.ref, ToolWorkerActor._methods, ToolWorkerActor._async_methods - ) - - async def _teardown_spawn_locked(self) -> None: - if self._supervisor is not None: - await self._supervisor.close() - self._supervisor = None - self._proxy = None - return - if self._spawn is None: - self._proxy = None - return - proc = self._spawn.process - if proc.returncode is None: - proc.terminate() - try: - await asyncio.wait_for(proc.wait(), timeout=8.0) - except asyncio.TimeoutError: - proc.kill() - await proc.wait() - self._spawn = None - self._proxy = None - - -async def spawn_shared_tool_worker( - *, - workspace_id: str, - cwd: str, - sandbox_policy: str = "off", - dangerously_disable_sandbox: bool = False, -) -> Any: - """Spawn one public ``ToolWorkerActor`` for a workspace (gossip name).""" - import pulsing as pul - - name = shared_tool_worker_name(workspace_id) - h = await pul.spawn( - ToolWorkerActor( - ToolWorkerConfig( - cwd=cwd, - sandbox_policy=sandbox_policy, - dangerously_disable_sandbox=dangerously_disable_sandbox, - ), - ), - new_process=True, - name=name, - public=True, - restart_policy="never", - ) - logger.info("shared tool worker spawned at %s", name) - return h - - -async def resolve_shared_tool_worker( - workspace_id: str, - *, - timeout: float = 120.0, -) -> ActorProxy: - name = shared_tool_worker_name(workspace_id) - return await resolve(name, cls=ToolWorkerActor, timeout=timeout) - - -@dataclass -class ForgeBackend: - """Host runtime + optional isolated worker — unified Forge on Pulsing.""" - - host: ForgeHostRuntime - worker: ForgeIsolatedWorker | None = None - event_sink_name: str | None = None - - @property - def mode(self) -> ForgeBackendMode: - if self.worker is None: - return ForgeBackendMode.LOCAL - return self.worker.mode - - def refresh_mcp(self) -> None: - if hasattr(self.host, "refresh_mcp"): - self.host.refresh_mcp() - - async def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> ToolResult: - args = dict(arguments or {}) - if name in FORGE_ISOLATED_TOOL_NAMES: - if self.worker is None: - return ToolResult( - content="Forge isolated worker is not configured", is_error=True - ) - last_exc: BaseException | None = None - for attempt in range(2): - try: - raw = await self.worker.call_tool( - name, - args, - event_sink=self.event_sink_name, - ) - return ToolResult.from_dict(raw) - except BaseException as e: - last_exc = e - logger.warning( - "isolated tool %s failed (attempt %s): %s", name, attempt + 1, e - ) - if self.worker.mode == ForgeBackendMode.SHARED: - async with self.worker._lock: - self.worker._proxy = None - else: - await self.worker.respawn(reason=f"recover after {name!r}") - return ToolResult( - content=f"isolated tool failed after retry: {last_exc!r}", - is_error=True, - ) - if name in FORGE_HOST_TOOL_NAMES or is_mcp_dynamic_tool(name): - return await asyncio.to_thread(self.host.call_tool, name, args) - return ToolResult(content=f"Unknown Forge tool: {name}", is_error=True) - - async def ensure_worker(self, *, reason: str = "startup") -> None: - if self.worker is not None: - await self.worker.ensure_ready(reason=reason) - - async def close(self) -> None: - if hasattr(self.host, "close"): - self.host.close() - if self.worker is not None: - await self.worker.close() diff --git a/python/pulsing/forge/cli.py b/python/pulsing/forge/cli.py deleted file mode 100644 index 64f72b35c..000000000 --- a/python/pulsing/forge/cli.py +++ /dev/null @@ -1,35 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge CLI: ``pulsing forge``.""" - -from __future__ import annotations - -import sys -from collections.abc import Sequence - -from pulsing.forge.repl.cli import main as repl_main - - -def main_pulsing_forge(argv: Sequence[str] | None = None) -> None: - args = list(argv if argv is not None else sys.argv[1:]) - if not args or args[0] in ("-h", "--help", "help"): - print( - """usage: pulsing forge [options] - -Commands: - repl Interactive session REPL (Rust when available, else Python) - -Examples: - pulsing forge repl --cwd . - pulsing forge repl --trace trace.jsonl --replay-all --verify -""" - ) - return - if args[0] != "repl": - print(f"Unknown forge command: {args[0]!r}", file=sys.stderr) - print("Run `pulsing forge --help` for usage.", file=sys.stderr) - raise SystemExit(2) - repl_main(args[1:]) - - -def main() -> None: - main_pulsing_forge(sys.argv[1:]) diff --git a/python/pulsing/forge/client.py b/python/pulsing/forge/client.py deleted file mode 100644 index 21d240927..000000000 --- a/python/pulsing/forge/client.py +++ /dev/null @@ -1,73 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Python interface to the canonical Rust Forge session control plane.""" - -from __future__ import annotations - -from typing import Any - -try: - from pulsing._core import ForgeClient as _NativeForgeClient - - RUST_FORGE_CLIENT_AVAILABLE = True -except ImportError: - _NativeForgeClient = None # type: ignore[misc, assignment] - RUST_FORGE_CLIENT_AVAILABLE = False - - -class ForgeClient: - """Thin client; all Session, Turn, Agent loop, and event state lives in Rust.""" - - def __init__(self) -> None: - if not RUST_FORGE_CLIENT_AVAILABLE: - raise RuntimeError( - "Rust ForgeClient is required; rebuild the extension with " - "`maturin develop`" - ) - self._inner = _NativeForgeClient() - - def create_session( - self, - *, - cwd: str = ".", - provider: str = "demo", - model: str = "demo", - max_tokens: int = 8192, - max_turns: int = 20, - sandbox: str = "off", - auto_approve: bool = True, - tool_names: list[str] | tuple[str, ...] | None = None, - system_prompt: str | None = None, - ) -> str: - return str( - self._inner.create_session( - cwd, - provider, - model, - max_tokens, - max_turns, - sandbox, - list(tool_names) if tool_names is not None else None, - system_prompt, - auto_approve, - ) - ) - - def start_turn(self, session_id: str, input: str) -> dict[str, Any]: - return dict(self._inner.start_turn(session_id, input)) - - def wait_turn( - self, - session_id: str, - turn_id: str, - after_seq: int, - ) -> dict[str, Any]: - return dict(self._inner.wait_turn(session_id, turn_id, after_seq)) - - def cancel_turn(self, session_id: str, turn_id: str) -> dict[str, Any]: - return dict(self._inner.cancel_turn(session_id, turn_id)) - - def snapshot(self, session_id: str) -> dict[str, Any]: - return dict(self._inner.snapshot(session_id)) - - -__all__ = ["ForgeClient", "RUST_FORGE_CLIENT_AVAILABLE"] diff --git a/python/pulsing/forge/code_mode/__init__.py b/python/pulsing/forge/code_mode/__init__.py deleted file mode 100644 index 06e3dcf6c..000000000 --- a/python/pulsing/forge/code_mode/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex-aligned Code Mode — Python cells with nested Forge tool calls.""" - -from pulsing.forge.code_mode.handlers import ( - CODE_MODE_TOOL_NAMES, - handle_exec, - handle_wait, -) -from pulsing.forge.code_mode.protocol import ( - PUBLIC_TOOL_NAME, - WAIT_TOOL_NAME, - CellId, - ParsedExecSource, - RuntimeResponse, - WaitArgs, -) -from pulsing.forge.code_mode.service import CodeModeService - -__all__ = [ - "CODE_MODE_TOOL_NAMES", - "CellId", - "CodeModeService", - "ParsedExecSource", - "PUBLIC_TOOL_NAME", - "RuntimeResponse", - "WAIT_TOOL_NAME", - "WaitArgs", - "handle_exec", - "handle_wait", -] diff --git a/python/pulsing/forge/code_mode/cell.py b/python/pulsing/forge/code_mode/cell.py deleted file mode 100644 index 9d6616058..000000000 --- a/python/pulsing/forge/code_mode/cell.py +++ /dev/null @@ -1,259 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""In-process code cell state (Actor-ready; no pulsing actor dependency in Forge).""" - -from __future__ import annotations - -import builtins -import uuid -from dataclasses import dataclass, field -from enum import Enum -from typing import Any - -from pulsing.forge.code_mode.exceptions import CellExit, CellYield -from pulsing.forge.code_mode.protocol import ( - CellId, - ContentItem, - ParsedExecSource, - RuntimeResponse, -) -from pulsing.forge.code_mode.tools_bridge import ToolsBridge - -# Cells have no OS-level sandbox (see code_mode/handlers.py:_rejects_sandbox_policy), -# so this is defense-in-depth only: it blocks the obvious escapes (import os, -# open, eval/exec/compile, __import__) but is NOT a real security boundary — -# attribute-based tricks (e.g. `().__class__.__mro__`) are a language feature -# that no builtins allowlist can remove. Real isolation needs a process/OS -# boundary, tracked as a follow-up (see codex_parity.py notes for "exec"). -_ALLOWED_BUILTINS = frozenset( - { - "abs", - "all", - "any", - "bool", - "bytes", - "callable", - "chr", - "dict", - "divmod", - "enumerate", - "filter", - "float", - "format", - "frozenset", - "hash", - "hex", - "int", - "isinstance", - "issubclass", - "iter", - "len", - "list", - "map", - "max", - "min", - "next", - "oct", - "ord", - "pow", - "print", - "range", - "repr", - "reversed", - "round", - "set", - "slice", - "sorted", - "str", - "sum", - "tuple", - "type", - "zip", - "True", - "False", - "None", - "NotImplemented", - "BaseException", - "Exception", - "ValueError", - "TypeError", - "KeyError", - "IndexError", - "StopIteration", - "RuntimeError", - "ArithmeticError", - "ZeroDivisionError", - "AttributeError", - "NotImplementedError", - "OverflowError", - "LookupError", - "AssertionError", - "NameError", - "UnicodeDecodeError", - "UnicodeEncodeError", - "StopAsyncIteration", - "GeneratorExit", - } -) - - -def _restricted_builtins() -> dict[str, Any]: - return { - name: getattr(builtins, name) - for name in _ALLOWED_BUILTINS - if hasattr(builtins, name) - } - - -class CellStatus(str, Enum): - RUNNING = "running" - YIELDED = "yielded" - DONE = "done" - TERMINATED = "terminated" - ERROR = "error" - - -_TERMINAL_STATUSES = (CellStatus.DONE, CellStatus.ERROR, CellStatus.TERMINATED) - - -@dataclass -class CodeCell: - cell_id: CellId - parsed: ParsedExecSource - stored_values: dict[str, Any] = field(default_factory=dict) - content_items: list[ContentItem] = field(default_factory=list) - status: CellStatus = CellStatus.RUNNING - error_text: str | None = None - _terminate_requested: bool = field(default=False, repr=False) - _segment_index: int = field(default=0, repr=False) - _tools: ToolsBridge | None = field(default=None, repr=False) - - @classmethod - def new(cls, parsed: ParsedExecSource) -> CodeCell: - cid = CellId(f"cell-{uuid.uuid4().hex[:12]}") - return cls(cell_id=cid, parsed=parsed) - - def append_text(self, value: Any) -> None: - if value is None: - text = "null" - elif isinstance(value, str): - text = value - else: - import json - - try: - text = json.dumps(value, ensure_ascii=False) - except TypeError: - text = str(value) - self.content_items.append(ContentItem(text=text)) - - def build_namespace(self, tools: ToolsBridge) -> dict[str, Any]: - cell = self - - def text(value: Any) -> None: - cell.append_text(value) - - def store(key: str, value: Any) -> None: - cell.stored_values[str(key)] = value - - def load(key: str) -> Any: - return cell.stored_values.get(str(key)) - - def yield_control() -> None: - raise CellYield() - - def exit() -> None: - raise CellExit() - - def notify(value: Any) -> None: - cell.append_text(value) - - return { - "__builtins__": _restricted_builtins(), - "tools": tools, - "text": text, - "store": store, - "load": load, - "yield_control": yield_control, - "exit": exit, - "notify": notify, - "ALL_TOOLS": sorted(tools._allowed), - } - - def _segments(self) -> list[str]: - segs = self.parsed.segments - return segs if segs else [self.parsed.source] - - def run(self, tools: ToolsBridge) -> None: - if self.status in _TERMINAL_STATUSES: - return - if self.status == CellStatus.YIELDED: - self.status = CellStatus.RUNNING - self._tools = tools - namespace = self.build_namespace(tools) - segments = self._segments() - while self._segment_index < len(segments): - if self._terminate_requested: - break - try: - src = segments[self._segment_index] - exec(compile(src, "", "exec"), namespace, namespace) - except CellYield: - self._segment_index += 1 - self.status = CellStatus.YIELDED - return - except CellExit: - self.status = CellStatus.DONE - return - except Exception as exc: - self.status = CellStatus.ERROR - message = str(exc) - self.error_text = ( - f"{type(exc).__name__}: {message}" - if message - else type(exc).__name__ - ) - return - self._segment_index += 1 - if not self._terminate_requested and self.status == CellStatus.RUNNING: - self.status = CellStatus.DONE - - def mark_terminated(self) -> None: - """Request termination; no-op if the cell already reached a terminal state. - - Codex ``wait(..., terminate=true)`` on an already-finished cell must not - clobber its result/error with a bogus ``terminated`` status. - """ - if self.status in _TERMINAL_STATUSES: - return - self.status = CellStatus.TERMINATED - self._terminate_requested = True - - def to_response(self, *, max_tokens: int | None = None) -> RuntimeResponse: - items = self.content_items - if max_tokens is not None and max_tokens > 0: - budget = max_tokens - trimmed: list[ContentItem] = [] - for item in items: - if budget <= 0: - break - text = item.text[:budget] - trimmed.append(ContentItem(text=text)) - budget -= len(text) - items = trimmed - - if self.status == CellStatus.ERROR: - return RuntimeResponse( - kind="result", - cell_id=self.cell_id, - content_items=items, - error_text=self.error_text, - ) - if self.status == CellStatus.TERMINATED: - return RuntimeResponse( - kind="terminated", cell_id=self.cell_id, content_items=items - ) - if self.status == CellStatus.YIELDED: - return RuntimeResponse( - kind="yielded", cell_id=self.cell_id, content_items=items - ) - return RuntimeResponse(kind="result", cell_id=self.cell_id, content_items=items) diff --git a/python/pulsing/forge/code_mode/exceptions.py b/python/pulsing/forge/code_mode/exceptions.py deleted file mode 100644 index 058df4364..000000000 --- a/python/pulsing/forge/code_mode/exceptions.py +++ /dev/null @@ -1,10 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Control-flow exceptions for Python code cells.""" - - -class CellYield(Exception): - """Raised by ``yield_control()`` to pause the cell (Codex yield semantics).""" - - -class CellExit(Exception): - """Raised by ``exit()`` to finish the cell successfully.""" diff --git a/python/pulsing/forge/code_mode/handlers.py b/python/pulsing/forge/code_mode/handlers.py deleted file mode 100644 index e504c3eac..000000000 --- a/python/pulsing/forge/code_mode/handlers.py +++ /dev/null @@ -1,112 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge tool handlers for Codex-aligned ``exec`` / ``wait``.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.code_mode.protocol import PUBLIC_TOOL_NAME, WAIT_TOOL_NAME -from pulsing.forge.code_mode.tools_bridge import ToolsBridge -from pulsing.forge.result import ToolResult -from pulsing.forge.sandbox import normalize_policy - - -def _exec_source_from_args(source: str = "", **kwargs: Any) -> str: - raw = ( - source - or kwargs.get("input") - or kwargs.get("code") - or kwargs.get("source") - or "" - ) - return str(raw) - - -def _rejects_sandbox_policy( - ctx: ToolCallContext, - *, - sandbox_policy: str | None, - dangerously_disable_sandbox: bool, -) -> str | None: - """``exec`` runs the cell in-process with no OS-level isolation. - - Unlike ``shell_command``/``exec_command``, there is no subprocess or - namespace boundary to apply ``sandbox_policy`` to. Rather than silently - ignoring a caller's request for isolation (a sandbox-boundary bypass), - fail closed whenever isolation was explicitly requested. - """ - if dangerously_disable_sandbox or ctx.dangerously_disable_sandbox: - return None - # Fail closed if *either* the session or per-call args request isolation. - # Per-call sandbox_policy="off" must not downgrade a restricted session - # (dispatch_tool uses setdefault, so model-supplied args can bypass ctx). - policies = [normalize_policy(ctx.sandbox_policy)] - if sandbox_policy is not None: - policies.append(normalize_policy(sandbox_policy)) - for policy in policies: - if policy != "off": - return ( - f"exec runs Python in-process and cannot honor sandbox_policy={policy!r} " - "(no filesystem/network isolation is available); set sandbox_policy=off " - "on the session and omit per-call overrides, or pass " - "dangerously_disable_sandbox=true to proceed at your own risk" - ) - return None - - -def handle_exec( - *, - ctx: ToolCallContext, - source: str = "", - sandbox_policy: str | None = None, - dangerously_disable_sandbox: bool = False, - **kwargs: Any, -) -> ToolResult: - from pulsing.forge.handlers import dispatch_tool - - text = _exec_source_from_args(source, **kwargs) - if not text.strip(): - return ToolResult(content="exec source is empty", is_error=True) - - rejection = _rejects_sandbox_policy( - ctx, - sandbox_policy=sandbox_policy, - dangerously_disable_sandbox=dangerously_disable_sandbox, - ) - if rejection is not None: - return ToolResult(content=rejection, is_error=True) - - bridge = ToolsBridge(lambda name, args: dispatch_tool(name, args, ctx=ctx)) - try: - response = ctx.code_mode.execute(text, bridge) - except ValueError as exc: - return ToolResult(content=str(exc), is_error=True) - - return ToolResult( - content=response.model_message(), - structured=response.to_dict(), - ) - - -def handle_wait(*, ctx: ToolCallContext, **kwargs: Any) -> ToolResult: - from pulsing.forge.code_mode.protocol import WaitArgs - - try: - args = WaitArgs.from_dict(dict(kwargs)) - except (TypeError, ValueError) as exc: - return ToolResult(content=str(exc), is_error=True) - if not args.cell_id: - return ToolResult(content="cell_id is required", is_error=True) - - response = ctx.code_mode.wait(args) - if response.error_text and response.error_text.startswith("unknown cell_id:"): - return ToolResult(content=response.error_text, is_error=True) - - return ToolResult( - content=response.model_message(), - structured=response.to_dict(), - ) - - -CODE_MODE_TOOL_NAMES: frozenset[str] = frozenset({PUBLIC_TOOL_NAME, WAIT_TOOL_NAME}) diff --git a/python/pulsing/forge/code_mode/parse.py b/python/pulsing/forge/code_mode/parse.py deleted file mode 100644 index bad0d334e..000000000 --- a/python/pulsing/forge/code_mode/parse.py +++ /dev/null @@ -1,70 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Parse exec cell source + optional ``# @exec:`` pragma (Codex-compatible shape).""" - -from __future__ import annotations - -import json -import re -from typing import Any - -from pulsing.forge.code_mode.protocol import ( - DEFAULT_EXEC_YIELD_TIME_MS, - DEFAULT_MAX_OUTPUT_TOKENS, - ParsedExecSource, -) - -_CODE_MODE_PRAGMA_PREFIX = re.compile( - r"^[ \t]*// @exec:\s*(?P\{.*\})\s*(?:\r?\n)", re.MULTILINE -) -_PY_EXEC_PRAGMA_PREFIX = re.compile( - r"^[ \t]*#\s*@exec:\s*(?P\{.*\})\s*(?:\r?\n)", re.MULTILINE -) -_YIELD_CONTROL_LINE = re.compile(r"^\s*yield_control\s*\(\s*\)\s*(?:#.*)?$") - - -def split_yield_segments(source: str) -> list[str]: - """Split top-level source at standalone ``yield_control()`` lines (L2 resume).""" - lines = source.splitlines(keepends=True) - segments: list[str] = [] - buf: list[str] = [] - for line in lines: - buf.append(line) - if _YIELD_CONTROL_LINE.match(line.rstrip("\r\n")): - segments.append("".join(buf)) - buf = [] - if buf: - segments.append("".join(buf)) - return segments or [source] - - -def parse_exec_source(raw: str) -> ParsedExecSource: - text = raw if raw.endswith("\n") else raw + "\n" - meta: dict[str, Any] = {} - body = text - - for pattern in (_PY_EXEC_PRAGMA_PREFIX, _CODE_MODE_PRAGMA_PREFIX): - match = pattern.search(text) - if match: - try: - meta = json.loads(match.group("body")) - except json.JSONDecodeError as exc: - raise ValueError(f"invalid @exec pragma JSON: {exc}") from exc - body = text[match.end() :] - break - - yield_ms = int(meta.get("yield_time_ms") or DEFAULT_EXEC_YIELD_TIME_MS) - max_tokens = int(meta.get("max_output_tokens") or DEFAULT_MAX_OUTPUT_TOKENS) - if yield_ms < 0: - raise ValueError("yield_time_ms must be non-negative") - if max_tokens < 1: - raise ValueError("max_output_tokens must be positive") - - stripped = body.strip("\n") - if not stripped.strip(): - raise ValueError("exec source is empty") - return ParsedExecSource( - source=stripped, - segments=split_yield_segments(stripped), - yield_time_ms=yield_ms, - max_output_tokens=max_tokens, - ) diff --git a/python/pulsing/forge/code_mode/protocol.py b/python/pulsing/forge/code_mode/protocol.py deleted file mode 100644 index 8989d7f70..000000000 --- a/python/pulsing/forge/code_mode/protocol.py +++ /dev/null @@ -1,118 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex-aligned Code Mode wire types (Python cell, no V8).""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from enum import Enum -from typing import Any, Literal - -PUBLIC_TOOL_NAME = "exec" -WAIT_TOOL_NAME = "wait" - -DEFAULT_EXEC_YIELD_TIME_MS = 10_000 -DEFAULT_WAIT_YIELD_TIME_MS = 10_000 -DEFAULT_MAX_OUTPUT_TOKENS = 10_000 - - -@dataclass(frozen=True) -class CellId: - value: str - - def __str__(self) -> str: - return self.value - - -class ContentItemType(str, Enum): - TEXT = "text" - - -@dataclass -class ContentItem: - type: Literal["text"] = "text" - text: str = "" - - def to_dict(self) -> dict[str, Any]: - return {"type": self.type, "text": self.text} - - -@dataclass -class ParsedExecSource: - source: str - segments: list[str] = field(default_factory=list) - yield_time_ms: int = DEFAULT_EXEC_YIELD_TIME_MS - max_output_tokens: int = DEFAULT_MAX_OUTPUT_TOKENS - - -@dataclass -class RuntimeResponse: - kind: Literal["yielded", "terminated", "result"] - cell_id: CellId - content_items: list[ContentItem] = field(default_factory=list) - error_text: str | None = None - - def to_dict(self) -> dict[str, Any]: - out: dict[str, Any] = { - "kind": self.kind, - "cell_id": str(self.cell_id), - "content_items": [c.to_dict() for c in self.content_items], - } - if self.error_text is not None: - out["error_text"] = self.error_text - return out - - @classmethod - def from_dict(cls, raw: dict[str, Any]) -> RuntimeResponse: - items = [ - ContentItem(type="text", text=str(item.get("text") or "")) - for item in (raw.get("content_items") or []) - if isinstance(item, dict) - ] - return cls( - kind=raw.get("kind") or "result", - cell_id=CellId(str(raw.get("cell_id") or "unknown")), - content_items=items, - error_text=raw.get("error_text"), - ) - - def model_message(self) -> str: - """Human-readable summary aligned with Codex exec/wait responses.""" - if self.kind == "yielded": - prefix = f"Script running with cell ID {self.cell_id}" - elif self.kind == "terminated": - prefix = f"Script terminated (cell ID {self.cell_id})" - else: - prefix = f"Script completed (cell ID {self.cell_id})" - body = "".join(c.text for c in self.content_items) - if self.error_text: - return f"{prefix}\nError: {self.error_text}\n{body}".strip() - return f"{prefix}\n{body}".strip() if body else prefix - - -@dataclass -class WaitArgs: - cell_id: str - yield_time_ms: int = DEFAULT_WAIT_YIELD_TIME_MS - max_tokens: int | None = None - terminate: bool = False - - @classmethod - def from_dict(cls, raw: dict[str, Any]) -> WaitArgs: - raw_yield_ms = raw.get("yield_time_ms") - yield_time_ms = ( - DEFAULT_WAIT_YIELD_TIME_MS if raw_yield_ms is None else int(raw_yield_ms) - ) - if yield_time_ms < 0: - raise ValueError("yield_time_ms must be non-negative") - - raw_max_tokens = raw.get("max_tokens") - max_tokens = None if raw_max_tokens is None else int(raw_max_tokens) - if max_tokens is not None and max_tokens < 1: - raise ValueError("max_tokens must be positive") - - return cls( - cell_id=str(raw.get("cell_id") or ""), - yield_time_ms=yield_time_ms, - max_tokens=max_tokens, - terminate=bool(raw.get("terminate")), - ) diff --git a/python/pulsing/forge/code_mode/registry.py b/python/pulsing/forge/code_mode/registry.py deleted file mode 100644 index e466d8e22..000000000 --- a/python/pulsing/forge/code_mode/registry.py +++ /dev/null @@ -1,73 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Code Mode cell registry actor.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.core.proxy import ActorProxy -from pulsing.core.remote import remote, resolve - -from pulsing._async_bridge import run_sync -from pulsing.forge.code_mode.protocol import WaitArgs -from pulsing.forge.code_mode.service import CodeModeService -from pulsing.forge.code_mode.tools_bridge import ToolsBridge -from pulsing.forge.naming import code_cell_registry_name -from pulsing.forge.result import ToolResult - - -@remote -class CodeCellRegistryActor: - """Session-scoped code cells with nested tool calls routed to the host agent.""" - - def __init__(self, host_name: str) -> None: - self._host_name = (host_name or "").strip() - self._service = CodeModeService() - - async def execute( - self, source: str, *, host_name: str | None = None - ) -> dict[str, Any]: - host = (host_name or self._host_name).strip() - bridge = ToolsBridge(self._host_call_tool_sync(host)) - response = self._service.execute(source, bridge) - return response.to_dict() - - async def wait(self, args: dict[str, Any]) -> dict[str, Any]: - wait_args = WaitArgs.from_dict(dict(args)) - response = self._service.wait(wait_args) - return response.to_dict() - - def _host_call_tool_sync(self, host_name: str): - def _call(name: str, args: dict[str, Any]) -> ToolResult: - raw = run_sync( - self._host_call_tool_async(host_name, name, args), timeout=600.0 - ) - if isinstance(raw, ToolResult): - return raw - return ToolResult.from_dict(dict(raw)) - - return _call - - async def _host_call_tool_async( - self, - host_name: str, - name: str, - args: dict[str, Any], - ) -> dict[str, Any]: - proxy = await resolve(host_name, timeout=60.0) - out = await proxy.call_tool(name, dict(args)) - if isinstance(out, ToolResult): - return out.to_dict() - if hasattr(out, "content") and hasattr(out, "is_error"): - return {"content": str(out.content), "is_error": bool(out.is_error)} - if isinstance(out, dict): - return dict(out) - return ToolResult(content=str(out), is_error=False).to_dict() - - -async def ensure_code_cell_registry(host_name: str) -> ActorProxy: - name = code_cell_registry_name(host_name) - try: - return await resolve(name, cls=CodeCellRegistryActor, timeout=30.0) - except Exception: - return await CodeCellRegistryActor.spawn(host_name, name=name, public=False) diff --git a/python/pulsing/forge/code_mode/remote.py b/python/pulsing/forge/code_mode/remote.py deleted file mode 100644 index 06d38651d..000000000 --- a/python/pulsing/forge/code_mode/remote.py +++ /dev/null @@ -1,54 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Remote Code Mode client — exec/wait via CodeCellRegistryActor.""" - -from __future__ import annotations - -from typing import Any - -from pulsing._async_bridge import run_sync -from pulsing.forge.code_mode.protocol import RuntimeResponse, WaitArgs -from pulsing.forge.code_mode.service import CodeModeService -from pulsing.forge.code_mode.tools_bridge import ToolsBridge -from pulsing.forge.result import ToolResult - - -class RemoteCodeModeClient: - """Host-side facade that delegates cells to a registry actor.""" - - def __init__(self, registry_name: str, host_name: str) -> None: - self._registry_name = registry_name - self._host_name = host_name - - def execute(self, source: str, tools: ToolsBridge) -> RuntimeResponse: - del tools # registry builds its own bridge from host_name - raw = run_sync(self._ask_execute(source), timeout=120.0) - return RuntimeResponse.from_dict(dict(raw)) - - def wait(self, args: WaitArgs) -> RuntimeResponse: - payload: dict[str, Any] = { - "cell_id": args.cell_id, - "yield_time_ms": args.yield_time_ms, - "terminate": args.terminate, - } - if args.max_tokens is not None: - payload["max_tokens"] = args.max_tokens - raw = run_sync(self._ask_wait(payload), timeout=120.0) - return RuntimeResponse.from_dict(dict(raw)) - - async def _ask_execute(self, source: str) -> dict[str, Any]: - import pulsing as pul - - proxy = await pul.resolve(self._registry_name, timeout=30.0) - return await proxy.execute(source, host_name=self._host_name) - - async def _ask_wait(self, payload: dict[str, Any]) -> dict[str, Any]: - import pulsing as pul - - proxy = await pul.resolve(self._registry_name, timeout=30.0) - return await proxy.wait(payload) - - -class LocalCodeModeClient(CodeModeService): - """Alias for in-process registry (tests).""" - - pass diff --git a/python/pulsing/forge/code_mode/service.py b/python/pulsing/forge/code_mode/service.py deleted file mode 100644 index 945a7fc3c..000000000 --- a/python/pulsing/forge/code_mode/service.py +++ /dev/null @@ -1,47 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Session-scoped Code Mode cell registry and exec/wait orchestration.""" - -from __future__ import annotations - -from pulsing.forge.code_mode.cell import CellStatus, CodeCell -from pulsing.forge.code_mode.parse import parse_exec_source -from pulsing.forge.code_mode.protocol import CellId, RuntimeResponse, WaitArgs -from pulsing.forge.code_mode.tools_bridge import ToolsBridge - - -class CodeModeService: - """In-process code cells (Actor control plane can wrap this later).""" - - def __init__(self) -> None: - self._cells: dict[str, CodeCell] = {} - - def execute(self, source: str, tools: ToolsBridge) -> RuntimeResponse: - parsed = parse_exec_source(source) - cell = CodeCell.new(parsed) - cell.run(tools) - self._cells[str(cell.cell_id)] = cell - return cell.to_response() - - def wait(self, args: WaitArgs) -> RuntimeResponse: - """Resume a yielded cell or return its latest snapshot. - - ``yield_time_ms`` is accepted for wire compatibility with Codex; there - is no OS-level blocking wait in the Python cell runtime. - """ - cell = self._cells.get(args.cell_id) - if cell is None: - return RuntimeResponse( - kind="result", - cell_id=CellId(args.cell_id or "unknown"), - error_text=f"unknown cell_id: {args.cell_id}", - ) - - if args.terminate: - cell.mark_terminated() - elif cell.status == CellStatus.YIELDED and cell._tools is not None: - cell.run(cell._tools) - - return cell.to_response(max_tokens=args.max_tokens) - - def get(self, cell_id: str) -> CodeCell | None: - return self._cells.get(cell_id) diff --git a/python/pulsing/forge/code_mode/tools_bridge.py b/python/pulsing/forge/code_mode/tools_bridge.py deleted file mode 100644 index 4d406da43..000000000 --- a/python/pulsing/forge/code_mode/tools_bridge.py +++ /dev/null @@ -1,69 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Nested Forge tool calls from a Python code cell.""" - -from __future__ import annotations - -import json -from typing import Any, Callable - -from pulsing.forge.code_mode.protocol import PUBLIC_TOOL_NAME, WAIT_TOOL_NAME -from pulsing.forge.result import ToolResult - -# Tools a cell may not invoke (avoid recursion / host-only orchestration). -_CODE_MODE_BLOCKED = frozenset({PUBLIC_TOOL_NAME, WAIT_TOOL_NAME}) - - -def default_nested_tool_names() -> frozenset[str]: - from pulsing.forge.integrated import ( - FORGE_ISOLATED_TOOL_NAMES, - FORGE_HOST_TOOL_NAMES, - ) - - allowed = (FORGE_ISOLATED_TOOL_NAMES | FORGE_HOST_TOOL_NAMES) - _CODE_MODE_BLOCKED - return frozenset(allowed) - - -class ToolsBridge: - """``tools.call(name, args)`` surface exposed inside exec cells.""" - - def __init__( - self, - call_tool: Callable[[str, dict[str, Any]], ToolResult], - *, - allowed: frozenset[str] | None = None, - ) -> None: - self._call_tool = call_tool - self._allowed = allowed or default_nested_tool_names() - - def call(self, name: str, args: dict[str, Any] | str | None = None) -> Any: - tool = str(name).strip() - if tool not in self._allowed: - raise PermissionError(f"tool not available in code mode: {tool}") - payload: dict[str, Any] - if args is None: - payload = {} - elif isinstance(args, str): - payload = {"input": args} - elif isinstance(args, dict): - payload = dict(args) - else: - raise TypeError("tool args must be a dict, string, or omitted") - result = self._call_tool(tool, payload) - if result.is_error: - raise RuntimeError(result.content or f"{tool} failed") - if result.structured is not None: - return result.structured - text = result.content or "" - try: - return json.loads(text) - except json.JSONDecodeError: - return text - - def __getattr__(self, name: str) -> Any: - if name.startswith("_"): - raise AttributeError(name) - - def _invoke(args: dict[str, Any] | str | None = None) -> Any: - return self.call(name, args) - - return _invoke diff --git a/python/pulsing/forge/codex_parity.py b/python/pulsing/forge/codex_parity.py deleted file mode 100644 index 18bd8d0f2..000000000 --- a/python/pulsing/forge/codex_parity.py +++ /dev/null @@ -1,488 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Internal tool-surface conformance tracker (registry / callable / wire / behavior). - -Used by CI and ``tests/python/forge/test_gates.py``. Not linked from public product docs. -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from enum import Enum -from typing import Literal - -from pulsing.forge.integrated import ( - FORGE_HOST_TOOL_NAMES, - FORGE_ISOLATED_TOOL_NAMES, - FORGE_TOOL_NAMES, -) - -Gate = Literal["pass", "partial", "fail", "na", "equiv"] - -# Host tools with no Rust handler today (maturin default path → Unknown tool). -PYTHON_ONLY_HOST: frozenset[str] = frozenset( - { - "exec", - "wait", - "web.run", - "skills.list", - "skills.read", - "memories.list", - "memories.read", - "memories.search", - "memories.add_ad_hoc_note", - "web_search", - } -) - -RUST_BUILTIN: frozenset[str] = frozenset( - { - "shell_command", - "exec_command", - "write_stdin", - "apply_patch", - "view_image", - "update_plan", - "new_context", - "get_context_remaining", - "request_user_input", - "request_permissions", - "tool_search", - "list_available_plugins_to_install", - "request_plugin_install", - "list_mcp_resources", - "list_mcp_resource_templates", - "read_mcp_resource", - "Read", - "Glob", - "Grep", - "Edit", - "Write", - "Bash", - } -) - - -class Scope(str, Enum): - """Whether a Codex capability counts toward the CCRP claim.""" - - CCRP = "ccrp" # must parity for "Codex base" marketing - FORGE_EXTRA = "forge_extra" # Forge adds (Claude interop) - EQUIVALENT = "equivalent" # covered elsewhere (Craft), not same tool name - OUT_OF_SCOPE = "out_of_scope" # intentionally not Forge (TUI, hosted-only, etc.) - - -@dataclass(frozen=True) -class ParityEntry: - codex_id: str - forge_tool: str | None - scope: Scope - domain: str - wire: Gate = "partial" - behavior: Gate = "partial" - integration: Gate = "partial" - equivalent: str | None = None - notes: str = "" - - -# Codex Client Runtime Profile — standard coding-agent tool surface (spec_plan + ext/*). -# Update wire/behavior/integration when tests land; registry/callable are computed. -CCRP_MANIFEST: tuple[ParityEntry, ...] = ( - # Execution - ParityEntry( - "shell_command", - "shell_command", - Scope.CCRP, - "exec", - "partial", - "partial", - "partial", - ), - ParityEntry( - "exec_command", - "exec_command", - Scope.CCRP, - "exec", - "partial", - "partial", - "partial", - ), - ParityEntry( - "write_stdin", - "write_stdin", - Scope.CCRP, - "exec", - "partial", - "partial", - "partial", - ), - # Files / patch - ParityEntry( - "apply_patch", - "apply_patch", - Scope.CCRP, - "fs", - "partial", - "partial", - "fail", - notes="Freeform LLM exposure pending", - ), - ParityEntry( - "view_image", "view_image", Scope.CCRP, "fs", "partial", "partial", "partial" - ), - ParityEntry("Read", "Read", Scope.FORGE_EXTRA, "fs", "na", "na", "pass"), - ParityEntry("Glob", "Glob", Scope.FORGE_EXTRA, "fs", "na", "na", "pass"), - ParityEntry("Grep", "Grep", Scope.FORGE_EXTRA, "fs", "na", "na", "pass"), - ParityEntry("Edit", "Edit", Scope.FORGE_EXTRA, "fs", "na", "na", "pass"), - ParityEntry("Write", "Write", Scope.FORGE_EXTRA, "fs", "na", "na", "pass"), - ParityEntry("Bash", "Bash", Scope.FORGE_EXTRA, "exec", "na", "na", "pass"), - # Session - ParityEntry( - "update_plan", "update_plan", Scope.CCRP, "session", "pass", "pass", "partial" - ), - ParityEntry( - "request_user_input", - "request_user_input", - Scope.CCRP, - "session", - "pass", - "partial", - "partial", - notes="No Codex TUI; autoResolutionMs ok", - ), - ParityEntry( - "request_permissions", - "request_permissions", - Scope.CCRP, - "session", - "pass", - "partial", - "partial", - ), - ParityEntry( - "new_context", "new_context", Scope.CCRP, "session", "pass", "pass", "partial" - ), - ParityEntry( - "get_context_remaining", - "get_context_remaining", - Scope.CCRP, - "session", - "pass", - "partial", - "partial", - notes="Token estimate only", - ), - # Discovery / plugins - ParityEntry( - "tool_search", - "tool_search", - Scope.CCRP, - "discovery", - "partial", - "partial", - "partial", - ), - ParityEntry( - "list_available_plugins_to_install", - "list_available_plugins_to_install", - Scope.CCRP, - "discovery", - "pass", - "partial", - "partial", - ), - ParityEntry( - "request_plugin_install", - "request_plugin_install", - Scope.CCRP, - "discovery", - "pass", - "partial", - "partial", - ), - # MCP - ParityEntry( - "list_mcp_resources", - "list_mcp_resources", - Scope.CCRP, - "mcp", - "pass", - "partial", - "partial", - notes="Hybrid Rust path wired; Python-only LocalToolRuntime has no MCP", - ), - ParityEntry( - "list_mcp_resource_templates", - "list_mcp_resource_templates", - Scope.CCRP, - "mcp", - "pass", - "partial", - "partial", - ), - ParityEntry( - "read_mcp_resource", - "read_mcp_resource", - Scope.CCRP, - "mcp", - "pass", - "partial", - "partial", - ), - ParityEntry( - "mcp_dynamic_tools", - None, - Scope.CCRP, - "mcp", - "pass", - "partial", - "partial", - notes="Per-server function tools via Rust MCP runtime", - ), - # Code mode - ParityEntry( - "exec", - "exec", - Scope.CCRP, - "code_mode", - "partial", - "partial", - "fail", - notes="L2 yield resume; no OS sandbox", - ), - ParityEntry("wait", "wait", Scope.CCRP, "code_mode", "partial", "partial", "fail"), - # Extension - ParityEntry( - "web.run", "web.run", Scope.CCRP, "extension", "partial", "partial", "fail" - ), - ParityEntry( - "skills.list", - "skills.list", - Scope.CCRP, - "extension", - "partial", - "partial", - "fail", - ), - ParityEntry( - "skills.read", - "skills.read", - Scope.CCRP, - "extension", - "partial", - "partial", - "fail", - ), - ParityEntry( - "memories.list", - "memories.list", - Scope.CCRP, - "extension", - "pass", - "pass", - "partial", - ), - ParityEntry( - "memories.read", - "memories.read", - Scope.CCRP, - "extension", - "pass", - "pass", - "partial", - ), - ParityEntry( - "memories.search", - "memories.search", - Scope.CCRP, - "extension", - "pass", - "pass", - "partial", - ), - ParityEntry( - "memories.add_ad_hoc_note", - "memories.add_ad_hoc_note", - Scope.CCRP, - "extension", - "pass", - "pass", - "partial", - ), - ParityEntry( - "web_search", - "web_search", - Scope.CCRP, - "extension", - "partial", - "na", - "fail", - notes="Hosted; Craft model config", - ), - # Equivalents (not counted in CCRP score denominator as failures) - ParityEntry( - "spawn_agent", - None, - Scope.EQUIVALENT, - "multi_agent", - "na", - "na", - "partial", - equivalent="Craft Summon", - ), - ParityEntry( - "multi_agent_v2", - None, - Scope.EQUIVALENT, - "multi_agent", - "na", - "na", - "partial", - equivalent="Craft cluster tools", - ), - # Out of scope - ParityEntry( - "image_gen.imagegen", None, Scope.OUT_OF_SCOPE, "extension", "na", "na", "na" - ), - ParityEntry("goals", None, Scope.OUT_OF_SCOPE, "extension", "na", "na", "na"), - ParityEntry( - "spawn_agents_on_csv", None, Scope.OUT_OF_SCOPE, "agent_jobs", "na", "na", "na" - ), - ParityEntry( - "codex_cli_tui_login", None, Scope.OUT_OF_SCOPE, "product", "na", "na", "na" - ), -) - - -@dataclass -class GateScore: - name: str - passed: int - total: int - pct: float - blockers: list[str] = field(default_factory=list) - - -@dataclass -class ParityReport: - certification: str - gates: dict[str, GateScore] - ccrp_entries: list[ParityEntry] - summary: str - - -def _registry_status(entry: ParityEntry) -> Gate: - if entry.scope != Scope.CCRP: - return "na" - if entry.codex_id == "mcp_dynamic_tools": - # Runtime-registered mcp__* tools; not a static FORGE_TOOL_NAMES entry. - return "pass" - name = entry.forge_tool - if not name: - return "fail" - return "pass" if name in FORGE_TOOL_NAMES else "fail" - - -def _callable_status(entry: ParityEntry, *, rust_available: bool) -> Gate: - if entry.scope != Scope.CCRP: - return "na" - if entry.codex_id == "mcp_dynamic_tools": - return "pass" if rust_available else "partial" - name = entry.forge_tool - if not name or name not in FORGE_TOOL_NAMES: - return "fail" - if rust_available and name in PYTHON_ONLY_HOST: - return "pass" - if name in FORGE_ISOLATED_TOOL_NAMES or name in FORGE_HOST_TOOL_NAMES: - if ( - rust_available - and name not in RUST_BUILTIN - and name not in FORGE_ISOLATED_TOOL_NAMES - ): - return "fail" - return "pass" - return "fail" - - -def _score_gate( - entries: list[ParityEntry], gate: str, *, rust_available: bool = True -) -> GateScore: - ccrp = [e for e in entries if e.scope == Scope.CCRP] - blockers: list[str] = [] - passed = 0 - for e in ccrp: - if gate == "registry": - st = _registry_status(e) - elif gate == "callable": - st = _callable_status(e, rust_available=rust_available) - else: - st = getattr(e, gate, "partial") - if st == "pass": - passed += 1 - elif st in ("fail", "partial"): - blockers.append(f"{e.codex_id}: {st}") - total = len(ccrp) - pct = (100.0 * passed / total) if total else 100.0 - return GateScore(gate, passed, total, pct, blockers) - - -def parity_report(*, rust_available: bool = True) -> ParityReport: - """Compute CCRP gate scores. Used in CI and docs.""" - gates = { - "registry": _score_gate( - list(CCRP_MANIFEST), "registry", rust_available=rust_available - ), - "callable": _score_gate( - list(CCRP_MANIFEST), "callable", rust_available=rust_available - ), - "wire": _score_gate(list(CCRP_MANIFEST), "wire", rust_available=rust_available), - "behavior": _score_gate( - list(CCRP_MANIFEST), "behavior", rust_available=rust_available - ), - "integration": _score_gate( - list(CCRP_MANIFEST), "integration", rust_available=rust_available - ), - } - cert = _certification_level(gates) - ccrp = [e for e in CCRP_MANIFEST if e.scope == Scope.CCRP] - summary = ( - f"CCRP certification: {cert} | " - f"registry {gates['registry'].pct:.0f}% | " - f"callable {gates['callable'].pct:.0f}% | " - f"wire {gates['wire'].pct:.0f}% | " - f"behavior {gates['behavior'].pct:.0f}% | " - f"integration {gates['integration'].pct:.0f}%" - ) - return ParityReport(cert, gates, ccrp, summary) - - -def _certification_level(gates: dict[str, GateScore]) -> str: - if gates["integration"].pct >= 95: - return "Platinum" - if gates["behavior"].pct >= 90: - return "Gold" - if gates["wire"].pct >= 90: - return "Silver" - if gates["registry"].pct >= 100 and gates["callable"].pct >= 100: - return "Bronze+" - if gates["registry"].pct >= 100: - return "Bronze" - return "Incomplete" - - -def assert_registry_gate() -> None: - """CI: every CCRP tool must appear in FORGE_TOOL_NAMES.""" - report = parity_report() - g = report.gates["registry"] - assert g.pct == 100.0, f"Registry gate failed ({g.passed}/{g.total}): {g.blockers}" - - -def format_report_text(report: ParityReport | None = None) -> str: - report = report or parity_report() - lines = [report.summary, ""] - for name, g in report.gates.items(): - lines.append(f" {name}: {g.passed}/{g.total} ({g.pct:.0f}%)") - for b in g.blockers[:8]: - lines.append(f" - {b}") - if len(g.blockers) > 8: - lines.append(f" ... +{len(g.blockers) - 8} more") - return "\n".join(lines) diff --git a/python/pulsing/forge/config.py b/python/pulsing/forge/config.py deleted file mode 100644 index 50170cd12..000000000 --- a/python/pulsing/forge/config.py +++ /dev/null @@ -1,21 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tool worker configuration.""" - -from __future__ import annotations - -from dataclasses import dataclass - - -@dataclass -class ToolWorkerConfig: - cwd: str = "." - sandbox_policy: str = "off" - dangerously_disable_sandbox: bool = False - auto_approve: bool = False - # Gossip name of the ForgeEventInbox (or host) that receives Forge tell events. - event_sink_name: str | None = None - # Host agent gossip name for exec approval / permissions ask RPC. - host_name: str | None = None - - def approval_sink(self) -> str | None: - return (self.host_name or self.event_sink_name or "").strip() or None diff --git a/python/pulsing/forge/context.py b/python/pulsing/forge/context.py deleted file mode 100644 index 6f5bb147a..000000000 --- a/python/pulsing/forge/context.py +++ /dev/null @@ -1,69 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Per tool-call context (cwd, sandbox, session).""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from pulsing.forge.discovery.catalog import ToolCatalog -from pulsing.forge.session import LocalToolSession, NullToolSession, ToolSession - - -def _new_exec() -> Any: - from pulsing.forge.unified_exec import UnifiedExecManager - - return UnifiedExecManager() - - -def _new_catalog() -> ToolCatalog: - catalog = ToolCatalog() - catalog.load_codex_plugins() - return catalog - - -def _new_code_mode() -> Any: - from pulsing.forge.code_mode.service import CodeModeService - - return CodeModeService() - - -def _new_memories() -> Any: - from pulsing.forge.extension.memories.local_backend import LocalMemoriesStore - - return LocalMemoriesStore() - - -def resolve_within_cwd(cwd: Path, path: str) -> Path: - """Resolve `path` against `cwd`, rejecting targets outside the workspace.""" - joined = Path(path) if Path(path).is_absolute() else cwd / path - target = joined.resolve() - root = cwd.resolve() - if target == root or root in target.parents: - return target - raise ValueError( - f"refusing to write outside working directory: {target} (cwd: {root})" - ) - - -@dataclass -class ToolCallContext: - cwd: Path - sandbox_policy: str = "off" - dangerously_disable_sandbox: bool = False - session: ToolSession | None = None - exec: Any = field(default_factory=_new_exec) - tool_catalog: ToolCatalog = field(default_factory=_new_catalog) - code_mode: Any = field(default_factory=_new_code_mode) - memories: Any = field(default_factory=_new_memories) - - def __post_init__(self) -> None: - self.cwd = Path(self.cwd).resolve() - if self.session is None: - self.session = NullToolSession() - - @property - def session_nonnull(self) -> ToolSession: - assert self.session is not None - return self.session diff --git a/python/pulsing/forge/discovery/__init__.py b/python/pulsing/forge/discovery/__init__.py deleted file mode 100644 index 260d23742..000000000 --- a/python/pulsing/forge/discovery/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tool discovery — Codex-compatible plugin + deferred tool search.""" - -from pulsing.forge.discovery.activate import activate_discovered_tools -from pulsing.forge.discovery.catalog import ToolCatalog -from pulsing.forge.discovery.entries import TOOL_SEARCH_DEFAULT_LIMIT, DeferredToolEntry - -__all__ = [ - "DeferredToolEntry", - "ToolCatalog", - "TOOL_SEARCH_DEFAULT_LIMIT", - "activate_discovered_tools", -] diff --git a/python/pulsing/forge/discovery/activate.py b/python/pulsing/forge/discovery/activate.py deleted file mode 100644 index ac3149a05..000000000 --- a/python/pulsing/forge/discovery/activate.py +++ /dev/null @@ -1,20 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Activate deferred tools discovered via tool_search.""" - -from __future__ import annotations - -from pulsing.forge.discovery.deferred import ( - DeferredForgeTool, - activate_discovered_tools, - parse_tool_search_result, -) - -__all__ = [ - "DeferredForgeTool", - "DeferredDiscoveredTool", - "activate_discovered_tools", - "parse_tool_search_result", -] - -# Back-compat alias (Craft imports). -DeferredDiscoveredTool = DeferredForgeTool diff --git a/python/pulsing/forge/discovery/bm25.py b/python/pulsing/forge/discovery/bm25.py deleted file mode 100644 index 268ffb265..000000000 --- a/python/pulsing/forge/discovery/bm25.py +++ /dev/null @@ -1,51 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""BM25-lite scoring for tool_search.""" - -from __future__ import annotations - -import json -import math -import re - - -def tokenize(text: str) -> list[str]: - return [t for t in re.split(r"[^a-zA-Z0-9_]+", text.lower()) if t] - - -def bm25_scores(query: str, documents: list[str]) -> list[float]: - q_terms = tokenize(query) - if not q_terms or not documents: - return [0.0] * len(documents) - - doc_terms = [tokenize(d) for d in documents] - n = float(len(documents)) - avgdl = sum(len(t) for t in doc_terms) / max(n, 1.0) - - df: dict[str, int] = {} - for terms in doc_terms: - seen: set[str] = set() - for t in terms: - if t not in seen: - df[t] = df.get(t, 0) + 1 - seen.add(t) - - k1 = 1.5 - b = 0.75 - scores: list[float] = [] - for terms in doc_terms: - dl = float(len(terms)) - score = 0.0 - for qt in q_terms: - tf = float(terms.count(qt)) - if tf == 0: - continue - df_q = float(df.get(qt, 0)) - idf = ((n - df_q + 0.5) / (df_q + 0.5)) + 1.0 - idf = math.log(idf) - score += ( - idf - * (tf * (k1 + 1.0)) - / (tf + k1 * (1.0 - b + b * dl / max(avgdl, 1.0))) - ) - scores.append(score) - return scores diff --git a/python/pulsing/forge/discovery/catalog.py b/python/pulsing/forge/discovery/catalog.py deleted file mode 100644 index 12d1c4771..000000000 --- a/python/pulsing/forge/discovery/catalog.py +++ /dev/null @@ -1,145 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Deferred tool catalog + Codex plugin loading.""" - -from __future__ import annotations - -from dataclasses import dataclass, field - -from pulsing.forge.discovery.bm25 import bm25_scores -from pulsing.forge.discovery.discoverable import ( - DiscoverablePlugin, - DiscoverableTool, - DiscoverableToolAction, - DiscoverableToolType, - collect_discoverable_tools, - request_plugin_install_entry, -) -from pulsing.forge.discovery.entries import TOOL_SEARCH_DEFAULT_LIMIT, DeferredToolEntry -from pulsing.forge.discovery.install import ( - deferred_tools_for_installed_plugin, - execute_plugin_install, -) -from pulsing.forge.discovery.plugin_store import PluginStore, load_plugin_state - - -class ToolCatalogRefreshError(RuntimeError): - """refresh_from_codex() could not enumerate the plugin cache/marketplaces.""" - - -@dataclass -class ToolCatalog: - deferred: list[DeferredToolEntry] = field(default_factory=list) - discoverable: list[DiscoverablePlugin] = field(default_factory=list) - discoverable_tools: list[DiscoverableTool] = field(default_factory=list) - installed_plugin_ids: set[str] = field(default_factory=set) - - def register_deferred(self, entry: DeferredToolEntry) -> None: - self.deferred = [e for e in self.deferred if e.name != entry.name] - self.deferred.append(entry) - - def refresh_from_codex(self, extra_dirs: list[str] | None = None) -> None: - """Rescan marketplaces + the installed-plugin cache. - - Raises `ToolCatalogRefreshError` if the plugin cache itself can't be read - (permission/disk errors). A single plugin with a corrupt manifest is - skipped rather than failing the whole refresh. - """ - _ = extra_dirs - state = load_plugin_state() - configured = set(state.get("enabled_plugins") or []) - store = PluginStore() - - try: - installed_ids = store.list_installed_plugin_ids() - discoverable_tools = collect_discoverable_tools( - configured_plugin_ids=configured - ) - except OSError as e: - raise ToolCatalogRefreshError( - f"failed to refresh plugin catalog: {e}" - ) from e - - self.installed_plugin_ids = {pid.id for pid in installed_ids} - self.discoverable_tools = discoverable_tools - self.discoverable = [ - t for t in self.discoverable_tools if isinstance(t, DiscoverablePlugin) - ] - - seen: set[str] = set() - self.deferred = [] - for pid in installed_ids: - try: - entries = deferred_tools_for_installed_plugin(pid.id) - except (OSError, ValueError): - continue # corrupt/unreadable plugin manifest — skip, don't fail the refresh - for entry in entries: - if entry.name not in seen: - seen.add(entry.name) - self.register_deferred(entry) - - def load_codex_plugins(self, extra_dirs: list[str] | None = None) -> None: - self.refresh_from_codex(extra_dirs) - - def search( - self, query: str, limit: int = TOOL_SEARCH_DEFAULT_LIMIT - ) -> list[DeferredToolEntry]: - docs = [e.search_text for e in self.deferred] - scores = bm25_scores(query, docs) - ranked = sorted(enumerate(scores), key=lambda x: x[1], reverse=True) - out: list[DeferredToolEntry] = [] - for idx, score in ranked: - if score <= 0: - break - if len(out) >= limit: - break - out.append(self.deferred[idx]) - return out - - def list_installable_entries(self) -> list[dict]: - return [request_plugin_install_entry(t) for t in self.discoverable_tools] - - def list_installable(self) -> list[DiscoverablePlugin]: - return list(self.discoverable) - - def find_discoverable( - self, tool_type: DiscoverableToolType, tool_id: str - ) -> DiscoverableTool | None: - for tool in self.discoverable_tools: - if tool.tool_type == tool_type and tool.id == tool_id: - return tool - return None - - def find_plugin(self, plugin_id: str) -> DiscoverablePlugin | None: - for p in self.discoverable: - if p.id == plugin_id: - return p - return None - - def install_plugin( - self, - plugin_id: str, - *, - user_confirmed: bool, - suggest_reason: str = "Model requested plugin install", - ) -> list[DeferredToolEntry]: - if not user_confirmed: - return [] - outcome = execute_plugin_install( - tool_type=DiscoverableToolType.PLUGIN, - action_type=DiscoverableToolAction.INSTALL, - tool_id=plugin_id, - suggest_reason=suggest_reason, - user_confirmed=user_confirmed, - ) - if not outcome.user_confirmed or outcome.deferred_tools is None: - return [] - self.refresh_from_codex() - return list(outcome.deferred_tools) - - def install_plugin_legacy(self, plugin_id: str) -> list[DeferredToolEntry]: - from pulsing.forge.discovery.install import install_plugin_from_marketplace - - install_plugin_from_marketplace(plugin_id) - entries = deferred_tools_for_installed_plugin(plugin_id) - self.refresh_from_codex() - return entries diff --git a/python/pulsing/forge/discovery/codex_manifest.py b/python/pulsing/forge/discovery/codex_manifest.py deleted file mode 100644 index e4b751f3f..000000000 --- a/python/pulsing/forge/discovery/codex_manifest.py +++ /dev/null @@ -1,151 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Parse Codex `.codex-plugin/plugin.json` manifests.""" - -from __future__ import annotations - -import json -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from pulsing.forge.discovery.codex_paths import PLUGIN_MANIFEST_RELATIVE_PATHS -from pulsing.forge.discovery.entries import DeferredToolEntry - - -def find_plugin_manifest_path(plugin_root: Path) -> Path | None: - for rel in PLUGIN_MANIFEST_RELATIVE_PATHS: - candidate = plugin_root / rel - if candidate.is_file(): - return candidate - return None - - -@dataclass -class CodexPluginManifest: - name: str - version: str | None = None - description: str | None = None - keywords: list[str] = field(default_factory=list) - skills_path: str | None = None - mcp_servers_path: str | None = None - apps_path: str | None = None - hooks_path: str | None = None - display_name: str | None = None - mcp_server_names: list[str] = field(default_factory=list) - app_connector_ids: list[str] = field(default_factory=list) - manifest_path: Path | None = None - plugin_root: Path | None = None - - @property - def has_skills(self) -> bool: - return bool(self.skills_path) - - @classmethod - def from_dict( - cls, raw: dict[str, Any], *, manifest_path: Path, plugin_root: Path - ) -> CodexPluginManifest: - interface = ( - raw.get("interface") if isinstance(raw.get("interface"), dict) else {} - ) - display = interface.get("displayName") or interface.get("display_name") - desc = ( - raw.get("description") - or interface.get("shortDescription") - or interface.get("short_description") - ) - mcp_path = raw.get("mcpServers") or raw.get("mcp_servers") - apps_path = raw.get("apps") - skills = raw.get("skills") - hooks = raw.get("hooks") - mcp_names = _extract_mcp_server_names(plugin_root, mcp_path) - connector_ids = _extract_app_connector_ids(plugin_root, apps_path) - name = str(raw.get("name") or plugin_root.name) - version = raw.get("version") - return cls( - name=name, - version=str(version) if version is not None else None, - description=str(desc) if desc is not None else None, - keywords=[str(k) for k in (raw.get("keywords") or []) if str(k).strip()], - skills_path=str(skills) if skills else None, - mcp_servers_path=str(mcp_path) if mcp_path else None, - apps_path=str(apps_path) if apps_path else None, - hooks_path=str(hooks) if hooks else None, - display_name=str(display) if display else None, - mcp_server_names=mcp_names, - app_connector_ids=connector_ids, - manifest_path=manifest_path, - plugin_root=plugin_root, - ) - - def deferred_tools(self) -> list[DeferredToolEntry]: - """Deferred stubs for MCP servers declared by the plugin (tool_search index).""" - out: list[DeferredToolEntry] = [] - plugin_id = self.name - for server in self.mcp_server_names: - ns = f"mcp__{server}" - entry = DeferredToolEntry.from_function( - ns, - f"MCP server {server} from plugin {self.display_name or self.name}", - {"type": "object", "properties": {}}, - defer_loading=True, - namespace=ns, - plugin_id=plugin_id, - source="codex_mcp_server", - ) - out.append(entry) - return out - - -def load_codex_manifest(plugin_root: Path) -> CodexPluginManifest: - manifest_path = find_plugin_manifest_path(plugin_root) - if manifest_path is None: - raise ValueError(f"missing plugin manifest under {plugin_root}") - raw = json.loads(manifest_path.read_text(encoding="utf-8")) - if not isinstance(raw, dict): - raise ValueError(f"{manifest_path}: manifest must be a JSON object") - return CodexPluginManifest.from_dict( - raw, manifest_path=manifest_path, plugin_root=plugin_root - ) - - -def _resolve_relative(plugin_root: Path, ref: str | None) -> Path | None: - if not ref: - return None - path = (plugin_root / ref).resolve() - return path if path.exists() else None - - -def _extract_mcp_server_names(plugin_root: Path, mcp_ref: Any) -> list[str]: - path = _resolve_relative(plugin_root, str(mcp_ref) if mcp_ref else None) - if path is None or not path.is_file(): - return [] - try: - raw = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return [] - servers = raw.get("mcpServers") if isinstance(raw, dict) else raw - if isinstance(servers, dict): - return sorted(str(k) for k in servers if str(k).strip()) - return [] - - -def _extract_app_connector_ids(plugin_root: Path, apps_ref: Any) -> list[str]: - path = _resolve_relative(plugin_root, str(apps_ref) if apps_ref else None) - if path is None or not path.is_file(): - return [] - try: - raw = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return [] - if not isinstance(raw, dict): - return [] - connectors = raw.get("connectors") or raw.get("apps") or raw - if isinstance(connectors, list): - return [ - str(c.get("id", c)) - for c in connectors - if isinstance(c, dict) and c.get("id") - ] - if isinstance(connectors, dict): - return sorted(str(k) for k in connectors) - return [] diff --git a/python/pulsing/forge/discovery/codex_paths.py b/python/pulsing/forge/discovery/codex_paths.py deleted file mode 100644 index 350a60f77..000000000 --- a/python/pulsing/forge/discovery/codex_paths.py +++ /dev/null @@ -1,128 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex home + plugin directory layout (aligned with codex-rs/core-plugins).""" - -from __future__ import annotations - -import os -from pathlib import Path - -PLUGINS_CACHE_DIR = "plugins/cache" -PLUGINS_DATA_DIR = "plugins/data" -DEFAULT_PLUGIN_VERSION = "local" - -MARKETPLACE_MANIFEST_RELATIVE_PATHS = ( - ".agents/plugins/marketplace.json", - ".claude-plugin/marketplace.json", -) - -PLUGIN_MANIFEST_RELATIVE_PATHS = ( - ".codex-plugin/plugin.json", - ".claude-plugin/plugin.json", -) - -# Codex tool_suggest fallback allowlist (core-plugins/src/discoverable.rs). -TOOL_SUGGEST_PLUGIN_ALLOWLIST: frozenset[str] = frozenset( - { - "github@openai-curated", - "notion@openai-curated", - "slack@openai-curated", - "gmail@openai-curated", - "google-calendar@openai-curated", - "google-drive@openai-curated", - "openai-developers@openai-curated", - "canva@openai-curated", - "teams@openai-curated", - "sharepoint@openai-curated", - "outlook-email@openai-curated", - "outlook-calendar@openai-curated", - "linear@openai-curated", - "figma@openai-curated", - "github@openai-curated-remote", - "notion@openai-curated-remote", - "slack@openai-curated-remote", - "gmail@openai-curated-remote", - "google-calendar@openai-curated-remote", - "google-drive@openai-curated-remote", - "openai-developers@openai-curated-remote", - "canva@openai-curated-remote", - "teams@openai-curated-remote", - "sharepoint@openai-curated-remote", - "outlook-email@openai-curated-remote", - "outlook-calendar@openai-curated-remote", - "linear@openai-curated-remote", - "figma@openai-curated-remote", - "chrome@openai-bundled", - "computer-use@openai-bundled", - } -) - - -def codex_home() -> Path: - raw = os.environ.get("CODEX_HOME", "").strip() - if raw: - return Path(raw).expanduser().resolve() - return (Path.home() / ".codex").resolve() - - -def plugins_cache_root() -> Path: - return codex_home() / PLUGINS_CACHE_DIR - - -def plugins_data_root() -> Path: - return codex_home() / PLUGINS_DATA_DIR - - -def forge_plugin_state_path() -> Path: - return codex_home() / "forge" / "plugin_state.json" - - -def scan_codex_plugin_dirs_legacy(extra_dirs: list[str] | None = None) -> list[Path]: - """Legacy flat scan roots — prefer marketplace + cache via ToolCatalog.refresh_from_codex.""" - out: list[Path] = [plugins_cache_root(), codex_home() / "plugins"] - for part in os.environ.get("FORGE_PLUGIN_DIRS", "").split(":"): - if part.strip(): - out.append(Path(part)) - for d in extra_dirs or []: - out.append(Path(d)) - return out - - -def discover_marketplace_roots(extra_roots: list[Path] | None = None) -> list[Path]: - roots: list[Path] = [] - for base in (Path.home(), codex_home()): - agents = base / ".agents" / "plugins" - if agents.is_dir(): - roots.append(agents) - for rel in MARKETPLACE_MANIFEST_RELATIVE_PATHS: - candidate = base / rel - if candidate.is_file(): - roots.append(candidate.parent) - cwd = Path.cwd() - for rel in MARKETPLACE_MANIFEST_RELATIVE_PATHS: - candidate = cwd / rel - if candidate.is_file(): - roots.append(candidate.parent) - for part in os.environ.get("FORGE_PLUGIN_DIRS", "").split(":"): - if part.strip(): - roots.append(Path(part).expanduser()) - for root in extra_roots or []: - roots.append(root) - seen: set[Path] = set() - out: list[Path] = [] - for root in roots: - resolved = root.resolve() - if resolved not in seen: - seen.add(resolved) - out.append(resolved) - return out - - -def find_marketplace_manifest(root: Path) -> Path | None: - for rel in MARKETPLACE_MANIFEST_RELATIVE_PATHS: - candidate = root / rel - if candidate.is_file(): - return candidate - direct = root / "marketplace.json" - if direct.is_file(): - return direct - return None diff --git a/python/pulsing/forge/discovery/deferred.py b/python/pulsing/forge/discovery/deferred.py deleted file mode 100644 index 2ee4fecdf..000000000 --- a/python/pulsing/forge/discovery/deferred.py +++ /dev/null @@ -1,102 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tools registered at runtime after ``tool_search``.""" - -from __future__ import annotations - -import json -from typing import Any, Protocol - -from pulsing.forge.tool_schema import json_schema_object - - -class ForgeToolLike(Protocol): - @property - def name(self) -> str: ... - - @property - def description(self) -> str: ... - - @property - def input_schema(self) -> dict[str, Any]: ... - - def is_read_only(self) -> bool: ... - - def execute(self, **kwargs: Any): ... - - -class DeferredForgeTool: - """Schema-only tool activated after ``tool_search`` (execution via Forge host/worker).""" - - def __init__( - self, - name: str, - description: str, - parameters: dict[str, Any], - *, - read_only: bool = False, - ) -> None: - self._name = name - self._description = description - self._parameters = parameters - self._read_only = read_only - - @property - def name(self) -> str: - return self._name - - @property - def description(self) -> str: - return self._description - - @property - def input_schema(self) -> dict: - props = dict(self._parameters.get("properties") or {}) - required = list(self._parameters.get("required") or []) - return json_schema_object(props, required or None) - - def is_read_only(self) -> bool: - return self._read_only - - def execute(self, **kwargs: Any): - raise RuntimeError(f"{self._name} runs in Forge worker/host") - - -def parse_tool_search_result(content: str) -> list[dict[str, Any]]: - try: - payload = json.loads(content) - except json.JSONDecodeError: - return [] - tools = payload.get("tools") - if not isinstance(tools, list): - return [] - return [t for t in tools if isinstance(t, dict) and t.get("name")] - - -def activate_discovered_tools( - tools_by_name: dict[str, Any], - content: str, - *, - register: Any | None = None, -) -> list[str]: - """Register ``tool_search`` hits. ``register(tool)`` optional (e.g. LlmChat.register_tool).""" - specs = parse_tool_search_result(content) - if not specs: - return [] - - activated: list[str] = [] - for spec in specs: - name = str(spec.get("name", "")).strip() - if not name or name in tools_by_name: - continue - tool = DeferredForgeTool( - name=name, - description=str(spec.get("description", "")), - parameters=dict( - spec.get("parameters") or {"type": "object", "properties": {}} - ), - ) - tools_by_name[name] = tool - if register is not None: - register(tool) - activated.append(name) - return activated diff --git a/python/pulsing/forge/discovery/discoverable.py b/python/pulsing/forge/discovery/discoverable.py deleted file mode 100644 index 5200ac39b..000000000 --- a/python/pulsing/forge/discovery/discoverable.py +++ /dev/null @@ -1,197 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex-aligned discoverable tools (Connector + Plugin).""" - -from __future__ import annotations - -import os -from dataclasses import dataclass -from enum import Enum -from typing import Any - -from pulsing.forge.discovery.codex_manifest import load_codex_manifest -from pulsing.forge.discovery.codex_paths import TOOL_SUGGEST_PLUGIN_ALLOWLIST -from pulsing.forge.discovery.marketplace import InstallPolicy, list_marketplaces -from pulsing.forge.discovery.plugin_id import PluginId -from pulsing.forge.discovery.plugin_store import PluginStore - -DESCRIPTION_MAX_LEN = 240 - - -class DiscoverableToolType(str, Enum): - CONNECTOR = "connector" - PLUGIN = "plugin" - - -class DiscoverableToolAction(str, Enum): - INSTALL = "install" - ENABLE = "enable" - - -@dataclass -class DiscoverableConnector: - id: str - name: str - description: str | None = None - install_url: str | None = None - is_accessible: bool = False - - @property - def tool_type(self) -> DiscoverableToolType: - return DiscoverableToolType.CONNECTOR - - -@dataclass -class DiscoverablePlugin: - id: str - name: str - description: str | None - remote_plugin_id: str | None - has_skills: bool - mcp_server_names: list[str] - app_connector_ids: list[str] - installed: bool = False - marketplace_name: str | None = None - manifest_path: Any = None # Path | None — kept for legacy compat - - @property - def tool_type(self) -> DiscoverableToolType: - return DiscoverableToolType.PLUGIN - - def to_entry_json(self) -> dict[str, Any]: - return request_plugin_install_entry(self) - - -DiscoverableTool = DiscoverableConnector | DiscoverablePlugin - - -def request_plugin_install_entry(tool: DiscoverableTool) -> dict[str, Any]: - desc = tool.description - if desc and len(desc) > DESCRIPTION_MAX_LEN: - desc = desc[: DESCRIPTION_MAX_LEN - 1] + "…" - if isinstance(tool, DiscoverableConnector): - return { - "id": tool.id, - "name": tool.name, - "description": desc, - "tool_type": DiscoverableToolType.CONNECTOR.value, - "has_skills": False, - "mcp_server_names": [], - "app_connector_ids": [], - } - return { - "id": tool.id, - "name": tool.name, - "description": desc, - "tool_type": DiscoverableToolType.PLUGIN.value, - "has_skills": tool.has_skills, - "mcp_server_names": list(tool.mcp_server_names), - "app_connector_ids": list(tool.app_connector_ids), - } - - -def collect_discoverable_plugins( - *, - configured_plugin_ids: set[str] | None = None, - allowlist_only: bool = False, -) -> list[DiscoverablePlugin]: - store = PluginStore() - configured = configured_plugin_ids or set() - discover_all = os.environ.get("FORGE_PLUGIN_DISCOVER_ALL", "").lower() in ( - "1", - "true", - "yes", - ) - out: list[DiscoverablePlugin] = [] - - for marketplace in list_marketplaces(): - for entry in marketplace.plugins: - pid = entry.plugin_id - if store.is_installed(pid): - continue - if entry.installation == InstallPolicy.NOT_AVAILABLE: - continue - in_allowlist = pid.id in TOOL_SUGGEST_PLUGIN_ALLOWLIST - is_configured = pid.id in configured - if not discover_all and not in_allowlist and not is_configured: - continue - manifest = None - try: - if entry.source.local_path and entry.source.local_path.is_dir(): - manifest = load_codex_manifest(entry.source.local_path) - except (OSError, ValueError): - manifest = None - name = manifest.display_name or manifest.name if manifest else entry.name - description = manifest.description if manifest else None - out.append( - DiscoverablePlugin( - id=pid.id, - name=name, - description=description, - remote_plugin_id=_remote_plugin_id(pid), - has_skills=bool(manifest and manifest.has_skills), - mcp_server_names=( - list(manifest.mcp_server_names) if manifest else [] - ), - app_connector_ids=( - list(manifest.app_connector_ids) if manifest else [] - ), - installed=False, - marketplace_name=marketplace.name, - ) - ) - return out - - -def collect_discoverable_connectors() -> list[DiscoverableConnector]: - """Connector catalog requires ChatGPT Apps API — stub for Codex wire compatibility.""" - return [] - - -def collect_discoverable_tools( - *, - configured_plugin_ids: set[str] | None = None, -) -> list[DiscoverableTool]: - plugins = collect_discoverable_plugins(configured_plugin_ids=configured_plugin_ids) - connectors = collect_discoverable_connectors() - return [*connectors, *plugins] - - -def find_discoverable_tool( - tool_type: DiscoverableToolType, - tool_id: str, - *, - configured_plugin_ids: set[str] | None = None, -) -> DiscoverableTool | None: - for tool in collect_discoverable_tools(configured_plugin_ids=configured_plugin_ids): - if tool.tool_type == tool_type and tool.id == tool_id: - return tool - return None - - -def _remote_plugin_id(pid: PluginId) -> str | None: - if pid.marketplace_name.endswith("-remote"): - return f"plugins~Plugin_{pid.plugin_name}" - return None - - -def build_plugin_install_elicitation_meta( - tool: DiscoverablePlugin, - *, - suggest_reason: str, - action_type: DiscoverableToolAction = DiscoverableToolAction.INSTALL, -) -> dict[str, Any]: - """Codex `tool_suggestion` elicitation meta (tools/request_plugin_install.rs).""" - meta: dict[str, Any] = { - "codex_approval_kind": "tool_suggestion", - "persist": "always", - "tool_type": DiscoverableToolType.PLUGIN.value, - "suggest_type": action_type.value, - "suggest_reason": suggest_reason, - "tool_id": tool.id, - "tool_name": tool.name, - } - if tool.remote_plugin_id: - meta["remote_plugin_id"] = tool.remote_plugin_id - if tool.app_connector_ids: - meta["app_connector_ids"] = tool.app_connector_ids - return meta diff --git a/python/pulsing/forge/discovery/entries.py b/python/pulsing/forge/discovery/entries.py deleted file mode 100644 index b47ccdfe4..000000000 --- a/python/pulsing/forge/discovery/entries.py +++ /dev/null @@ -1,66 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Deferred tool entries for tool_search.""" - -from __future__ import annotations - -from dataclasses import dataclass -from typing import Any - -TOOL_SEARCH_DEFAULT_LIMIT = 8 -TOOL_SEARCH_MAX_LIMIT = 100 -TOOL_SEARCH_MAX_QUERY_CHARS = 2000 - - -def normalize_tool_search_limit(limit: Any) -> int: - """Positive limits only; non-positive or unparsable values use the default.""" - if limit is None: - return TOOL_SEARCH_DEFAULT_LIMIT - try: - n = int(limit) - except (TypeError, ValueError): - return TOOL_SEARCH_DEFAULT_LIMIT - if n <= 0: - return TOOL_SEARCH_DEFAULT_LIMIT - return min(n, TOOL_SEARCH_MAX_LIMIT) - - -@dataclass -class DeferredToolEntry: - name: str - description: str - parameters: dict[str, Any] - search_text: str - defer_loading: bool = True - namespace: str | None = None - plugin_id: str | None = None - source: str | None = None - - @classmethod - def from_function( - cls, - name: str, - description: str, - parameters: dict[str, Any] | None = None, - **kwargs: Any, - ) -> DeferredToolEntry: - params = parameters or {"type": "object", "properties": {}} - search_text = f"{name} {name.replace('_', ' ')} {description}" - return cls( - name=name, - description=description, - parameters=params, - search_text=search_text, - **kwargs, - ) - - def to_loadable_json(self) -> dict[str, Any]: - return { - "type": "function", - "name": self.name, - "description": self.description, - "parameters": self.parameters, - "defer_loading": self.defer_loading, - "namespace": self.namespace, - "plugin_id": self.plugin_id, - "source": self.source, - } diff --git a/python/pulsing/forge/discovery/install.py b/python/pulsing/forge/discovery/install.py deleted file mode 100644 index 6558cd166..000000000 --- a/python/pulsing/forge/discovery/install.py +++ /dev/null @@ -1,145 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex-aligned plugin install orchestration.""" - -from __future__ import annotations - -import shutil -from dataclasses import dataclass -from pathlib import Path - -from pulsing.forge.discovery.codex_manifest import load_codex_manifest -from pulsing.forge.discovery.discoverable import ( - DiscoverableToolAction, - DiscoverableToolType, - find_discoverable_tool, -) -from pulsing.forge.discovery.entries import DeferredToolEntry -from pulsing.forge.discovery.marketplace import ( - find_installable_plugin, - materialize_plugin_source, -) -from pulsing.forge.discovery.plugin_id import PluginId -from pulsing.forge.discovery.plugin_store import ( - PluginInstallResult, - PluginStore, - enable_plugin, -) - - -@dataclass -class CodexInstallOutcome: - completed: bool - user_confirmed: bool - tool_type: DiscoverableToolType - action_type: DiscoverableToolAction - tool_id: str - tool_name: str - suggest_reason: str - tools_registered: int = 0 - install_result: PluginInstallResult | None = None - deferred_tools: list[DeferredToolEntry] | None = None - - def to_result_json(self) -> dict: - return { - "completed": self.completed, - "user_confirmed": self.user_confirmed, - "tool_type": self.tool_type.value, - "action_type": self.action_type.value, - "tool_id": self.tool_id, - "tool_name": self.tool_name, - "suggest_reason": self.suggest_reason, - "tools_registered": self.tools_registered, - } - - -def install_plugin_from_marketplace(plugin_id: str) -> PluginInstallResult: - entry = find_installable_plugin(plugin_id) - pid = entry.plugin_id - source = materialize_plugin_source(entry) - store = PluginStore() - try: - result = store.install(source, pid) - finally: - if source.name.startswith("forge-plugin-src-"): - shutil.rmtree(source, ignore_errors=True) - enable_plugin(pid) - return result - - -def deferred_tools_for_installed_plugin(plugin_id: str) -> list[DeferredToolEntry]: - pid = PluginId.parse(plugin_id) - root = PluginStore().active_plugin_root(pid) - if root is None: - return [] - manifest = load_codex_manifest(root) - return manifest.deferred_tools() - - -def verify_plugin_install_completed(plugin_id: str) -> bool: - pid = PluginId.parse(plugin_id) - if pid.marketplace_name.endswith("-remote"): - return True - return PluginStore().is_installed(pid) - - -def execute_plugin_install( - *, - tool_type: DiscoverableToolType, - action_type: DiscoverableToolAction, - tool_id: str, - suggest_reason: str, - user_confirmed: bool, -) -> CodexInstallOutcome: - if action_type != DiscoverableToolAction.INSTALL: - raise ValueError( - 'plugin install requests currently support only action_type="install"' - ) - if not suggest_reason.strip(): - raise ValueError("request_plugin_install requires non-empty suggest_reason") - if not user_confirmed: - tool = find_discoverable_tool(tool_type, tool_id) - if tool is None: - raise ValueError(f"unknown plugin {tool_id!r}") - return CodexInstallOutcome( - completed=True, - user_confirmed=False, - tool_type=tool_type, - action_type=action_type, - tool_id=tool_id, - tool_name=tool.name, - suggest_reason=suggest_reason, - tools_registered=0, - ) - - tool = find_discoverable_tool(tool_type, tool_id) - if tool is None: - raise ValueError(f"unknown plugin {tool_id!r}") - tool_name = tool.name - - if tool_type == DiscoverableToolType.PLUGIN: - install_result = install_plugin_from_marketplace(tool_id) - deferred = deferred_tools_for_installed_plugin(tool_id) - completed = verify_plugin_install_completed(tool_id) - return CodexInstallOutcome( - completed=completed, - user_confirmed=True, - tool_type=tool_type, - action_type=action_type, - tool_id=tool_id, - tool_name=tool_name, - suggest_reason=suggest_reason, - tools_registered=len(deferred), - install_result=install_result, - deferred_tools=deferred, - ) - - # Connector install is browser/OAuth — Craft must open install_url separately. - return CodexInstallOutcome( - completed=False, - user_confirmed=True, - tool_type=tool_type, - action_type=action_type, - tool_id=tool_id, - tool_name=tool_name, - suggest_reason=suggest_reason, - ) diff --git a/python/pulsing/forge/discovery/marketplace.py b/python/pulsing/forge/discovery/marketplace.py deleted file mode 100644 index 30d48e377..000000000 --- a/python/pulsing/forge/discovery/marketplace.py +++ /dev/null @@ -1,185 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex marketplace.json discovery (aligned with codex-rs/core-plugins/marketplace.rs).""" - -from __future__ import annotations - -import json -import shutil -import subprocess -import tempfile -from dataclasses import dataclass, field -from enum import Enum -from pathlib import Path -from typing import Any - -from pulsing.forge.discovery.codex_manifest import load_codex_manifest -from pulsing.forge.discovery.codex_paths import ( - discover_marketplace_roots, - find_marketplace_manifest, -) -from pulsing.forge.discovery.plugin_id import PluginId - - -class InstallPolicy(str, Enum): - NOT_AVAILABLE = "NOT_AVAILABLE" - AVAILABLE = "AVAILABLE" - INSTALLED_BY_DEFAULT = "INSTALLED_BY_DEFAULT" - - -@dataclass -class MarketplacePluginSource: - kind: str - local_path: Path | None = None - git_url: str | None = None - git_path: str | None = None - git_ref: str | None = None - - -@dataclass -class MarketplacePluginEntry: - name: str - source: MarketplacePluginSource - installation: InstallPolicy = InstallPolicy.AVAILABLE - marketplace_name: str = "" - marketplace_root: Path | None = None - - @property - def plugin_id(self) -> PluginId: - return PluginId(plugin_name=self.name, marketplace_name=self.marketplace_name) - - -@dataclass -class Marketplace: - name: str - root: Path - manifest_path: Path - plugins: list[MarketplacePluginEntry] = field(default_factory=list) - - -def list_marketplaces(extra_roots: list[Path] | None = None) -> list[Marketplace]: - out: list[Marketplace] = [] - for root in discover_marketplace_roots(extra_roots): - manifest_path = find_marketplace_manifest(root) - if manifest_path is None: - continue - try: - out.append(load_marketplace(manifest_path)) - except (OSError, json.JSONDecodeError, ValueError): - continue - return out - - -def load_marketplace(manifest_path: Path) -> Marketplace: - raw = json.loads(manifest_path.read_text(encoding="utf-8")) - if not isinstance(raw, dict): - raise ValueError(f"{manifest_path}: marketplace must be a JSON object") - name = str(raw.get("name") or manifest_path.parent.name) - marketplace_root = ( - manifest_path.parent - if manifest_path.name == "marketplace.json" - else _marketplace_root_from_manifest(manifest_path) - ) - plugins: list[MarketplacePluginEntry] = [] - for item in raw.get("plugins") or []: - if not isinstance(item, dict): - continue - plugin_name = str(item.get("name", "")).strip() - if not plugin_name: - continue - policy_raw = (item.get("policy") or {}).get("installation", "AVAILABLE") - try: - installation = InstallPolicy(str(policy_raw)) - except ValueError: - installation = InstallPolicy.AVAILABLE - source = _parse_source(item.get("source") or {}, marketplace_root) - plugins.append( - MarketplacePluginEntry( - name=plugin_name, - source=source, - installation=installation, - marketplace_name=name, - marketplace_root=marketplace_root, - ) - ) - return Marketplace( - name=name, - root=marketplace_root, - manifest_path=manifest_path, - plugins=plugins, - ) - - -def find_installable_plugin(plugin_id: str) -> MarketplacePluginEntry: - pid = PluginId.parse(plugin_id) - for marketplace in list_marketplaces(): - if marketplace.name != pid.marketplace_name: - continue - for plugin in marketplace.plugins: - if plugin.name != pid.plugin_name: - continue - if plugin.installation == InstallPolicy.NOT_AVAILABLE: - raise ValueError( - f"plugin {plugin_id!r} is not available for install in marketplace {marketplace.name!r}" - ) - return plugin - raise ValueError(f"plugin {plugin_id!r} was not found in any marketplace") - - -def materialize_plugin_source(entry: MarketplacePluginEntry) -> Path: - source = entry.source - if source.kind == "local": - if source.local_path is None or not source.local_path.is_dir(): - raise ValueError(f"local plugin source missing for {entry.plugin_id.id}") - return source.local_path.resolve() - if source.kind == "git": - if not source.git_url: - raise ValueError(f"git plugin source missing url for {entry.plugin_id.id}") - tmp = Path(tempfile.mkdtemp(prefix="forge-plugin-src-")) - cmd = ["git", "clone", "--depth", "1"] - if source.git_ref: - cmd.extend(["--branch", source.git_ref]) - cmd.extend([source.git_url, str(tmp)]) - subprocess.run(cmd, check=True, capture_output=True, text=True) - if source.git_path: - sub = (tmp / source.git_path).resolve() - if not sub.is_dir(): - raise ValueError(f"git plugin subpath missing: {source.git_path}") - return sub - return tmp - raise ValueError(f"unsupported plugin source kind {source.kind!r}") - - -def _marketplace_root_from_manifest(manifest_path: Path) -> Path: - for rel in (".agents/plugins/marketplace.json", ".claude-plugin/marketplace.json"): - parts = Path(rel).parts - current = manifest_path - for part in reversed(parts): - if current.name != part: - break - current = current.parent - else: - return current - return manifest_path.parent - - -def _parse_source( - raw: dict[str, Any], marketplace_root: Path -) -> MarketplacePluginSource: - kind = str(raw.get("source", "local")).lower() - if kind == "git": - return MarketplacePluginSource( - kind="git", - git_url=str(raw.get("url", "")), - git_path=str(raw["path"]) if raw.get("path") else None, - git_ref=str(raw.get("ref") or raw.get("sha") or "") or None, - ) - rel = str(raw.get("path", ".")) - local = (marketplace_root / rel).resolve() - return MarketplacePluginSource(kind="local", local_path=local) - - -def copy_tree_atomic(src: Path, dst: Path) -> None: - if dst.exists(): - shutil.rmtree(dst) - dst.parent.mkdir(parents=True, exist_ok=True) - shutil.copytree(src, dst) diff --git a/python/pulsing/forge/discovery/plugin_id.py b/python/pulsing/forge/discovery/plugin_id.py deleted file mode 100644 index 827220fca..000000000 --- a/python/pulsing/forge/discovery/plugin_id.py +++ /dev/null @@ -1,28 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex plugin id: `{plugin_name}@{marketplace_name}`.""" - -from __future__ import annotations - -from dataclasses import dataclass - - -@dataclass(frozen=True) -class PluginId: - plugin_name: str - marketplace_name: str - - @property - def id(self) -> str: - return f"{self.plugin_name}@{self.marketplace_name}" - - @classmethod - def parse(cls, raw: str) -> PluginId: - text = (raw or "").strip() - if "@" not in text: - raise ValueError(f"invalid plugin id {raw!r}: expected name@marketplace") - name, marketplace = text.rsplit("@", 1) - name = name.strip() - marketplace = marketplace.strip() - if not name or not marketplace: - raise ValueError(f"invalid plugin id {raw!r}") - return cls(plugin_name=name, marketplace_name=marketplace) diff --git a/python/pulsing/forge/discovery/plugin_store.py b/python/pulsing/forge/discovery/plugin_store.py deleted file mode 100644 index c840b3ae4..000000000 --- a/python/pulsing/forge/discovery/plugin_store.py +++ /dev/null @@ -1,163 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex plugin cache store: ~/.codex/plugins/cache/{marketplace}/{name}/{version}/.""" - -from __future__ import annotations - -import json -import re -import shutil -from dataclasses import dataclass -from pathlib import Path - -from pulsing.forge.discovery.codex_manifest import ( - find_plugin_manifest_path, - load_codex_manifest, -) -from pulsing.forge.discovery.codex_paths import ( - DEFAULT_PLUGIN_VERSION, - plugins_cache_root, -) -from pulsing.forge.discovery.marketplace import copy_tree_atomic -from pulsing.forge.discovery.plugin_id import PluginId - - -@dataclass -class PluginInstallResult: - plugin_id: PluginId - plugin_version: str - installed_path: Path - - -class PluginStore: - def __init__(self, cache_root: Path | None = None) -> None: - self.cache_root = (cache_root or plugins_cache_root()).resolve() - - def plugin_base_root(self, plugin_id: PluginId) -> Path: - return self.cache_root / plugin_id.marketplace_name / plugin_id.plugin_name - - def plugin_version_root(self, plugin_id: PluginId, version: str) -> Path: - return self.plugin_base_root(plugin_id) / version - - def active_plugin_version(self, plugin_id: PluginId) -> str | None: - base = self.plugin_base_root(plugin_id) - if not base.is_dir(): - return None - versions = [ - p.name - for p in base.iterdir() - if p.is_dir() and _valid_version_segment(p.name) - ] - if not versions: - return None - if DEFAULT_PLUGIN_VERSION in versions: - return DEFAULT_PLUGIN_VERSION - return sorted(versions, key=_version_sort_key)[-1] - - def active_plugin_root(self, plugin_id: PluginId) -> Path | None: - version = self.active_plugin_version(plugin_id) - if version is None: - return None - return self.plugin_version_root(plugin_id, version) - - def is_installed(self, plugin_id: PluginId) -> bool: - root = self.active_plugin_root(plugin_id) - return root is not None and find_plugin_manifest_path(root) is not None - - def install(self, source_path: Path, plugin_id: PluginId) -> PluginInstallResult: - source_path = source_path.resolve() - if not source_path.is_dir(): - raise ValueError(f"plugin source is not a directory: {source_path}") - manifest = load_codex_manifest(source_path) - if manifest.name != plugin_id.plugin_name: - raise ValueError( - f"plugin.json name {manifest.name!r} does not match marketplace name {plugin_id.plugin_name!r}" - ) - version = manifest.version or DEFAULT_PLUGIN_VERSION - _validate_version_segment(version) - installed_path = self.plugin_version_root(plugin_id, version) - copy_tree_atomic(source_path, installed_path) - return PluginInstallResult( - plugin_id=plugin_id, - plugin_version=version, - installed_path=installed_path, - ) - - def uninstall(self, plugin_id: PluginId) -> None: - base = self.plugin_base_root(plugin_id) - if base.exists(): - shutil.rmtree(base) - - def list_installed_plugin_ids(self) -> list[PluginId]: - out: list[PluginId] = [] - if not self.cache_root.is_dir(): - return out - for marketplace_dir in self.cache_root.iterdir(): - if not marketplace_dir.is_dir(): - continue - for plugin_dir in marketplace_dir.iterdir(): - if not plugin_dir.is_dir(): - continue - pid = PluginId( - plugin_name=plugin_dir.name, marketplace_name=marketplace_dir.name - ) - if self.is_installed(pid): - out.append(pid) - return out - - -def _valid_version_segment(version: str) -> bool: - try: - _validate_version_segment(version) - return True - except ValueError: - return False - - -def _validate_version_segment(version: str) -> None: - if not version or version in {".", ".."}: - raise ValueError("invalid plugin version") - if not re.fullmatch(r"[A-Za-z0-9._+\-]+", version): - raise ValueError("invalid plugin version characters") - - -def _version_sort_key(version: str) -> tuple[tuple[int, int | str], ...]: - """Return a deterministic key whose components are always comparable. - - Plugin caches can contain both numeric versions and labels. Returning raw - ``int`` and ``str`` components makes Python 3 raise when two versions first - differ by component type (for example ``1.0.0`` and ``1.0.dev``). - """ - - return tuple( - (0, int(component)) if component.isdigit() else (1, component.casefold()) - for component in re.split(r"[.\-+]", version) - ) - - -def load_plugin_state() -> dict: - from pulsing.forge.discovery.codex_paths import forge_plugin_state_path - - path = forge_plugin_state_path() - if not path.is_file(): - return {"enabled_plugins": []} - try: - raw = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return {"enabled_plugins": []} - return raw if isinstance(raw, dict) else {"enabled_plugins": []} - - -def save_plugin_state(state: dict) -> None: - from pulsing.forge.discovery.codex_paths import forge_plugin_state_path - - path = forge_plugin_state_path() - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(state, indent=2), encoding="utf-8") - - -def enable_plugin(plugin_id: PluginId) -> None: - state = load_plugin_state() - enabled = set(state.get("enabled_plugins") or []) - enabled.add(plugin_id.id) - state["enabled_plugins"] = sorted(enabled) - save_plugin_state(state) diff --git a/python/pulsing/forge/discovery/plugins.py b/python/pulsing/forge/discovery/plugins.py deleted file mode 100644 index 9fba19c0f..000000000 --- a/python/pulsing/forge/discovery/plugins.py +++ /dev/null @@ -1,50 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex plugin compatibility layer (re-exports + legacy scan helpers).""" - -from __future__ import annotations - -from pathlib import Path - -from pulsing.forge.discovery.codex_manifest import ( - find_plugin_manifest_path, - load_codex_manifest, -) -from pulsing.forge.discovery.codex_paths import ( - plugins_cache_root, - scan_codex_plugin_dirs_legacy, -) -from pulsing.forge.discovery.discoverable import ( - DiscoverablePlugin, - DiscoverableToolType, -) -from pulsing.forge.discovery.plugin_id import PluginId -from pulsing.forge.discovery.plugin_store import PluginStore - - -def scan_codex_plugin_dirs(extra_dirs: list[str] | None = None) -> list[Path]: - return scan_codex_plugin_dirs_legacy(extra_dirs) - - -def load_installed_manifests() -> list[tuple[object, Path]]: - """Load manifests from Codex cache layout.""" - store = PluginStore() - out: list[tuple[object, Path]] = [] - for pid in store.list_installed_plugin_ids(): - root = store.active_plugin_root(pid) - if root is None: - continue - manifest_path = find_plugin_manifest_path(root) - if manifest_path is None: - continue - out.append((load_codex_manifest(root), manifest_path)) - return out - - -# Back-compat re-export -__all__ = [ - "DiscoverablePlugin", - "DiscoverableToolType", - "PluginId", - "load_installed_manifests", - "scan_codex_plugin_dirs", -] diff --git a/python/pulsing/forge/environment.py b/python/pulsing/forge/environment.py deleted file mode 100644 index 09aac4897..000000000 --- a/python/pulsing/forge/environment.py +++ /dev/null @@ -1,53 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Agent execution environment — the primary Forge abstraction.""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from pathlib import Path -from typing import Union - -from pulsing.forge.hybrid_runtime import HybridForgeRuntime -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.rust_runtime import rust_forge_available -from pulsing.forge.session import LocalToolSession, NullToolSession, ToolSession - -ForgeRuntime = Union[LocalToolRuntime, HybridForgeRuntime] - - -@dataclass -class ForgeEnvironment: - """Where an agent runs tools: workspace root, sandbox, and host session hooks.""" - - cwd: Path | str = "." - sandbox_policy: str = "off" - dangerously_disable_sandbox: bool = False - session: ToolSession = field(default_factory=LocalToolSession) - auto_approve: bool = False - - def __post_init__(self) -> None: - self.cwd = Path(self.cwd).resolve() - - def runtime(self) -> ForgeRuntime: - """Preferred runtime: Hybrid (Rust+Python) when built, else Python-only.""" - if rust_forge_available(): - return HybridForgeRuntime.create( - cwd=str(self.cwd), - sandbox_policy=self.sandbox_policy, - dangerously_disable_sandbox=self.dangerously_disable_sandbox, - session=self.session, - auto_approve=self.auto_approve, - ) - return LocalToolRuntime( - cwd=str(self.cwd), - sandbox_policy=self.sandbox_policy, - dangerously_disable_sandbox=self.dangerously_disable_sandbox, - session=self.session, - ) - - @classmethod - def ephemeral( - cls, cwd: Path | str = ".", *, auto_approve: bool = True - ) -> ForgeEnvironment: - """Environment with no host session side effects (shell/files only).""" - return cls(cwd=cwd, session=NullToolSession(), auto_approve=auto_approve) diff --git a/python/pulsing/forge/event_inbox.py b/python/pulsing/forge/event_inbox.py deleted file mode 100644 index 819c3f632..000000000 --- a/python/pulsing/forge/event_inbox.py +++ /dev/null @@ -1,70 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge event inbox — decouple tell delivery from host mailbox.""" - -from __future__ import annotations - -import logging -from typing import Any - -from pulsing.core.proxy import ActorProxy -from pulsing.core.remote import remote, resolve - -from pulsing.forge.events import ForgeEvent, ForgeEventKind -from pulsing.forge.naming import forge_event_inbox_name - -logger = logging.getLogger(__name__) - -_STREAM_KINDS = frozenset( - { - ForgeEventKind.EXEC_OUTPUT_DELTA.value, - ForgeEventKind.TOOL_BEGIN.value, - ForgeEventKind.TOOL_END.value, - ForgeEventKind.USER_INPUT_REQUEST.value, - } -) - - -@remote -class ForgeEventInbox: - """Collects Forge events and forwards side effects to the host agent.""" - - def __init__(self, host_name: str) -> None: - self._host_name = (host_name or "").strip() - self._events: list[dict[str, Any]] = [] - - async def on_forge_event(self, event: dict[str, Any]) -> None: - raw = dict(event) - self._events.append(raw) - if not self._host_name: - return - kind = str(raw.get("kind") or "") - try: - host = await resolve(self._host_name) - if kind in _STREAM_KINDS: - await host.as_any().tell("on_forge_stream_event", raw) - else: - await host.as_any().tell("on_forge_side_effect", raw) - except Exception as exc: - logger.warning( - "forge inbox forward failed host=%s kind=%s: %s", - self._host_name, - kind, - exc, - ) - - def get_forge_events(self, since: int = 0) -> list[dict[str, Any]]: - if since <= 0: - return list(self._events) - return self._events[since:] - - def event_count(self) -> int: - return len(self._events) - - -async def ensure_forge_event_inbox(host_name: str) -> ActorProxy: - """Resolve or spawn ``{host}/events``.""" - name = forge_event_inbox_name(host_name) - try: - return await resolve(name, cls=ForgeEventInbox, timeout=30.0) - except Exception: - return await ForgeEventInbox.spawn(host_name, name=name, public=True) diff --git a/python/pulsing/forge/events.py b/python/pulsing/forge/events.py deleted file mode 100644 index 603cd8f14..000000000 --- a/python/pulsing/forge/events.py +++ /dev/null @@ -1,86 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge → Host point-to-point events (Codex event-bus equivalent).""" - -from __future__ import annotations - -import time -from dataclasses import asdict, dataclass, field -from enum import Enum -from typing import Any - - -class ForgeEventKind(str, Enum): - EXEC_OUTPUT_DELTA = "exec_output_delta" - TOOL_BEGIN = "tool_begin" - TOOL_END = "tool_end" - PLAN_UPDATED = "plan_updated" - NEW_CONTEXT = "new_context" - USER_INPUT_REQUEST = "user_input_request" - EXEC_APPROVAL_REQUEST = "exec_approval_request" - REQUEST_PERMISSIONS = "request_permissions" - - -@dataclass -class ForgeEvent: - """Pickle-friendly envelope for actor tell/ask transport.""" - - kind: str - payload: dict[str, Any] - source: str | None = None - ts: float = field(default_factory=time.time) - - def to_dict(self) -> dict[str, Any]: - return asdict(self) - - @classmethod - def from_dict(cls, raw: dict[str, Any]) -> ForgeEvent: - return cls( - kind=str(raw.get("kind", "")), - payload=dict(raw.get("payload") or {}), - source=raw.get("source"), - ts=float(raw.get("ts") or time.time()), - ) - - @classmethod - def exec_output_delta( - cls, *, session_id: int, stream: str, chunk: str - ) -> ForgeEvent: - return cls( - kind=ForgeEventKind.EXEC_OUTPUT_DELTA.value, - payload={"session_id": session_id, "stream": stream, "chunk": chunk}, - ) - - @classmethod - def tool_begin( - cls, tool: str, arguments: dict[str, Any] | None = None - ) -> ForgeEvent: - return cls( - kind=ForgeEventKind.TOOL_BEGIN.value, - source=tool, - payload={"arguments": dict(arguments or {})}, - ) - - @classmethod - def tool_end( - cls, tool: str, *, is_error: bool, content_preview: str = "" - ) -> ForgeEvent: - preview = content_preview[:500] - return cls( - kind=ForgeEventKind.TOOL_END.value, - source=tool, - payload={"is_error": is_error, "content_preview": preview}, - ) - - @classmethod - def exec_approval_request(cls, request: dict[str, Any]) -> ForgeEvent: - return cls( - kind=ForgeEventKind.EXEC_APPROVAL_REQUEST.value, - payload=dict(request), - ) - - @classmethod - def request_permissions(cls, args: dict[str, Any]) -> ForgeEvent: - return cls( - kind=ForgeEventKind.REQUEST_PERMISSIONS.value, - payload=dict(args), - ) diff --git a/python/pulsing/forge/exec_output.py b/python/pulsing/forge/exec_output.py deleted file mode 100644 index 3b5914ebc..000000000 --- a/python/pulsing/forge/exec_output.py +++ /dev/null @@ -1,138 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex-compatible exec output helpers.""" - -from __future__ import annotations - -import uuid -from dataclasses import asdict, dataclass -from enum import Enum -from typing import Any - -DEFAULT_SHELL_TIMEOUT_MS = 10_000 -DEFAULT_YIELD_TIME_MS = 250 -MIN_YIELD_TIME_MS = 250 -MAX_YIELD_TIME_MS = 30_000 -DEFAULT_MAX_OUTPUT_TOKENS = 10_000 -SHELL_MAX_BYTES = 256 * 1024 -MAX_STDIN_BYTES = 1024 * 1024 -RUNNING_EXIT_SENTINEL = -(2**31) - - -class ExecStream(str, Enum): - STDOUT = "stdout" - STDERR = "stderr" - PTY = "pty" - - -@dataclass -class ExecOutputDelta: - session_id: int - stream: ExecStream - chunk: str - - -@dataclass -class ExecCommandOutput: - chunk_id: str - wall_time_seconds: float - output: str - exit_code: int | None = None - session_id: int | None = None - original_token_count: int | None = None - - @classmethod - def build( - cls, - output: str, - wall_time_seconds: float, - exit_code: int | None, - session_id: int | None, - ) -> ExecCommandOutput: - return cls( - chunk_id=str(uuid.uuid4()), - wall_time_seconds=wall_time_seconds, - output=output, - exit_code=exit_code, - session_id=session_id, - original_token_count=max(1, len(output) // 4), - ) - - def to_dict(self) -> dict[str, Any]: - d = asdict(self) - return {k: v for k, v in d.items() if v is not None} - - -def _tail_at(s: str, keep: int) -> str: - # Python str slicing is codepoint-safe; keep parity with Rust helper naming. - return s[-keep:] if keep > 0 else "" - - -class Utf8ChunkDecoder: - """Incrementally decode PTY/pipe byte chunks without splitting codepoints.""" - - def __init__(self) -> None: - self._pending = bytearray() - - def decode(self, data: bytes) -> str: - if data: - self._pending.extend(data) - try: - out = self._pending.decode("utf-8") - self._pending.clear() - return out - except UnicodeDecodeError as e: - valid_len = e.start - out = self._pending[:valid_len].decode("utf-8", errors="replace") - leftover = len(self._pending) - valid_len - if leftover > 4: - rest = self._pending[valid_len:].decode("utf-8", errors="replace") - self._pending.clear() - return out + rest - del self._pending[:valid_len] - return out - - def finish(self) -> str: - if not self._pending: - return "" - out = self._pending.decode("utf-8", errors="replace") - self._pending.clear() - return out - - -class OutputBuffer: - def __init__(self, max_bytes: int = SHELL_MAX_BYTES) -> None: - self._max_bytes = max_bytes - self._data = "" - - def push(self, chunk: str) -> None: - if not chunk: - return - self._data += chunk - if len(self._data) > self._max_bytes: - keep = self._max_bytes // 2 - self._data = f"...[output truncated]...\n{_tail_at(self._data, keep)}" - - def snapshot(self) -> str: - return self._data - - def truncate_to_tokens(self, max_tokens: int) -> None: - est = max(1, len(self._data) // 4) - if est <= max_tokens: - return - ratio = max_tokens / est - keep = int(len(self._data) * ratio) - self._data = f"...[token limit]...\n{_tail_at(self._data, keep)}" - - -def clamp_yield_ms(raw: int | None) -> int: - return max(MIN_YIELD_TIME_MS, min(raw or DEFAULT_YIELD_TIME_MS, MAX_YIELD_TIME_MS)) - - -def shell_timeout_ms(args: dict[str, Any]) -> int: - raw_ms = args.get("timeout_ms") - if raw_ms is not None: - return max(1, int(raw_ms)) - raw_sec = args.get("timeout_sec") - if raw_sec is not None: - return max(1, int(raw_sec) * 1000) - return DEFAULT_SHELL_TIMEOUT_MS diff --git a/python/pulsing/forge/extension/__init__.py b/python/pulsing/forge/extension/__init__.py deleted file mode 100644 index 1586c1db7..000000000 --- a/python/pulsing/forge/extension/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex Extension tools — grouped by domain, implemented under forge/extension/.""" - -from pulsing.forge.extension.handlers import ( - EXTENSION_TOOL_NAMES, - dispatch_extension_tool, -) -from pulsing.forge.extension.protocol import ( - MEMORIES_ADD_AD_HOC_NOTE_TOOL, - MEMORIES_LIST_TOOL, - MEMORIES_READ_TOOL, - MEMORIES_SEARCH_TOOL, - MEMORIES_NAMESPACE, - SKILLS_LIST_TOOL, - SKILLS_READ_TOOL, - SKILLS_NAMESPACE, - WEB_NAMESPACE, - WEB_RUN_TOOL, - WEB_SEARCH_TOOL, -) - -__all__ = [ - "EXTENSION_TOOL_NAMES", - "MEMORIES_ADD_AD_HOC_NOTE_TOOL", - "MEMORIES_LIST_TOOL", - "MEMORIES_NAMESPACE", - "MEMORIES_READ_TOOL", - "MEMORIES_SEARCH_TOOL", - "SKILLS_LIST_TOOL", - "SKILLS_NAMESPACE", - "SKILLS_READ_TOOL", - "WEB_NAMESPACE", - "WEB_RUN_TOOL", - "WEB_SEARCH_TOOL", - "dispatch_extension_tool", -] diff --git a/python/pulsing/forge/extension/handlers.py b/python/pulsing/forge/extension/handlers.py deleted file mode 100644 index 8a6ec962e..000000000 --- a/python/pulsing/forge/extension/handlers.py +++ /dev/null @@ -1,58 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Dispatch Codex Extension namespace tools.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.extension.protocol import ( - EXTENSION_TOOL_NAMES, - MEMORIES_ADD_AD_HOC_NOTE_TOOL, - MEMORIES_LIST_TOOL, - MEMORIES_READ_TOOL, - MEMORIES_SEARCH_TOOL, - SKILLS_LIST_TOOL, - SKILLS_READ_TOOL, - WEB_RUN_TOOL, - WEB_SEARCH_TOOL, -) -from pulsing.forge.extension.memories.handlers import ( - handle_memories_add_ad_hoc_note, - handle_memories_list, - handle_memories_read, - handle_memories_search, -) -from pulsing.forge.extension.skills.handlers import ( - handle_skills_list, - handle_skills_read, -) -from pulsing.forge.extension.web_run.handlers import handle_web_run -from pulsing.forge.extension.web_search.handlers import handle_web_search -from pulsing.forge.result import ToolResult - -_HANDLERS = { - WEB_RUN_TOOL: handle_web_run, - SKILLS_LIST_TOOL: handle_skills_list, - SKILLS_READ_TOOL: handle_skills_read, - MEMORIES_LIST_TOOL: handle_memories_list, - MEMORIES_READ_TOOL: handle_memories_read, - MEMORIES_SEARCH_TOOL: handle_memories_search, - MEMORIES_ADD_AD_HOC_NOTE_TOOL: handle_memories_add_ad_hoc_note, - WEB_SEARCH_TOOL: handle_web_search, -} - - -def dispatch_extension_tool( - name: str, - arguments: dict[str, Any], - *, - ctx: ToolCallContext, -) -> ToolResult: - impl = _HANDLERS.get(name) - if impl is None: - return ToolResult(content=f"unknown extension tool: {name}", is_error=True) - return impl(ctx=ctx, **dict(arguments)) - - -__all__ = ["EXTENSION_TOOL_NAMES", "dispatch_extension_tool"] diff --git a/python/pulsing/forge/extension/memories/__init__.py b/python/pulsing/forge/extension/memories/__init__.py deleted file mode 100644 index 60effef99..000000000 --- a/python/pulsing/forge/extension/memories/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -from pulsing.forge.extension.memories.backend import ( - DEFAULT_LIST_MAX_RESULTS, - DEFAULT_READ_MAX_TOKENS, - DEFAULT_SEARCH_MAX_RESULTS, - MemoriesBackendError, - SearchMatchMode, -) -from pulsing.forge.extension.memories.handlers import ( - handle_memories_add_ad_hoc_note, - handle_memories_list, - handle_memories_read, - handle_memories_search, -) -from pulsing.forge.extension.memories.local_backend import LocalMemoriesStore - -__all__ = [ - "DEFAULT_LIST_MAX_RESULTS", - "DEFAULT_READ_MAX_TOKENS", - "DEFAULT_SEARCH_MAX_RESULTS", - "LocalMemoriesStore", - "MemoriesBackendError", - "SearchMatchMode", - "handle_memories_add_ad_hoc_note", - "handle_memories_list", - "handle_memories_read", - "handle_memories_search", -] diff --git a/python/pulsing/forge/extension/memories/backend.py b/python/pulsing/forge/extension/memories/backend.py deleted file mode 100644 index d0c0c2217..000000000 --- a/python/pulsing/forge/extension/memories/backend.py +++ /dev/null @@ -1,181 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Memories backend wire types (aligned with codex-rs/ext/memories).""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from enum import Enum -from typing import Any, Literal - -DEFAULT_LIST_MAX_RESULTS = 2000 -MAX_LIST_RESULTS = 2000 -DEFAULT_SEARCH_MAX_RESULTS = 200 -MAX_SEARCH_RESULTS = 200 -MAX_SEARCH_QUERIES = 16 -MAX_SEARCH_CONTEXT_LINES = 50 -MAX_SEARCH_MATCH_WINDOW_LINES = 200 -DEFAULT_READ_MAX_TOKENS = 20_000 - -AD_HOC_NOTES_DIR = ("extensions", "ad_hoc", "notes") -AD_HOC_NOTE_FILENAME_MAX_BYTES = 128 -AD_HOC_NOTE_SLUG_MAX_BYTES = 80 -AD_HOC_NOTE_MAX_BYTES = 256 * 1024 -TIMESTAMP_PREFIX_LEN = len("YYYY-MM-DDTHH-MM-SS-") - - -class MemoryEntryType(str, Enum): - FILE = "file" - DIRECTORY = "directory" - - -class SearchMatchModeKind(str, Enum): - ANY = "any" - ALL_ON_SAME_LINE = "all_on_same_line" - ALL_WITHIN_LINES = "all_within_lines" - - -@dataclass -class SearchMatchMode: - kind: SearchMatchModeKind = SearchMatchModeKind.ANY - line_count: int = 1 - - @classmethod - def from_wire(cls, raw: Any) -> SearchMatchMode: - if raw is None: - return cls() - if isinstance(raw, str): - try: - return cls(kind=SearchMatchModeKind(raw)) - except ValueError: - return cls() - if isinstance(raw, dict): - typ = raw.get("type") or raw.get("kind") or "any" - if typ == "all_within_lines": - raw_line_count = raw.get("line_count") - line_count = int(raw_line_count if raw_line_count is not None else 1) - return cls( - kind=SearchMatchModeKind.ALL_WITHIN_LINES, - line_count=line_count, - ) - try: - return cls(kind=SearchMatchModeKind(str(typ))) - except ValueError: - return cls() - return cls() - - def to_wire(self) -> dict[str, Any]: - if self.kind == SearchMatchModeKind.ALL_WITHIN_LINES: - return {"type": "all_within_lines", "line_count": self.line_count} - return {"type": self.kind.value} - - -@dataclass(frozen=True) -class MemoryEntry: - path: str - entry_type: MemoryEntryType - - def to_dict(self) -> dict[str, str]: - return {"path": self.path, "entry_type": self.entry_type.value} - - -@dataclass -class ListMemoriesResponse: - path: str | None - entries: list[MemoryEntry] - next_cursor: str | None = None - truncated: bool = False - - def to_dict(self) -> dict[str, Any]: - return { - "path": self.path, - "entries": [e.to_dict() for e in self.entries], - "next_cursor": self.next_cursor, - "truncated": self.truncated, - } - - -@dataclass -class ReadMemoryResponse: - path: str - start_line_number: int - content: str - truncated: bool = False - - def to_dict(self) -> dict[str, Any]: - return { - "path": self.path, - "start_line_number": self.start_line_number, - "content": self.content, - "truncated": self.truncated, - } - - -@dataclass -class MemorySearchMatch: - path: str - match_line_number: int - content_start_line_number: int - content: str - matched_queries: list[str] - - def to_dict(self) -> dict[str, Any]: - return { - "path": self.path, - "match_line_number": self.match_line_number, - "content_start_line_number": self.content_start_line_number, - "content": self.content, - "matched_queries": self.matched_queries, - } - - -@dataclass -class SearchMemoriesResponse: - queries: list[str] - match_mode: SearchMatchMode - path: str | None - matches: list[MemorySearchMatch] - next_cursor: str | None = None - truncated: bool = False - - def to_dict(self) -> dict[str, Any]: - return { - "queries": self.queries, - "match_mode": self.match_mode.to_wire(), - "path": self.path, - "matches": [m.to_dict() for m in self.matches], - "next_cursor": self.next_cursor, - "truncated": self.truncated, - } - - -class MemoriesBackendError(Exception): - """Model-facing memory backend error (maps to Codex RespondToModel errors).""" - - def __init__(self, message: str, *, fatal: bool = False) -> None: - super().__init__(message) - self.fatal = fatal - - @classmethod - def invalid_filename(cls, filename: str, reason: str) -> MemoriesBackendError: - return cls(f"filename '{filename}' {reason}") - - @classmethod - def invalid_path(cls, path: str, reason: str) -> MemoriesBackendError: - return cls(f"path '{path}' {reason}") - - @classmethod - def invalid_cursor(cls, cursor: str, reason: str) -> MemoriesBackendError: - return cls(f"cursor '{cursor}' {reason}") - - @classmethod - def not_found(cls, path: str) -> MemoriesBackendError: - return cls(f"path '{path}' was not found") - - @classmethod - def not_file(cls, path: str) -> MemoriesBackendError: - return cls(f"path '{path}' is not a file") - - @classmethod - def write_failed(cls, filename: str, exc: OSError) -> MemoriesBackendError: - reason = exc.strerror or str(exc) - return cls(f"failed to write ad-hoc note '{filename}': {reason}") diff --git a/python/pulsing/forge/extension/memories/handlers.py b/python/pulsing/forge/extension/memories/handlers.py deleted file mode 100644 index a97271143..000000000 --- a/python/pulsing/forge/extension/memories/handlers.py +++ /dev/null @@ -1,142 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Handlers for ``memories.*`` namespace tools (Codex wire shapes).""" - -from __future__ import annotations - -import json -from typing import Any - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.extension.memories.backend import ( - MemoriesBackendError, - SearchMatchMode, -) -from pulsing.forge.extension.memories.local_backend import ( - LocalMemoriesStore, - default_ad_hoc_filename, -) -from pulsing.forge.extension.memories.path_utils import ( - validate_optional_scoped_path, - validate_read_path, -) -from pulsing.forge.result import ToolResult - - -def _store(ctx: ToolCallContext) -> LocalMemoriesStore: - return ctx.memories - - -def _ok_response(payload: dict[str, Any]) -> ToolResult: - return ToolResult( - content=json.dumps(payload, indent=2, ensure_ascii=False), - structured=payload, - ) - - -def _err(exc: Exception) -> ToolResult: - return ToolResult(content=str(exc), is_error=True) - - -def handle_memories_list( - *, - ctx: ToolCallContext, - path: str | None = None, - cursor: str | None = None, - max_results: int | None = None, - **_: Any, -) -> ToolResult: - try: - rel_path = validate_optional_scoped_path(path) - except MemoriesBackendError as exc: - return _err(exc) - try: - response = _store(ctx).list_memories( - path=rel_path, cursor=cursor, max_results=max_results - ) - except MemoriesBackendError as exc: - return _err(exc) - except OSError as exc: - return _err(exc) - return _ok_response(response.to_dict()) - - -def handle_memories_read( - *, - ctx: ToolCallContext, - path: str = "", - line_offset: int | None = None, - max_lines: int | None = None, - max_tokens: int | None = None, - **_: Any, -) -> ToolResult: - try: - rel_path = validate_read_path(path) - except MemoriesBackendError as exc: - return _err(exc) - try: - response = _store(ctx).read_memory( - path=rel_path, - line_offset=int(line_offset or 1), - max_lines=max_lines, - max_tokens=int(max_tokens or 0), - ) - except MemoriesBackendError as exc: - return _err(exc) - except OSError as exc: - return _err(exc) - return _ok_response(response.to_dict()) - - -def handle_memories_search( - *, - ctx: ToolCallContext, - queries: list[str] | None = None, - query: str = "", - match_mode: Any = None, - path: str | None = None, - cursor: str | None = None, - context_lines: int | None = None, - case_sensitive: bool | None = None, - normalized: bool | None = None, - max_results: int | None = None, - **_: Any, -) -> ToolResult: - qlist = list(queries) if queries else ([query] if query else []) - rel_path = str(path).strip() if path else None - if rel_path == "": - rel_path = None - try: - response = _store(ctx).search_memories( - queries=qlist, - match_mode=SearchMatchMode.from_wire(match_mode), - path=rel_path, - cursor=cursor, - context_lines=int(context_lines or 0), - case_sensitive=bool(case_sensitive if case_sensitive is not None else True), - normalized=bool(normalized or False), - max_results=max_results, - ) - except MemoriesBackendError as exc: - return _err(exc) - return _ok_response(response.to_dict()) - - -def handle_memories_add_ad_hoc_note( - *, - ctx: ToolCallContext, - filename: str = "", - path: str = "", - note: str = "", - text: str = "", - content: str = "", - **_: Any, -) -> ToolResult: - body = note or text or content - name = (filename or path).strip() or default_ad_hoc_filename(body[:40]) - try: - out = _store(ctx).add_ad_hoc_note(filename=name, note=body) - except MemoriesBackendError as exc: - return _err(exc) - except OSError as exc: - return _err(exc) - return _ok_response(out) diff --git a/python/pulsing/forge/extension/memories/local_backend.py b/python/pulsing/forge/extension/memories/local_backend.py deleted file mode 100644 index c6eed711a..000000000 --- a/python/pulsing/forge/extension/memories/local_backend.py +++ /dev/null @@ -1,571 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Local filesystem memories backend (codex-rs/ext/memories/local).""" - -from __future__ import annotations - -import os -import re -import secrets -import stat -from contextlib import suppress -from dataclasses import dataclass -from datetime import datetime, timezone -from pathlib import Path - -from pulsing.forge.extension.memories.backend import ( - AD_HOC_NOTES_DIR, - AD_HOC_NOTE_FILENAME_MAX_BYTES, - AD_HOC_NOTE_MAX_BYTES, - AD_HOC_NOTE_SLUG_MAX_BYTES, - DEFAULT_LIST_MAX_RESULTS, - DEFAULT_READ_MAX_TOKENS, - DEFAULT_SEARCH_MAX_RESULTS, - MAX_LIST_RESULTS, - MAX_SEARCH_CONTEXT_LINES, - MAX_SEARCH_MATCH_WINDOW_LINES, - MAX_SEARCH_QUERIES, - MAX_SEARCH_RESULTS, - TIMESTAMP_PREFIX_LEN, - ListMemoriesResponse, - MemoriesBackendError, - MemoryEntry, - MemoryEntryType, - MemorySearchMatch, - ReadMemoryResponse, - SearchMatchMode, - SearchMatchModeKind, - SearchMemoriesResponse, -) -from pulsing.forge.extension.memories.path_utils import ( - assert_readable_memory_file, - display_relative_path, - is_hidden_component, - is_hidden_path, - is_symlink, - metadata_or_none, - read_sorted_dir_paths, - reject_symlink, -) -from pulsing.forge.extension.paths import memories_root - -_AD_HOC_FILENAME_RE = re.compile( - r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-[a-z0-9][a-z0-9-]{0,79}\.md$" -) - - -def clamp_max_results(requested: int | None, default: int, maximum: int) -> int: - value = int(requested if requested is not None else default) - return max(1, min(value, maximum)) - - -def truncate_tokens(text: str, max_tokens: int) -> tuple[str, bool]: - """Approximate Codex token truncation (~4 chars per token).""" - if max_tokens <= 0: - max_tokens = DEFAULT_READ_MAX_TOKENS - max_chars = max_tokens * 4 - if len(text) <= max_chars: - return text, False - return text[:max_chars], True - - -def default_ad_hoc_filename(slug: str) -> str: - """Build a timestamp+slug filename with a random suffix. - - The suffix keeps concurrent/rapid calls (second-granularity timestamp, - possibly identical slug) from colliding on the same path. - """ - ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H-%M-%S") - clean = re.sub(r"[^a-z0-9]+", "-", slug.lower()).strip("-") or "note" - suffix = f"-{secrets.token_hex(3)}" - clean = clean[: AD_HOC_NOTE_SLUG_MAX_BYTES - len(suffix)] - return f"{ts}-{clean}{suffix}.md" - - -@dataclass -class LocalMemoriesStore: - root: Path - - def __init__(self, root: Path | None = None) -> None: - self.root = (root or memories_root()).resolve() - try: - self.root.mkdir(parents=True, exist_ok=True) - except OSError as exc: - raise MemoriesBackendError(str(exc), fatal=True) from exc - - @classmethod - def from_codex_home(cls, codex_home: Path) -> LocalMemoriesStore: - return cls(codex_home / "memories") - - def resolve_scoped_path(self, relative_path: str | None) -> Path: - if not relative_path: - return self.root - relative = Path(relative_path) - if relative.is_absolute(): - raise MemoriesBackendError.invalid_path( - relative_path, "must stay within the memories root" - ) - if any(p == ".." for p in relative.parts): - raise MemoriesBackendError.invalid_path( - relative_path, "must stay within the memories root" - ) - for part in relative.parts: - if is_hidden_component(part): - raise MemoriesBackendError.not_found(relative_path) - - scoped = self.root - components = list(relative.parts) - for idx, part in enumerate(components): - scoped = scoped / part - meta = metadata_or_none(scoped) - if meta is None: - if idx + 1 < len(components): - for remaining in components[idx + 1 :]: - scoped = scoped / remaining - return scoped.resolve() - reject_symlink(display_relative_path(self.root, scoped), scoped) - if not scoped.resolve().is_relative_to(self.root): - raise MemoriesBackendError.invalid_path( - relative_path, "must stay within the memories root" - ) - if idx + 1 < len(components) and not os.path.isdir(scoped): - raise MemoriesBackendError.invalid_path( - relative_path, - "traverses through a non-directory path component", - ) - return scoped.resolve() - - def list_memories( - self, - *, - path: str | None = None, - cursor: str | None = None, - max_results: int | None = None, - ) -> ListMemoriesResponse: - limit = clamp_max_results( - max_results, DEFAULT_LIST_MAX_RESULTS, MAX_LIST_RESULTS - ) - start_path = self.resolve_scoped_path(path) - start_index = _parse_cursor(cursor) - - meta = metadata_or_none(start_path) - if meta is None: - raise MemoriesBackendError.not_found(path or "") - - reject_symlink(display_relative_path(self.root, start_path), start_path) - - if os.path.isfile(start_path): - entries = [ - MemoryEntry( - path=display_relative_path(self.root, start_path), - entry_type=MemoryEntryType.FILE, - ) - ] - elif os.path.isdir(start_path): - entries = [] - for child in read_sorted_dir_paths(start_path): - if is_hidden_path(child): - continue - child_meta = metadata_or_none(child) - if child_meta is None or is_symlink(child): - continue - if stat.S_ISDIR(child_meta.st_mode): - entry_type = MemoryEntryType.DIRECTORY - elif stat.S_ISREG(child_meta.st_mode): - entry_type = MemoryEntryType.FILE - else: - continue - entries.append( - MemoryEntry( - path=display_relative_path(self.root, child), - entry_type=entry_type, - ) - ) - else: - entries = [] - - if start_index > len(entries): - raise MemoriesBackendError.invalid_cursor( - str(start_index), "exceeds result count" - ) - - end_index = min(start_index + limit, len(entries)) - next_cursor = str(end_index) if end_index < len(entries) else None - return ListMemoriesResponse( - path=path, - entries=entries[start_index:end_index], - next_cursor=next_cursor, - truncated=next_cursor is not None, - ) - - def read_memory( - self, - *, - path: str, - line_offset: int = 1, - max_lines: int | None = None, - max_tokens: int = DEFAULT_READ_MAX_TOKENS, - ) -> ReadMemoryResponse: - if line_offset < 1: - raise MemoriesBackendError("line_offset must be a 1-indexed line number") - if max_lines is not None and max_lines < 1: - raise MemoriesBackendError("max_lines must be a positive integer") - - file_path = self.resolve_scoped_path(path) - assert_readable_memory_file( - root=self.root, relative_path=path, file_path=file_path - ) - - try: - original = file_path.read_text(encoding="utf-8") - except UnicodeDecodeError as exc: - raise MemoriesBackendError( - f"path '{path}' is not valid UTF-8 text" - ) from exc - start_byte = _line_start_byte_offset(original, line_offset) - end_byte = _line_end_byte_offset(original, start_byte, max_lines) - slice_text = original[start_byte:end_byte] - content, token_truncated = truncate_tokens(slice_text, max_tokens) - truncated = end_byte < len(original) or token_truncated or content != slice_text - return ReadMemoryResponse( - path=path, - start_line_number=line_offset, - content=content, - truncated=truncated, - ) - - def search_memories( - self, - *, - queries: list[str], - match_mode: SearchMatchMode | None = None, - path: str | None = None, - cursor: str | None = None, - context_lines: int = 0, - case_sensitive: bool = True, - normalized: bool = False, - max_results: int | None = None, - ) -> SearchMemoriesResponse: - cleaned = [q.strip() for q in queries] - if not cleaned: - raise MemoriesBackendError("at least one query is required") - if any(not q for q in cleaned): - raise MemoriesBackendError("queries must not contain empty strings") - if len(cleaned) > MAX_SEARCH_QUERIES: - raise MemoriesBackendError( - f"queries must contain at most {MAX_SEARCH_QUERIES} entries" - ) - mode = match_mode or SearchMatchMode() - if mode.kind == SearchMatchModeKind.ALL_WITHIN_LINES: - if mode.line_count <= 0: - raise MemoriesBackendError( - "all_within_lines.line_count must be a positive integer" - ) - if mode.line_count > MAX_SEARCH_MATCH_WINDOW_LINES: - raise MemoriesBackendError( - f"all_within_lines.line_count must be at most {MAX_SEARCH_MATCH_WINDOW_LINES}" - ) - - limit = clamp_max_results( - max_results, DEFAULT_SEARCH_MAX_RESULTS, MAX_SEARCH_RESULTS - ) - bounded_context_lines = max(0, min(context_lines, MAX_SEARCH_CONTEXT_LINES)) - start_path = self.resolve_scoped_path(path) - start_index = _parse_cursor(cursor) - - meta = metadata_or_none(start_path) - if meta is None: - raise MemoriesBackendError.not_found(path or "") - - reject_symlink(display_relative_path(self.root, start_path), start_path) - - matcher = _SearchMatcher(cleaned, mode, case_sensitive, normalized) - matches: list[MemorySearchMatch] = [] - _search_entries( - self.root, start_path, meta, matcher, bounded_context_lines, matches - ) - - matches.sort(key=lambda m: (m.path, m.match_line_number)) - if start_index > len(matches): - raise MemoriesBackendError.invalid_cursor( - str(start_index), "exceeds result count" - ) - - end_index = min(start_index + limit, len(matches)) - next_cursor = str(end_index) if end_index < len(matches) else None - return SearchMemoriesResponse( - queries=cleaned, - match_mode=mode, - path=path, - matches=matches[start_index:end_index], - next_cursor=next_cursor, - truncated=next_cursor is not None, - ) - - def add_ad_hoc_note(self, *, filename: str, note: str) -> dict[str, object]: - _validate_ad_hoc_filename(filename) - if not note.strip(): - raise MemoriesBackendError("ad-hoc note must not be empty") - note_bytes = note.encode("utf-8") - if len(note_bytes) > AD_HOC_NOTE_MAX_BYTES: - raise MemoriesBackendError( - f"ad-hoc note exceeds {AD_HOC_NOTE_MAX_BYTES} byte limit" - f" ({len(note_bytes)} bytes given)" - ) - - notes_dir = self._ensure_notes_dir() - dest = notes_dir / filename - if dest.parent != notes_dir: - raise MemoriesBackendError.invalid_filename( - filename, "must not contain path separators" - ) - # O_EXCL makes create-if-absent atomic, closing the check-then-write - # race that a plain `exists()` check followed by `write_text()` would - # leave open between two concurrent callers targeting the same name. - try: - fd = os.open(dest, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) - except FileExistsError as exc: - raise MemoriesBackendError( - f"ad-hoc note '{filename}' already exists" - ) from exc - except OSError as exc: - raise MemoriesBackendError.write_failed(filename, exc) from exc - - try: - with os.fdopen(fd, "wb") as fh: - fh.write(note_bytes) - except OSError as exc: - with suppress(OSError): - dest.unlink() - raise MemoriesBackendError.write_failed(filename, exc) from exc - return {} - - def _ensure_notes_dir(self) -> Path: - path = self.root - for component in AD_HOC_NOTES_DIR: - path = path / component - meta = metadata_or_none(path) - if meta is None: - try: - path.mkdir(parents=True, exist_ok=True) - except OSError as exc: - raise MemoriesBackendError.write_failed(str(path), exc) from exc - meta = metadata_or_none(path) - if meta is None: - raise MemoriesBackendError.not_found(str(path)) - reject_symlink(str(path), path) - if not os.path.isdir(path): - raise MemoriesBackendError.invalid_path( - str(path), "must be a directory" - ) - return path - - -def _parse_cursor(cursor: str | None) -> int: - if not cursor: - return 0 - try: - value = int(cursor) - except ValueError as exc: - raise MemoriesBackendError.invalid_cursor( - cursor, "must be a non-negative integer" - ) from exc - if value < 0: - raise MemoriesBackendError.invalid_cursor( - cursor, "must be a non-negative integer" - ) - return value - - -def _line_start_byte_offset(content: str, line_offset: int) -> int: - if line_offset == 1: - return 0 - current = 1 - for idx, ch in enumerate(content): - if ch == "\n": - current += 1 - if current == line_offset: - return idx + 1 - raise MemoriesBackendError("line_offset exceeds file length") - - -def _line_end_byte_offset(content: str, start_byte: int, max_lines: int | None) -> int: - if max_lines is None: - return len(content) - lines_seen = 1 - for relative_idx, ch in enumerate(content[start_byte:]): - if ch == "\n": - if lines_seen == max_lines: - return start_byte + relative_idx + 1 - lines_seen += 1 - return len(content) - - -def _validate_ad_hoc_filename(filename: str) -> None: - if len(filename.encode("utf-8")) > AD_HOC_NOTE_FILENAME_MAX_BYTES: - raise MemoriesBackendError.invalid_filename( - filename, "must be at most 128 bytes" - ) - if not filename.endswith(".md"): - raise MemoriesBackendError.invalid_filename(filename, "must end with .md") - if not _AD_HOC_FILENAME_RE.match(filename): - raise MemoriesBackendError.invalid_filename( - filename, - "must use YYYY-MM-DDTHH-MM-SS-.md with lowercase slug", - ) - stem = filename[:-3] - slug = stem[TIMESTAMP_PREFIX_LEN:] - if not slug or len(slug.encode("utf-8")) > AD_HOC_NOTE_SLUG_MAX_BYTES: - raise MemoriesBackendError.invalid_filename( - filename, "slug must be 1 to 80 bytes" - ) - - -class _SearchMatcher: - def __init__( - self, - queries: list[str], - match_mode: SearchMatchMode, - case_sensitive: bool, - normalized: bool, - ) -> None: - self.queries = queries - self.match_mode = match_mode - self.case_sensitive = case_sensitive - self.normalized = normalized - self.prepared = [_prepare_query(q, case_sensitive, normalized) for q in queries] - empty = next( - (q for q, p in zip(queries, self.prepared, strict=True) if not p), None - ) - if empty is not None: - raise MemoriesBackendError(f"query {empty!r} is empty after normalization") - - def matched_query_flags(self, line: str) -> list[bool]: - hay = _prepare_query(line, self.case_sensitive, self.normalized) - return [q in hay for q in self.prepared] - - def matched_queries(self, flags: list[bool]) -> list[str]: - return [q for q, ok in zip(self.queries, flags, strict=True) if ok] - - -def _prepare_query(value: str, case_sensitive: bool, normalized: bool) -> str: - out = value if case_sensitive else value.lower() - if normalized: - out = "".join(ch for ch in out if ch.isalnum()) - return out - - -def _search_entries( - root: Path, - current: Path, - meta: os.stat_result, - matcher: _SearchMatcher, - context_lines: int, - matches: list[MemorySearchMatch], -) -> None: - if os.path.isfile(current): - _search_file(root, current, matcher, context_lines, matches) - return - if not os.path.isdir(current): - return - - pending = [current] - while pending: - dir_path = pending.pop() - for path in read_sorted_dir_paths(dir_path): - if is_hidden_path(path): - continue - child_meta = metadata_or_none(path) - if child_meta is None or is_symlink(path): - continue - if os.path.isdir(path): - pending.append(path) - elif os.path.isfile(path): - _search_file(root, path, matcher, context_lines, matches) - - -def _search_file( - root: Path, - path: Path, - matcher: _SearchMatcher, - context_lines: int, - matches: list[MemorySearchMatch], -) -> None: - try: - content = path.read_text(encoding="utf-8") - except UnicodeDecodeError: - return - except OSError: - return - - lines = content.splitlines() - line_matches = [matcher.matched_query_flags(line) for line in lines] - mode = matcher.match_mode.kind - - if mode == SearchMatchModeKind.ANY: - for idx, flags in enumerate(line_matches): - if any(flags): - matches.append( - _build_match( - root, path, lines, idx, idx, context_lines, matcher, flags - ) - ) - elif mode == SearchMatchModeKind.ALL_ON_SAME_LINE: - for idx, flags in enumerate(line_matches): - if all(flags): - matches.append( - _build_match( - root, path, lines, idx, idx, context_lines, matcher, flags - ) - ) - elif mode == SearchMatchModeKind.ALL_WITHIN_LINES: - window = matcher.match_mode.line_count - windows: list[tuple[int, int, list[bool]]] = [] - for start in range(len(lines)): - if not any(line_matches[start]): - continue - last = min(start + window - 1, len(lines) - 1) - flags = [False] * len(matcher.queries) - for end in range(start, last + 1): - for i, matched in enumerate(line_matches[end]): - flags[i] = flags[i] or matched - if all(flags): - windows.append((start, end, flags.copy())) - break - # windows are already ordered by ascending start; a window is redundant - # (dominated) iff a later, narrower window is fully contained in it, so a - # single backward sweep with a running minimum end suffices (avoids O(n^2) - # all-pairs containment checks on files with many matching lines). - min_end_after = None - kept: list[tuple[int, int, list[bool]]] = [] - for start, end, flags in reversed(windows): - if min_end_after is not None and min_end_after <= end: - continue - kept.append((start, end, flags)) - min_end_after = end if min_end_after is None else min(min_end_after, end) - for start, end, flags in reversed(kept): - matches.append( - _build_match( - root, path, lines, start, end, context_lines, matcher, flags - ) - ) - - -def _build_match( - root: Path, - path: Path, - lines: list[str], - match_start: int, - match_end: int, - context_lines: int, - matcher: _SearchMatcher, - flags: list[bool], -) -> MemorySearchMatch: - content_start = max(0, match_start - context_lines) - content_end = min(len(lines), match_end + context_lines + 1) - return MemorySearchMatch( - path=display_relative_path(root, path), - match_line_number=match_start + 1, - content_start_line_number=content_start + 1, - content="\n".join(lines[content_start:content_end]), - matched_queries=matcher.matched_queries(flags), - ) diff --git a/python/pulsing/forge/extension/memories/path_utils.py b/python/pulsing/forge/extension/memories/path_utils.py deleted file mode 100644 index 5a80918e3..000000000 --- a/python/pulsing/forge/extension/memories/path_utils.py +++ /dev/null @@ -1,119 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Path helpers for local memories (codex ext/memories/local/path.rs).""" - -from __future__ import annotations - -import os -from pathlib import Path - -from pulsing.forge.extension.memories.backend import MemoriesBackendError - -MAX_READ_FILE_BYTES = 2 * 1024 * 1024 - - -def _os_error_message(exc: OSError) -> str: - return exc.strerror or str(exc) - - -def display_relative_path(root: Path, path: Path) -> str: - try: - rel = path.relative_to(root) - except ValueError: - rel = path - parts = [p for p in rel.parts if p] - return "/".join(parts) - - -def is_hidden_path(path: Path) -> bool: - name = path.name - return bool(name.startswith(".")) - - -def is_hidden_component(name: str) -> bool: - return name.startswith(".") - - -def is_symlink(path: Path) -> bool: - return path.is_symlink() - - -def reject_symlink(path: str, resolved: Path) -> None: - if is_symlink(resolved): - raise MemoriesBackendError.invalid_path(path, "must not be a symlink") - - -def validate_optional_scoped_path(path: str | None) -> str | None: - """Normalize optional list/search scope; reject escapes before filesystem access.""" - if path is None: - return None - rel = str(path).strip() - if not rel: - return None - if "\x00" in rel: - raise MemoriesBackendError.invalid_path( - rel, "must stay within the memories root" - ) - candidate = Path(rel) - if candidate.is_absolute(): - raise MemoriesBackendError.invalid_path( - rel, "must stay within the memories root" - ) - if any(part == ".." for part in candidate.parts): - raise MemoriesBackendError.invalid_path( - rel, "must stay within the memories root" - ) - for part in candidate.parts: - if is_hidden_component(part): - raise MemoriesBackendError.not_found(rel) - return rel - - -def validate_read_path(path: str) -> str: - """Normalize and reject obvious path-escape inputs before filesystem access.""" - rel = validate_optional_scoped_path(path) - if rel is None: - raise MemoriesBackendError("path is required") - return rel - - -def assert_readable_memory_file( - *, - root: Path, - relative_path: str, - file_path: Path, - max_bytes: int = MAX_READ_FILE_BYTES, -) -> None: - """Re-check symlink, root scope, and size immediately before reading.""" - meta = metadata_or_none(file_path) - if meta is None: - raise MemoriesBackendError.not_found(relative_path) - reject_symlink(relative_path, file_path) - if not file_path.resolve().is_relative_to(root.resolve()): - raise MemoriesBackendError.invalid_path( - relative_path, "must stay within the memories root" - ) - if not os.path.isfile(file_path): - raise MemoriesBackendError.not_file(relative_path) - if meta.st_size > max_bytes: - raise MemoriesBackendError( - f"path '{relative_path}' exceeds {max_bytes} byte read limit ({meta.st_size} bytes)" - ) - - -def read_sorted_dir_paths(dir_path: Path) -> list[Path]: - if not dir_path.is_dir(): - return [] - try: - paths = sorted(dir_path.iterdir(), key=lambda p: p.name) - except OSError as exc: - raise MemoriesBackendError(_os_error_message(exc), fatal=True) from exc - return paths - - -def metadata_or_none(path: Path) -> os.stat_result | None: - try: - return os.lstat(path) - except FileNotFoundError: - return None - except OSError as exc: - raise MemoriesBackendError(_os_error_message(exc), fatal=True) from exc diff --git a/python/pulsing/forge/extension/paths.py b/python/pulsing/forge/extension/paths.py deleted file mode 100644 index 77af51928..000000000 --- a/python/pulsing/forge/extension/paths.py +++ /dev/null @@ -1,32 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Filesystem roots for Extension tools (aligned with Codex layout).""" - -from __future__ import annotations - -import os -from pathlib import Path - -from pulsing.forge.discovery.codex_paths import codex_home - - -def agents_skills_roots(cwd: Path) -> list[Path]: - roots: list[Path] = [] - user = Path.home() / ".agents" / "skills" - if user.is_dir(): - roots.append(user.resolve()) - repo = (cwd / ".agents" / "skills").resolve() - if repo.is_dir(): - roots.append(repo) - extra = os.environ.get("FORGE_SKILLS_DIRS", "").strip() - for part in extra.split(os.pathsep): - p = Path(part).expanduser() - if p.is_dir(): - roots.append(p.resolve()) - return roots - - -def memories_root() -> Path: - raw = os.environ.get("FORGE_MEMORIES_ROOT", "").strip() - if raw: - return Path(raw).expanduser().resolve() - return (codex_home() / "memories").resolve() diff --git a/python/pulsing/forge/extension/protocol.py b/python/pulsing/forge/extension/protocol.py deleted file mode 100644 index 076a5af91..000000000 --- a/python/pulsing/forge/extension/protocol.py +++ /dev/null @@ -1,39 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex Extension tool names and shared wire constants.""" - -from __future__ import annotations - -# --- web.run (client search / browse; ext/web-search) --- -WEB_NAMESPACE = "web" -WEB_RUN_TOOL = "web.run" - -# --- skills (ext/skills + ~/.agents/skills) --- -SKILLS_NAMESPACE = "skills" -SKILLS_LIST_TOOL = "skills.list" -SKILLS_READ_TOOL = "skills.read" - -# --- memories (ext/memories; $CODEX_HOME/memories) --- -MEMORIES_NAMESPACE = "memories" -MEMORIES_LIST_TOOL = "memories.list" -MEMORIES_READ_TOOL = "memories.read" -MEMORIES_SEARCH_TOOL = "memories.search" -MEMORIES_ADD_AD_HOC_NOTE_TOOL = "memories.add_ad_hoc_note" - -# --- hosted Provider tool (Responses API; not client sandbox) --- -WEB_SEARCH_TOOL = "web_search" - -WEB_RUN_TOOLS: frozenset[str] = frozenset({WEB_RUN_TOOL}) -SKILLS_TOOLS: frozenset[str] = frozenset({SKILLS_LIST_TOOL, SKILLS_READ_TOOL}) -MEMORIES_TOOLS: frozenset[str] = frozenset( - { - MEMORIES_LIST_TOOL, - MEMORIES_READ_TOOL, - MEMORIES_SEARCH_TOOL, - MEMORIES_ADD_AD_HOC_NOTE_TOOL, - } -) -WEB_SEARCH_TOOLS: frozenset[str] = frozenset({WEB_SEARCH_TOOL}) - -EXTENSION_TOOL_NAMES: frozenset[str] = ( - WEB_RUN_TOOLS | SKILLS_TOOLS | MEMORIES_TOOLS | WEB_SEARCH_TOOLS -) diff --git a/python/pulsing/forge/extension/skills/__init__.py b/python/pulsing/forge/extension/skills/__init__.py deleted file mode 100644 index 622429b0a..000000000 --- a/python/pulsing/forge/extension/skills/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -from pulsing.forge.extension.skills.handlers import ( - handle_skills_list, - handle_skills_read, -) - -__all__ = ["handle_skills_list", "handle_skills_read"] diff --git a/python/pulsing/forge/extension/skills/catalog.py b/python/pulsing/forge/extension/skills/catalog.py deleted file mode 100644 index 85412eafa..000000000 --- a/python/pulsing/forge/extension/skills/catalog.py +++ /dev/null @@ -1,187 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Discover Agent Skills (SKILL.md) under Codex-standard paths.""" - -from __future__ import annotations - -import re -from dataclasses import dataclass -from pathlib import Path - -from pulsing.forge.extension.paths import agents_skills_roots - -_FRONTMATTER = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL) -_NAME_RE = re.compile(r"^name:\s*(.+)\s*$", re.MULTILINE) -_DESC_RE = re.compile(r"^description:\s*(.+)\s*$", re.MULTILINE) - - -@dataclass(frozen=True) -class SkillEntry: - name: str - description: str - path: str - root: str - - def to_dict(self) -> dict[str, str]: - return { - "name": self.name, - "description": self.description, - "path": self.path, - "root": self.root, - } - - -def _parse_skill_md(path: Path, root: Path) -> SkillEntry | None: - try: - text = path.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): - return None - name = path.parent.name - description = "" - body = text - match = _FRONTMATTER.match(text) - if match: - meta = match.group(1) - body = text[match.end() :] - if m := _NAME_RE.search(meta): - name = m.group(1).strip().strip('"').strip("'") - if m := _DESC_RE.search(meta): - description = m.group(1).strip().strip('"').strip("'") - if not description: - for line in body.splitlines(): - line = line.strip() - if line.startswith("#"): - description = line.lstrip("#").strip() - break - try: - rel = str(path.relative_to(root)) - except ValueError: - return None - return SkillEntry(name=name, description=description, path=rel, root=str(root)) - - -def _resolved_within_root(path: Path, root: Path) -> bool: - try: - safe_root = root.resolve() - resolved = path.resolve() - except OSError: - return False - return resolved == safe_root or safe_root in resolved.parents - - -def _has_symlink_component(root: Path, path: Path) -> bool: - """True when any path component under ``root`` is a symlink (lstat, no follow).""" - try: - safe_root = root.resolve() - rel = path.relative_to(safe_root) - except (OSError, ValueError): - return True - candidate = safe_root - for part in rel.parts: - if part in ("..", ""): - return True - candidate = candidate / part - if candidate.is_symlink(): - return True - return False - - -def _skill_md_is_listable(skill_md: Path, safe_root: Path) -> bool: - # Symlinked SKILL.md leaves still match a filename walk and would leak - # arbitrary file content via frontmatter/body parsing if read. - if skill_md.is_symlink() or not skill_md.is_file(): - return False - if _has_symlink_component(safe_root, skill_md): - return False - return _resolved_within_root(skill_md, safe_root) - - -def _iter_skill_md_files(safe_root: Path) -> list[Path]: - """Collect SKILL.md files under ``safe_root`` without following symlink dirs.""" - found: list[Path] = [] - stack = [safe_root] - while stack: - current = stack.pop() - try: - children = sorted(current.iterdir(), key=lambda p: p.name) - except OSError: - continue - for child in children: - if child.is_symlink(): - continue - if child.name == "SKILL.md" and child.is_file(): - found.append(child) - elif child.is_dir(): - stack.append(child) - return found - - -def list_skills(cwd: Path) -> list[SkillEntry]: - seen: set[str] = set() - out: list[SkillEntry] = [] - for root in agents_skills_roots(cwd): - try: - safe_root = root.resolve() - if not safe_root.is_dir(): - continue - candidates = _iter_skill_md_files(safe_root) - except OSError: - continue - for skill_md in candidates: - if not _skill_md_is_listable(skill_md, safe_root): - continue - entry = _parse_skill_md(skill_md, safe_root) - if entry is None: - continue - key = f"{entry.root}:{entry.path}" - if key in seen: - continue - seen.add(key) - out.append(entry) - return out - - -_SKILL_READ_CAP = 2 * 1024 * 1024 - - -def _resolve_within_root(root: Path, relative_path: str) -> Path: - """Resolve ``relative_path`` under ``root``, rejecting any symlink hop or escape. - - ``entry.path`` values always come from :func:`list_skills`'s own directory - walk, but we re-validate here (rather than trusting the cached entry) so a - symlink swapped in between listing and reading cannot smuggle an out-of-root - file into the response. - """ - safe_root = root.resolve() - candidate = safe_root - for part in Path(relative_path).parts: - if part in ("..", ""): - raise FileNotFoundError(f"skill not found: {relative_path}") - candidate = candidate / part - if _has_symlink_component(safe_root, candidate): - raise FileNotFoundError(f"skill not found: {relative_path}") - resolved = candidate.resolve() - if resolved != safe_root and safe_root not in resolved.parents: - raise FileNotFoundError(f"skill not found: {relative_path}") - return resolved - - -def _read_skill_file(entry: SkillEntry) -> str: - file_path = _resolve_within_root(Path(entry.root), entry.path) - try: - size = file_path.stat().st_size - except OSError as exc: - raise FileNotFoundError(f"skill not found: {entry.path}") from exc - if size > _SKILL_READ_CAP: - raise OSError(f"skill file too large to read (max {_SKILL_READ_CAP} bytes)") - return file_path.read_text(encoding="utf-8") - - -def read_skill(*, cwd: Path, name: str = "", path: str = "") -> str: - target_name = name.strip() - target_path = path.strip() - for entry in list_skills(cwd): - if target_path and entry.path == target_path: - return _read_skill_file(entry) - if target_name and entry.name == target_name: - return _read_skill_file(entry) - raise FileNotFoundError(f"skill not found: {name or path}") diff --git a/python/pulsing/forge/extension/skills/handlers.py b/python/pulsing/forge/extension/skills/handlers.py deleted file mode 100644 index f64a4f65b..000000000 --- a/python/pulsing/forge/extension/skills/handlers.py +++ /dev/null @@ -1,42 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Handlers for ``skills.list`` / ``skills.read``.""" - -from __future__ import annotations - -import json -from typing import Any - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.extension.skills.catalog import list_skills, read_skill -from pulsing.forge.result import ToolResult - - -def handle_skills_list(*, ctx: ToolCallContext, **_: Any) -> ToolResult: - try: - entries = [e.to_dict() for e in list_skills(ctx.cwd)] - except OSError: - entries = [] - return ToolResult( - content=json.dumps({"skills": entries}, indent=2, ensure_ascii=False), - structured={"skills": entries}, - ) - - -def handle_skills_read( - *, - ctx: ToolCallContext, - name: str = "", - path: str = "", - **_: Any, -) -> ToolResult: - target_name = name.strip() - target_path = path.strip() - if not target_name and not target_path: - return ToolResult(content="name or path is required", is_error=True) - try: - text = read_skill(cwd=ctx.cwd, name=target_name, path=target_path) - except FileNotFoundError as exc: - return ToolResult(content=str(exc), is_error=True) - except OSError as exc: - return ToolResult(content=str(exc), is_error=True) - return ToolResult(content=text) diff --git a/python/pulsing/forge/extension/web_run/__init__.py b/python/pulsing/forge/extension/web_run/__init__.py deleted file mode 100644 index 746a917a8..000000000 --- a/python/pulsing/forge/extension/web_run/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -from pulsing.forge.extension.web_run.handlers import handle_web_run - -__all__ = ["handle_web_run"] diff --git a/python/pulsing/forge/extension/web_run/handlers.py b/python/pulsing/forge/extension/web_run/handlers.py deleted file mode 100644 index 2f38118d2..000000000 --- a/python/pulsing/forge/extension/web_run/handlers.py +++ /dev/null @@ -1,337 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""``web.run`` — client web search / open / find (Codex ext/web-search). - -Codex ships no open-source implementation of this tool: the ChatGPT client -browses/searches via a hosted product service. This Forge implementation only -covers the ``open`` operation (direct HTTPS fetch), gated behind an explicit -host allowlist. ``search``/``find`` remain unimplemented and return a clear -error rather than a silent no-op. -""" - -from __future__ import annotations - -import ipaddress -import json -import os -import socket -from typing import Any -from urllib.error import HTTPError, URLError -from urllib.parse import urlparse -from urllib.request import HTTPRedirectHandler, Request, build_opener - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.result import ToolResult - -_FETCH_CAP = 512 * 1024 -_TIMEOUT_SECONDS = 30 - - -def _allowed_hosts() -> set[str]: - raw = os.environ.get( - "FORGE_WEB_ALLOW", os.environ.get("PULSING_CRAFT_FETCH_ALLOW", "") - ).strip() - return {h.strip().lower().rstrip(".") for h in raw.split(",") if h.strip()} - - -def _host_matches_allowlist(host: str, allowed: set[str]) -> bool: - """Match Codex network-proxy domain patterns: exact, *.apex, **.apex.""" - host = host.lower().rstrip(".") - for pattern in allowed: - if pattern.startswith("**."): - apex = pattern[3:] - if host == apex or host.endswith(f".{apex}"): - return True - elif pattern.startswith("*."): - apex = pattern[2:] - if host != apex and host.endswith(f".{apex}"): - return True - elif host == pattern: - return True - return False - - -def _resolve_ips(host: str) -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]: - try: - infos = socket.getaddrinfo(host, None) - except OSError: - return [] - ips: list[ipaddress.IPv4Address | ipaddress.IPv6Address] = [] - for info in infos: - raw_addr = info[4][0].split("%", 1)[0] # strip IPv6 zone id - try: - ips.append(ipaddress.ip_address(raw_addr)) - except ValueError: - continue - return ips - - -def _ipv4_in_cidr( - ip: ipaddress.IPv4Address, base: tuple[int, int, int, int], prefix: int -) -> bool: - ip_int = int(ip) - base_int = (base[0] << 24) | (base[1] << 16) | (base[2] << 8) | base[3] - mask = 0 if prefix == 0 else (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF - return (ip_int & mask) == (base_int & mask) - - -def _is_non_public(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: - # Align with codex-rs/network-proxy policy.rs (CGNAT, TEST-NET, etc.). - if isinstance(ip, ipaddress.IPv6Address): - mapped = ip.ipv4_mapped - if mapped is not None: - return _is_non_public(mapped) - return ( - ip.is_loopback - or ip.is_private - or ip.is_link_local - or ip.is_unspecified - or ip.is_multicast - or ip.is_reserved - ) - return ( - ip.is_private - or ip.is_loopback - or ip.is_link_local - or ip.is_reserved - or ip.is_unspecified - or ip.is_multicast - or ip == ipaddress.IPv4Address("255.255.255.255") - or _ipv4_in_cidr(ip, (0, 0, 0, 0), 8) - or _ipv4_in_cidr(ip, (100, 64, 0, 0), 10) - or _ipv4_in_cidr(ip, (192, 0, 0, 0), 24) - or _ipv4_in_cidr(ip, (192, 0, 2, 0), 24) - or _ipv4_in_cidr(ip, (198, 18, 0, 0), 15) - or _ipv4_in_cidr(ip, (198, 51, 100, 0), 24) - or _ipv4_in_cidr(ip, (203, 0, 113, 0), 24) - or _ipv4_in_cidr(ip, (240, 0, 0, 0), 4) - ) - - -_BLOCKED_HOSTNAMES = frozenset({"localhost", "metadata", "metadata.google.internal"}) - - -def _reject_ssrf_target(host: str) -> str | None: - """Return an error message if ``host`` resolves to a non-public address, else None. - - Blocks direct IP-literal access and DNS names that resolve to loopback, - private, link-local (e.g. the ``169.254.169.254`` cloud metadata service), - or other non-routable ranges. This runs both before the initial request - and before following any redirect. - """ - host = host.rstrip(".").lower() - if ( - host in _BLOCKED_HOSTNAMES - or host.endswith(".localhost") - or host.endswith(".local") - ): - return f"host {host!r} is blocked to prevent SSRF" - try: - ip = ipaddress.ip_address(host) - except ValueError: - pass - else: - if _is_non_public(ip): - return ( - f"host {host!r} is a non-public address ({ip}); blocked to prevent SSRF" - ) - return None - ips = _resolve_ips(host) - if not ips: - return f"could not resolve host {host!r}" - blocked = [ip for ip in ips if _is_non_public(ip)] - if blocked: - return f"host {host!r} resolves to a non-public address ({blocked[0]}); blocked to prevent SSRF" - return None - - -def _check_url_allowed(url: str, allowed: set[str]) -> str | None: - parsed = urlparse(url) - if parsed.scheme not in ("http", "https"): - return "web.run open: only http/https URLs are supported" - if parsed.username or parsed.password: - return "web.run open: URLs with embedded credentials are not allowed" - host = (parsed.hostname or "").lower().rstrip(".") - if not host: - return "web.run open: URL has no host" - if not _host_matches_allowlist(host, allowed): - return f"web.run open: host {host!r} is not in FORGE_WEB_ALLOW" - return _reject_ssrf_target(host) - - -class _AllowlistRedirectHandler(HTTPRedirectHandler): - """Re-validates every redirect hop against the same allowlist/SSRF checks. - - ``urllib`` follows redirects transparently by default, which would let an - allowlisted host bounce the request to an internal address (e.g. cloud - metadata) after the initial check already passed. Rejecting the redirect - here means the request to the disallowed target is never made. - """ - - def __init__(self, allowed: set[str]) -> None: - self._allowed = allowed - - def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: N802 (stdlib override) - error = _check_url_allowed(newurl, self._allowed) - if error is not None: - raise HTTPError(newurl, code, f"redirect blocked: {error}", headers, fp) - return super().redirect_request(req, fp, code, msg, headers, newurl) - - -def _fetch_url(url: str) -> ToolResult: - allowed = _allowed_hosts() - if not allowed: - return ToolResult( - content=( - "web.run open disabled: set FORGE_WEB_ALLOW (comma-separated hostnames) " - "or configure standalone search via FORGE_WEB_SEARCH=1 and provider credentials." - ), - is_error=True, - ) - url = url.strip() - if not url: - return ToolResult(content="web.run open: URL is empty", is_error=True) - error = _check_url_allowed(url, allowed) - if error is not None: - return ToolResult(content=error, is_error=True) - - opener = build_opener(_AllowlistRedirectHandler(allowed)) - req = Request(url, headers={"User-Agent": "pulsing-forge-web-run/1.0"}) - try: - with opener.open(req, timeout=_TIMEOUT_SECONDS) as resp: # noqa: S310 - max_bytes = _FETCH_CAP - data = resp.read(max_bytes + 1) - except HTTPError as exc: - reason = str(exc.reason or "") - if reason.startswith("redirect blocked:"): - return ToolResult(content=f"web.run open: {reason}", is_error=True) - return ToolResult( - content=f"web.run open: HTTP {exc.code} fetching {url}: {reason}", - is_error=True, - ) - except TimeoutError: - return ToolResult( - content=f"web.run open: timed out after {_TIMEOUT_SECONDS}s fetching {url}", - is_error=True, - ) - except URLError as exc: - if isinstance(exc.reason, TimeoutError): - return ToolResult( - content=f"web.run open: timed out after {_TIMEOUT_SECONDS}s fetching {url}", - is_error=True, - ) - return ToolResult( - content=f"web.run open: failed to fetch {url}: {exc.reason}", - is_error=True, - ) - except OSError as exc: - return ToolResult( - content=f"web.run open: failed to fetch {url}: {exc}", is_error=True - ) - if len(data) > max_bytes: - return ToolResult( - content=f"web.run open: response from {url} exceeds {max_bytes} byte cap", - is_error=True, - ) - try: - text = data.decode("utf-8") - except UnicodeDecodeError: - text = data.decode("utf-8", errors="replace") - return ToolResult(content=text) - - -def handle_web_run(*, ctx: ToolCallContext, **kwargs: Any) -> ToolResult: - # Accept Codex SearchCommands-shaped payload (flat or nested under "commands"). - payload = dict(kwargs) - if "commands" in payload and isinstance(payload["commands"], dict): - payload = dict(payload["commands"]) - - flat_url = payload.get("url") - if ( - flat_url - and payload.get("open") is None - and not payload.get("search_query") - and not payload.get("image_query") - and not (payload.get("find") or []) - ): - payload = {**payload, "open": [{"url": str(flat_url)}]} - - if payload.get("search_query") or payload.get("image_query"): - if os.environ.get("FORGE_WEB_SEARCH", "").strip() not in ("1", "true", "yes"): - return ToolResult( - content=( - "web.run search requires standalone search (Codex alpha/search). " - "Set FORGE_WEB_SEARCH=1 and wire provider auth in Craft, " - "or use hosted web_search on the model provider." - ), - is_error=True, - ) - return ToolResult( - content="standalone web search client not configured in Forge MVP", - is_error=True, - ) - - open_ops = payload.get("open") - if open_ops is not None: - if not isinstance(open_ops, list): - return ToolResult( - content="web.run open: expected a list of open commands", is_error=True - ) - if not open_ops: - return ToolResult( - content="web.run open: command list is empty", is_error=True - ) - first = open_ops[0] - if not isinstance(first, dict): - return ToolResult( - content="web.run open: each command must be an object with 'url' or 'ref_id'", - is_error=True, - ) - ref = str(first.get("ref_id") or first.get("url") or "").strip() - if not ref: - return ToolResult( - content="web.run open: missing 'url' or 'ref_id'", is_error=True - ) - if "://" in ref and not ( - ref.startswith("http://") or ref.startswith("https://") - ): - return ToolResult( - content="web.run open: only http/https URLs are supported", - is_error=True, - ) - if ref.startswith("http://") or ref.startswith("https://"): - return _fetch_url(ref) - return ToolResult( - content=( - f"web.run open: ref_id {ref!r} is not a literal URL " - "(turn refs require a search backend)" - ), - is_error=True, - ) - - find_ops = payload.get("find") or [] - if isinstance(find_ops, list) and find_ops: - op = find_ops[0] - if not isinstance(op, dict): - return ToolResult( - content="find op must be an object with 'ref_id' and 'pattern'", - is_error=True, - ) - return ToolResult( - content=json.dumps( - { - "status": "unsupported_in_mvp", - "ref_id": op.get("ref_id"), - "pattern": op.get("pattern"), - "hint": "find-in-page requires prior search results; use open with https URL", - }, - indent=2, - ), - is_error=True, - ) - - if not payload: - return ToolResult(content="empty web.run command", is_error=True) - return ToolResult( - content=json.dumps({"received": payload}, indent=2), - is_error=True, - ) diff --git a/python/pulsing/forge/extension/web_search/__init__.py b/python/pulsing/forge/extension/web_search/__init__.py deleted file mode 100644 index 296e5c927..000000000 --- a/python/pulsing/forge/extension/web_search/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -from pulsing.forge.extension.web_search.handlers import handle_web_search - -__all__ = ["handle_web_search"] diff --git a/python/pulsing/forge/extension/web_search/handlers.py b/python/pulsing/forge/extension/web_search/handlers.py deleted file mode 100644 index c9d8c267c..000000000 --- a/python/pulsing/forge/extension/web_search/handlers.py +++ /dev/null @@ -1,123 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Hosted ``web_search`` — Provider-side tool (Responses API), not sandbox execution.""" - -from __future__ import annotations - -import json -import re -from typing import Any - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.result import ToolResult - -# Codex registers web_search as a Responses API tool ({type: "web_search"}), not a -# sandbox function. Forge records calls; Craft enables provider execution. -_DEFERRED_MESSAGE = ( - "web_search is a hosted Provider tool (Responses API type=web_search). " - "Forge recorded this call only; enable web_search in Craft's model config so the " - "provider executes it. For client-side fetch/search, use web.run " - "(FORGE_WEB_ALLOW / FORGE_WEB_SEARCH)." -) -_NO_PROVIDER_AUTH_MESSAGE = ( - "web_search provider credentials are not configured. " - "Set the provider API key in Craft (e.g. OPENAI_API_KEY) and enable web_search " - "in the model tools list. Forge does not execute hosted search locally." -) -_AUTH_ERROR_HINT = re.compile( - r"(api[_ -]?key|authentication|unauthorized|invalid[_ -]?key|credentials?|" - r"permission denied|401|403|no key)", - re.IGNORECASE, -) - - -def _clean_query(query: Any) -> str: - return str(query).strip() if query else "" - - -def _clean_queries(queries: Any) -> list[str]: - if not isinstance(queries, list): - return [] - return [s for q in queries if (s := str(q).strip())] - - -def _json_result(payload: dict[str, Any], *, is_error: bool = False) -> ToolResult: - return ToolResult( - content=json.dumps(payload, indent=2, ensure_ascii=False), - structured=payload, - is_error=is_error, - ) - - -def _deferred_stub(arguments: dict[str, Any]) -> ToolResult: - structured = { - "kind": "hosted_web_search", - "status": "deferred", - "reason": "provider_not_configured", - "executed_by": "provider", - "arguments": arguments, - "message": _DEFERRED_MESSAGE, - } - return _json_result(structured) - - -def _format_hook_error(exc: BaseException) -> str: - text = str(exc).strip() or exc.__class__.__name__ - if _AUTH_ERROR_HINT.search(text): - return f"web_search provider auth missing: {text}. {_NO_PROVIDER_AUTH_MESSAGE}" - return f"web_search provider hook failed: {text}" - - -def _normalize_hook_result(out: Any, *, arguments: dict[str, Any]) -> ToolResult: - if out is None: - return _deferred_stub(arguments) - if isinstance(out, ToolResult): - return out - if not isinstance(out, dict): - return ToolResult(content=str(out)) - - if out.get("is_error") or out.get("status") in {"error", "failed"}: - message = str( - out.get("message") or out.get("error") or out.get("content") or out - ) - if _AUTH_ERROR_HINT.search(message): - message = f"web_search provider auth missing: {message}. {_NO_PROVIDER_AUTH_MESSAGE}" - return _json_result({**out, "message": message}, is_error=True) - - if out.get("status") == "deferred": - return _deferred_stub(arguments) - - return _json_result(out) - - -def handle_web_search( - *, - ctx: ToolCallContext, - query: Any = "", - queries: Any = None, - **kwargs: Any, -) -> ToolResult: - """Forge records the call; actual search runs on the LLM provider when enabled in Craft.""" - query = _clean_query(query) - queries = _clean_queries(queries) - if not query and not queries: - return ToolResult( - content="web_search requires a non-empty 'query' or 'queries' argument", - is_error=True, - ) - - arguments: dict[str, Any] = dict(kwargs) - if query: - arguments["query"] = query - if queries: - arguments["queries"] = queries - - hook = getattr(ctx.session, "hosted_web_search", None) - if not callable(hook): - return _deferred_stub(arguments) - - try: - out = hook(arguments) - except Exception as exc: - return ToolResult(content=_format_hook_error(exc), is_error=True) - - return _normalize_hook_result(out, arguments=arguments) diff --git a/python/pulsing/forge/grep_worker.py b/python/pulsing/forge/grep_worker.py deleted file mode 100644 index f5ee261f0..000000000 --- a/python/pulsing/forge/grep_worker.py +++ /dev/null @@ -1,70 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Spawn-safe grep scan worker (stdlib only — no pulsing.forge package import).""" - -from __future__ import annotations - -import fnmatch -import re -from pathlib import Path -from typing import Any - -GREP_MAX = 200 - - -def scan( - root: Path, - pattern: str, - glob: str | None, - boundary_s: str | None, -) -> tuple[list[str], int]: - boundary = Path(boundary_s) if boundary_s else None - cre = re.compile(pattern) - hits: list[str] = [] - total = 0 - - def within_boundary(fp: Path) -> bool: - if boundary is None: - return True - try: - fp.resolve().relative_to(boundary.resolve()) - except ValueError: - return False - return True - - def consider_file(fp: Path) -> None: - nonlocal total - if not within_boundary(fp): - return - if glob and not fnmatch.fnmatch(fp.name, glob): - return - try: - text = fp.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): - return - for i, line in enumerate(text.splitlines(), 1): - if cre.search(line): - total += 1 - if len(hits) < GREP_MAX: - hits.append(f"{fp}:{i}:{line[:500]}") - - if root.is_file(): - consider_file(root) - else: - for fp in root.rglob("*"): - if fp.is_file(): - consider_file(fp) - return hits, total - - -def worker( - root_s: str, - pattern: str, - glob: str | None, - boundary_s: str | None, - q: Any, -) -> None: - try: - hits, total = scan(Path(root_s), pattern, glob, boundary_s) - q.put(("ok", hits, total)) - except Exception as exc: - q.put(("err", str(exc))) diff --git a/python/pulsing/forge/handlers.py b/python/pulsing/forge/handlers.py deleted file mode 100644 index 16c6f5f45..000000000 --- a/python/pulsing/forge/handlers.py +++ /dev/null @@ -1,787 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Built-in tool implementations for pulsing.forge.""" - -from __future__ import annotations - -import base64 -import errno -import fnmatch -import json -import multiprocessing -import os -import re -import shutil -import subprocess -import tempfile -from pathlib import Path -from typing import Any - -from pulsing.forge.context import ToolCallContext, resolve_within_cwd -from pulsing.forge.exec_output import SHELL_MAX_BYTES, shell_timeout_ms -from pulsing.forge.patch_invocation import ( - MaybeApplyPatch, - ParsedPatch, - apply_parsed_patch, - maybe_parse_apply_patch, -) -from pulsing.forge.result import ToolResult -from pulsing.forge.sandbox import build_bash_exec, normalize_policy -from pulsing.forge.discovery.catalog import ToolCatalogRefreshError -from pulsing.forge.discovery.entries import ( - TOOL_SEARCH_MAX_QUERY_CHARS, - normalize_tool_search_limit, -) -from pulsing.forge.discovery.discoverable import ( - DiscoverablePlugin, - DiscoverableToolAction, - DiscoverableToolType, - build_plugin_install_elicitation_meta, -) -from pulsing.forge.discovery.install import execute_plugin_install -from pulsing.forge.grep_worker import GREP_MAX as _GREP_MAX -from pulsing.forge.grep_worker import worker as _grep_scan_worker -from pulsing.forge.session import UpdatePlanArgs -from pulsing.forge.session_input import args_to_payload, validate_request_user_input - -_READ_CAP = 2 * 1024 * 1024 -_GREP_PATTERN_MAX = 1000 -_GREP_TIMEOUT_SEC = 5.0 -_GLOB_MAX = 500 -_VIEW_IMAGE_CAP = 8 * 1024 * 1024 -_HIGH_DETAIL_MAX_PX = 2048 - -# Must stay byte-for-byte identical to NEW_CONTEXT_MESSAGE in -# crates/pulsing-forge/src/handlers/session.rs — this pure-Python fallback path -# does not link against that crate, so the string is duplicated rather than shared. -NEW_CONTEXT_MESSAGE = ( - "A new context window will start without summarizing conversation history." -) -# Must stay byte-for-byte identical to PLAN_UPDATED in -# crates/pulsing-forge/src/handlers/plan.rs — this pure-Python fallback path -# does not link against that crate, so the string is duplicated rather than shared. -PLAN_UPDATED = "Plan updated" - -_CODEX_SHELL = frozenset({"shell_command", "exec_command", "write_stdin"}) -_CODEX_FILE = frozenset({"apply_patch", "view_image"}) -_CODEX_SESSION = frozenset( - {"update_plan", "new_context", "get_context_remaining", "request_user_input"} -) -_CODEX_DISCOVERY = frozenset( - {"tool_search", "list_available_plugins_to_install", "request_plugin_install"} -) -_CODEX_CODE_MODE = frozenset({"exec", "wait"}) -from pulsing.forge.extension.protocol import EXTENSION_TOOL_NAMES as _CODEX_EXTENSION - -_CLAUDE_STYLE = frozenset({"Read", "Glob", "Grep", "Edit", "Write", "Bash"}) - -_ALL = ( - _CODEX_SHELL - | _CODEX_FILE - | _CODEX_SESSION - | _CODEX_DISCOVERY - | _CODEX_CODE_MODE - | _CODEX_EXTENSION - | _CLAUDE_STYLE -) - - -def dispatch_tool( - name: str, - arguments: dict[str, Any], - *, - ctx: ToolCallContext, -) -> ToolResult: - if name in _CODEX_EXTENSION: - from pulsing.forge.extension.handlers import dispatch_extension_tool - - return dispatch_extension_tool(name, arguments, ctx=ctx) - if name not in _ALL: - return ToolResult(content=f"Unknown tool: {name}", is_error=True) - impl = { - "shell_command": _shell_command, - "exec_command": _exec_command, - "write_stdin": _write_stdin, - "apply_patch": _apply_patch, - "view_image": _view_image, - "update_plan": _update_plan, - "new_context": _new_context, - "get_context_remaining": _get_context_remaining, - "request_user_input": _request_user_input, - "tool_search": _tool_search, - "list_available_plugins_to_install": _list_available_plugins, - "request_plugin_install": _request_plugin_install, - "exec": _exec, - "wait": _wait, - "Read": _read, - "Glob": _glob, - "Grep": _grep, - "Edit": _edit, - "Write": _write, - "Bash": _shell_command, - }[name] - kwargs = dict(arguments) - kwargs.setdefault("cwd", str(ctx.cwd)) - kwargs.setdefault("sandbox_policy", ctx.sandbox_policy) - kwargs.setdefault("dangerously_disable_sandbox", ctx.dangerously_disable_sandbox) - return impl(ctx=ctx, **kwargs) - - -def _resolve_path(ctx: ToolCallContext, path: str) -> Path: - p = Path(path) - return p if p.is_absolute() else ctx.cwd / p - - -def _read_os_error(path: Path, exc: OSError) -> str: - """Mirror `read_error` in crates/pulsing-forge/src/handlers/read.rs.""" - if exc.errno == errno.ENOENT: - reason = "No such file" - elif exc.errno in (errno.EACCES, errno.EPERM): - reason = "Permission denied" - else: - reason = str(exc) - return f"{reason}: {path}" - - -def _read( - *, - ctx: ToolCallContext, - file_path: str, - offset: int | None = None, - limit: int | None = None, - **_: Any, -) -> ToolResult: - path = _resolve_path(ctx, file_path) - if path.is_dir(): - return ToolResult( - content=f"Path is a directory, not a file: {path}", is_error=True - ) - if offset is not None or limit is not None: - return _read_range(path, max(offset or 1, 1), limit) - try: - data = path.read_bytes() - except OSError as e: - return ToolResult(content=_read_os_error(path, e), is_error=True) - if len(data) > _READ_CAP: - return ToolResult( - content=( - f"File too large for Read tool ({len(data)} bytes > {_READ_CAP} cap); " - "retry with offset/limit to page through it." - ), - is_error=True, - ) - try: - return ToolResult(content=data.decode("utf-8")) - except UnicodeDecodeError: - return ToolResult(content=f"Not valid UTF-8: {path}", is_error=True) - - -def _read_range(path: Path, start_line: int, limit: int | None) -> ToolResult: - """Streams `path` line by line so a paginated read never needs the whole file in memory.""" - end_line = start_line + limit if limit is not None else None - out: list[str] = [] - size = 0 - try: - with path.open("r", encoding="utf-8") as fh: - for lineno, line in enumerate(fh, start=1): - if lineno < start_line: - continue - if end_line is not None and lineno >= end_line: - break - size += len(line) - if size > _READ_CAP: - return ToolResult( - content="Requested range too large for Read tool; use a smaller limit.", - is_error=True, - ) - out.append(line) - except UnicodeDecodeError: - return ToolResult(content=f"Not valid UTF-8: {path}", is_error=True) - except OSError as e: - return ToolResult(content=str(e), is_error=True) - return ToolResult(content="".join(out)) - - -def _glob( - *, ctx: ToolCallContext, pattern: str, path: str | None = None, **_: Any -) -> ToolResult: - if Path(pattern).is_absolute(): - return ToolResult( - content="pattern must be relative to path/cwd; absolute glob patterns are not supported", - is_error=True, - ) - base = _resolve_path(ctx, path) if path else ctx.cwd - if not base.exists(): - return ToolResult(content=f"path does not exist: {base}", is_error=True) - try: - matches = sorted(str(p) for p in base.glob(pattern)) - except (OSError, NotImplementedError, ValueError) as e: - return ToolResult( - content=f"invalid glob pattern {pattern!r}: {e}", is_error=True - ) - if not matches: - return ToolResult(content="(no matches)") - total = len(matches) - truncated = matches[:_GLOB_MAX] - if total > _GLOB_MAX: - truncated.append(f"… truncated: showing {_GLOB_MAX} of {total} matches …") - return ToolResult(content="\n".join(truncated)) - - -def _grep_boundary(ctx: ToolCallContext, root: Path) -> Path | None: - """When search root is under cwd, skip files that resolve outside cwd.""" - try: - root.resolve().relative_to(ctx.cwd.resolve()) - except ValueError: - return None - return ctx.cwd - - -def _grep( - *, - ctx: ToolCallContext, - pattern: str, - path: str | None = None, - glob: str | None = None, - **_: Any, -) -> ToolResult: - if len(pattern) > _GREP_PATTERN_MAX: - return ToolResult( - content=f"Pattern too long ({len(pattern)} > {_GREP_PATTERN_MAX} chars); simplify the regex", - is_error=True, - ) - root = _resolve_path(ctx, path) if path else ctx.cwd - if not root.exists(): - return ToolResult(content="path not found", is_error=True) - try: - re.compile(pattern) - except re.error as e: - return ToolResult(content=f"Invalid regex: {e}", is_error=True) - - # `re` has no backtracking budget; run the scan in a child process so a - # pathological pattern cannot block the tool runtime indefinitely. - boundary = _grep_boundary(ctx, root) - ctx_mp = multiprocessing.get_context("spawn") - q: Any = ctx_mp.Queue() - proc = ctx_mp.Process( - target=_grep_scan_worker, - args=(str(root), pattern, glob, str(boundary) if boundary else None, q), - ) - proc.start() - proc.join(timeout=_GREP_TIMEOUT_SEC) - if proc.is_alive(): - proc.terminate() - proc.join(timeout=1.0) - return ToolResult( - content=( - f"grep timed out after {_GREP_TIMEOUT_SEC:.0f}s " - "(pattern may cause catastrophic regex backtracking); simplify it" - ), - is_error=True, - ) - if q.empty(): - return ToolResult(content="grep failed: no result from worker", is_error=True) - status, *payload = q.get_nowait() - if status == "err": - return ToolResult(content=f"grep failed: {payload[0]}", is_error=True) - hits, total = payload - extra = ( - f"\n… truncated: showing {_GREP_MAX} of {total} matches …" - if total > _GREP_MAX - else "" - ) - return ToolResult(content="\n".join(hits) + extra if hits else "(no matches)") - - -def _atomic_write_text(path: Path, content: str, *, encoding: str = "utf-8") -> None: - """Write `content` via a sibling temp file + rename. - - A plain `write_text()` truncates the target before writing, so a failure - mid-write (disk full, killed process) leaves a corrupted file. Writing to - a temp file first and renaming it into place keeps the replace atomic on - POSIX and Windows (`os.replace`), and `path` unchanged on any failure. - """ - fd, tmp_name = tempfile.mkstemp( - dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" - ) - try: - with os.fdopen(fd, "w", encoding=encoding) as f: - f.write(content) - f.flush() - os.fsync(f.fileno()) - try: - shutil.copymode(path, tmp_name) - except OSError: - pass - os.replace(tmp_name, path) - except BaseException: - try: - os.unlink(tmp_name) - except OSError: - pass - raise - - -def _edit( - *, - ctx: ToolCallContext, - file_path: str, - old_string: str, - new_string: str, - **_: Any, -) -> ToolResult: - try: - fp = _resolve_write_target(ctx, file_path) - except ValueError as e: - return ToolResult(content=str(e), is_error=True) - if not fp.exists(): - return ToolResult(content=f"file not found: {fp}", is_error=True) - if not fp.is_file(): - return ToolResult(content=f"not a file: {fp}", is_error=True) - try: - text = fp.read_text(encoding="utf-8") - except OSError as e: - return ToolResult(content=f"failed to read {fp}: {e}", is_error=True) - count = text.count(old_string) - if count == 0: - return ToolResult(content=f"old_string not found in {fp}", is_error=True) - if count > 1: - return ToolResult( - content=f"old_string is not unique in {fp} ({count} occurrences); refusing ambiguous edit", - is_error=True, - ) - try: - _atomic_write_text(fp, text.replace(old_string, new_string, 1)) - except OSError as e: - return ToolResult(content=f"failed to write {fp}: {e}", is_error=True) - return ToolResult(content="ok") - - -def _resolve_shell_workdir( - ctx: ToolCallContext, - workdir: str | None, - cwd: str | None, -) -> Path: - raw = workdir or cwd - if raw is None: - return ctx.cwd - return resolve_within_cwd(ctx.cwd, raw) - - -def _resolve_write_target(ctx: ToolCallContext, file_path: str) -> Path: - """Resolve `file_path` against cwd, rejecting any target outside of it. - - `Write` runs with no OS-level sandbox (unlike apply_patch/Bash), so this - boundary check is the only thing standing between the model and the rest - of the filesystem. - """ - return resolve_within_cwd(ctx.cwd, file_path) - - -def _write( - *, ctx: ToolCallContext, file_path: str, content: str, **_: Any -) -> ToolResult: - try: - fp = _resolve_write_target(ctx, file_path) - except ValueError as e: - return ToolResult(content=str(e), is_error=True) - existed = fp.exists() - try: - fp.parent.mkdir(parents=True, exist_ok=True) - except OSError as e: - return ToolResult( - content=f"failed to create parent directory {fp.parent}: {e}", is_error=True - ) - try: - _atomic_write_text(fp, content) - except OSError as e: - return ToolResult(content=f"failed to write {fp}: {e}", is_error=True) - return ToolResult(content="overwritten" if existed else "created") - - -def _shell_command( - *, - ctx: ToolCallContext, - cmd: str | None = None, - command: str | None = None, - workdir: str | None = None, - cwd: str | None = None, - timeout_sec: int | None = None, - timeout_ms: int | None = None, - login: bool = False, - sandbox_permissions: str | None = None, - sandbox_policy: str = "off", - dangerously_disable_sandbox: bool = False, - **_: Any, -) -> ToolResult: - shell_cmd = cmd or command or "" - if not shell_cmd: - return ToolResult(content="missing cmd/command", is_error=True) - try: - run_cwd = str(_resolve_shell_workdir(ctx, workdir, cwd)) - except ValueError as e: - return ToolResult(content=str(e), is_error=True) - args = { - "timeout_ms": timeout_ms, - "timeout_sec": timeout_sec, - "sandbox_permissions": sandbox_permissions, - "dangerously_disable_sandbox": dangerously_disable_sandbox, - } - timeout = shell_timeout_ms(args) / 1000.0 - policy = _effective_shell_policy(ctx, args, sandbox_policy) - - argv, extra_env, label = build_bash_exec( - shell_cmd, - cwd=run_cwd, - policy=normalize_policy(policy), - dangerously_disable_sandbox=dangerously_disable_sandbox, - timeout=int(timeout), - login=login, - ) - - kind, parsed = maybe_parse_apply_patch(argv) - if kind is MaybeApplyPatch.BODY and parsed is not None: - try: - return ToolResult(content=apply_parsed_patch(parsed, Path(run_cwd))) - except (OSError, ValueError) as e: - return ToolResult(content=str(e), is_error=True) - if kind is MaybeApplyPatch.IMPLICIT: - return ToolResult( - content="patch detected without explicit apply_patch invocation; use apply_patch tool", - is_error=True, - ) - - run_kw: dict[str, Any] = { - "args": argv, - "capture_output": True, - "text": True, - "timeout": timeout, - "cwd": run_cwd, - } - if extra_env is not None: - run_kw["env"] = extra_env - try: - proc = subprocess.run(**run_kw) - except subprocess.TimeoutExpired: - ms = int(timeout * 1000) - return ToolResult(content=f"timed out after {ms}ms", is_error=True) - except OSError as e: - return ToolResult(content=str(e), is_error=True) - out = (proc.stdout or "") + (proc.stderr or "") - if len(out) > SHELL_MAX_BYTES: - out = out[:SHELL_MAX_BYTES] + "\n… truncated …" - tail = f"\nexit={proc.returncode}\n[{label}]" - return ToolResult(content=out + tail, is_error=proc.returncode != 0) - - -def _exec_command(*, ctx: ToolCallContext, **kwargs: Any) -> ToolResult: - return ctx.exec.exec_command(ctx, kwargs) - - -def _write_stdin(*, ctx: ToolCallContext, **kwargs: Any) -> ToolResult: - return ctx.exec.write_stdin(ctx, kwargs) - - -def _effective_shell_policy( - ctx: ToolCallContext, args: dict[str, Any], fallback: str -) -> str: - if args.get("dangerously_disable_sandbox", ctx.dangerously_disable_sandbox): - return "off" - perm = args.get("sandbox_permissions") - if perm == "require_escalated": - return "off" - if perm == "with_additional_permissions": - return "restricted" - return fallback or ctx.sandbox_policy - - -def _apply_patch( - *, - ctx: ToolCallContext, - patch: str | None = None, - input: str | None = None, - command: list[str] | None = None, - **kwargs: Any, -) -> ToolResult: - if command: - argv = [str(x) for x in command] - kind, parsed = maybe_parse_apply_patch(argv) - if kind is MaybeApplyPatch.BODY and parsed is not None: - try: - return ToolResult(content=apply_parsed_patch(parsed, ctx.cwd)) - except (OSError, ValueError) as e: - return ToolResult(content=str(e), is_error=True) - if kind is MaybeApplyPatch.IMPLICIT: - return ToolResult( - content="patch detected without explicit apply_patch invocation; use apply_patch tool", - is_error=True, - ) - return ToolResult(content="not an apply_patch command", is_error=True) - - raw = patch or input or kwargs.get("arguments") - if isinstance(raw, dict): - raw = raw.get("patch") or raw.get("input") - if not raw or not isinstance(raw, str): - return ToolResult(content="apply_patch expects a patch string", is_error=True) - try: - summary = apply_parsed_patch(ParsedPatch(patch=raw), ctx.cwd) - except (OSError, ValueError) as e: - return ToolResult(content=str(e), is_error=True) - return ToolResult(content=summary) - - -def _resolve_view_image_target(ctx: ToolCallContext, path: str) -> Path: - """Resolve `path` against cwd, rejecting any target outside of it.""" - target = _resolve_path(ctx, path).resolve() - root = ctx.cwd - if target != root and root not in target.parents: - raise ValueError( - f"refusing to read outside working directory: {target} (cwd: {root})" - ) - return target - - -def _sniff_image_mime(data: bytes) -> str | None: - if data.startswith(b"\x89PNG\r\n\x1a\n"): - return "image/png" - if len(data) >= 3 and data[:3] == b"\xff\xd8\xff": - return "image/jpeg" - if data[:6] in (b"GIF87a", b"GIF89a"): - return "image/gif" - if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": - return "image/webp" - return None - - -def _view_image( - *, ctx: ToolCallContext, path: str, detail: str = "high", **_: Any -) -> ToolResult: - if detail not in {"high", "original"}: - return ToolResult( - content=( - f"view_image.detail only supports `high` or `original`; omit `detail` for default " - f"high resized behavior, got `{detail}`" - ), - is_error=True, - ) - try: - abs_path = _resolve_view_image_target(ctx, path) - except ValueError as e: - return ToolResult(content=str(e), is_error=True) - if not abs_path.is_file(): - return ToolResult( - content=f"image path `{abs_path}` is not a file", is_error=True - ) - try: - data = abs_path.read_bytes() - except OSError as e: - return ToolResult( - content=f"unable to read image at `{abs_path}`: {e}", is_error=True - ) - if len(data) > _VIEW_IMAGE_CAP: - return ToolResult( - content=( - f"Image too large for view_image: {len(data)} bytes exceeds the " - f"{_VIEW_IMAGE_CAP} byte cap." - ), - is_error=True, - ) - - mime = _sniff_image_mime(data) - if mime is None: - return ToolResult( - content="not a recognized image format (png/jpeg/gif/webp)", - is_error=True, - ) - out_bytes = data - if detail == "high": - out_bytes, mime = _maybe_resize_image(data, mime) - - b64 = base64.standard_b64encode(out_bytes).decode("ascii") - data_url = f"data:{mime};base64,{b64}" - structured = { - "content_items": [ - {"type": "input_image", "image_url": data_url, "detail": detail}, - ], - "path": str(abs_path), - "bytes": len(out_bytes), - } - return ToolResult( - content=f"Attached image {abs_path} (detail={detail}, {len(out_bytes)} bytes)", - structured=structured, - ) - - -def _maybe_resize_image(data: bytes, mime: str) -> tuple[bytes, str]: - try: - from PIL import Image - import io - except ImportError: - return data, mime - img = Image.open(io.BytesIO(data)) - w, h = img.size - if max(w, h) <= _HIGH_DETAIL_MAX_PX: - return data, mime - scale = _HIGH_DETAIL_MAX_PX / max(w, h) - nw = max(1, int(w * scale)) - nh = max(1, int(h * scale)) - resized = img.resize((nw, nh), Image.Resampling.LANCZOS) - buf = io.BytesIO() - fmt = { - "image/png": "PNG", - "image/jpeg": "JPEG", - "image/gif": "GIF", - "image/webp": "WEBP", - }.get(mime, "PNG") - resized.save(buf, format=fmt) - return buf.getvalue(), mime - - -def _update_plan(*, ctx: ToolCallContext, **raw: Any) -> ToolResult: - # dispatch_tool injects cwd/sandbox fields; only validate model-visible args. - injected = frozenset({"cwd", "sandbox_policy", "dangerously_disable_sandbox"}) - tool_args = {k: v for k, v in raw.items() if k not in injected} - try: - args = UpdatePlanArgs.from_dict(tool_args) - except (TypeError, ValueError) as e: - return ToolResult( - content=f"failed to parse update_plan arguments: {e}", is_error=True - ) - ctx.session_nonnull.update_plan(args) - return ToolResult(content=PLAN_UPDATED) - - -def _new_context(*, ctx: ToolCallContext, **_: Any) -> ToolResult: - try: - ctx.session_nonnull.request_new_context() - except RuntimeError as e: - return ToolResult(content=str(e), is_error=True) - return ToolResult(content=NEW_CONTEXT_MESSAGE) - - -def _get_context_remaining(*, ctx: ToolCallContext, **_: Any) -> ToolResult: - remaining = ctx.session_nonnull.tokens_remaining() - payload = ( - {"tokens_remaining": remaining, "status": "ok"} - if remaining is not None - else {"tokens_remaining": None, "status": "unknown"} - ) - return ToolResult(content=json.dumps(payload, indent=2)) - - -def _request_user_input(*, ctx: ToolCallContext, **raw: Any) -> ToolResult: - try: - validated = validate_request_user_input(raw) - response = ctx.session_nonnull.request_user_input(args_to_payload(validated)) - except (RuntimeError, ValueError) as e: - return ToolResult(content=str(e), is_error=True) - return ToolResult(content=json.dumps(response, indent=2)) - - -def _tool_search( - *, - ctx: ToolCallContext, - query: str | None = None, - limit: int | None = None, - **_: Any, -) -> ToolResult: - q = (query or "").strip() - if not q: - return ToolResult(content="tool_search requires non-empty query", is_error=True) - q = q[:TOOL_SEARCH_MAX_QUERY_CHARS] - hits = ctx.tool_catalog.search(q, normalize_tool_search_limit(limit)) - payload = {"tools": [h.to_loadable_json() for h in hits]} - return ToolResult(content=json.dumps(payload, indent=2)) - - -def _list_available_plugins(*, ctx: ToolCallContext, **_: Any) -> ToolResult: - try: - ctx.tool_catalog.refresh_from_codex() - except ToolCatalogRefreshError as e: - return ToolResult(content=str(e), is_error=True) - payload = {"tools": ctx.tool_catalog.list_installable_entries()} - return ToolResult(content=json.dumps(payload, indent=2)) - - -def _request_plugin_install(*, ctx: ToolCallContext, **raw: Any) -> ToolResult: - tool_id = str(raw.get("tool_id") or raw.get("plugin_id") or "").strip() - if not tool_id: - return ToolResult( - content="request_plugin_install requires tool_id", is_error=True - ) - tool_type_raw = str(raw.get("tool_type") or "plugin") - action_type_raw = str(raw.get("action_type") or "install") - suggest_reason = str(raw.get("suggest_reason") or raw.get("reason") or "").strip() - if not suggest_reason: - return ToolResult( - content="request_plugin_install requires non-empty suggest_reason", - is_error=True, - ) - if action_type_raw != DiscoverableToolAction.INSTALL.value: - return ToolResult( - content='plugin install requests currently support only action_type="install"', - is_error=True, - ) - try: - tool_type = DiscoverableToolType(tool_type_raw) - action_type = DiscoverableToolAction(action_type_raw) - except ValueError: - return ToolResult( - content=f"invalid tool_type or action_type: {tool_type_raw!r}, {action_type_raw!r}", - is_error=True, - ) - - try: - ctx.tool_catalog.refresh_from_codex() - except ToolCatalogRefreshError as e: - return ToolResult(content=str(e), is_error=True) - tool = ctx.tool_catalog.find_discoverable(tool_type, tool_id) - if tool is None: - return ToolResult(content=f"unknown plugin {tool_id!r}", is_error=True) - - elicitation: dict[str, Any] = { - "tool_type": tool_type.value, - "action_type": action_type.value, - "tool_id": tool_id, - "tool_name": tool.name, - "suggest_reason": suggest_reason, - } - if isinstance(tool, DiscoverablePlugin): - elicitation["meta"] = build_plugin_install_elicitation_meta( - tool, suggest_reason=suggest_reason, action_type=action_type - ) - - try: - confirmed = ctx.session_nonnull.request_plugin_install(elicitation) - except RuntimeError as e: - return ToolResult(content=str(e), is_error=True) - if confirmed is not True: - confirmed = False - - try: - outcome = execute_plugin_install( - tool_type=tool_type, - action_type=action_type, - tool_id=tool_id, - suggest_reason=suggest_reason, - user_confirmed=confirmed, - ) - except ValueError as e: - return ToolResult(content=str(e), is_error=True) - - if outcome.deferred_tools: - for entry in outcome.deferred_tools: - ctx.tool_catalog.register_deferred(entry) - ctx.tool_catalog.refresh_from_codex() - return ToolResult(content=json.dumps(outcome.to_result_json(), indent=2)) - - -def _exec(*, ctx: ToolCallContext, **kwargs: Any) -> ToolResult: - from pulsing.forge.code_mode.handlers import handle_exec - - return handle_exec(ctx=ctx, **kwargs) - - -def _wait(*, ctx: ToolCallContext, **kwargs: Any) -> ToolResult: - from pulsing.forge.code_mode.handlers import handle_wait - - return handle_wait(ctx=ctx, **kwargs) diff --git a/python/pulsing/forge/host/__init__.py b/python/pulsing/forge/host/__init__.py deleted file mode 100644 index c5f7447f9..000000000 --- a/python/pulsing/forge/host/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""High-level Forge client facade plus explicit legacy host adapters.""" - -from pulsing.forge.host.agent import ForgeAgent, DEFAULT_TOOL_NAMES -from pulsing.forge.host.legacy_agent import LegacyPythonForgeAgent -from pulsing.forge.host.cli_events import CliEventSink -from pulsing.forge.host.llm import ( - LLMClient, - LLMMessage, - LLMUsage, - RUST_LLM_AVAILABLE, - create_llm_client, - default_model, - llm_runtime_options, -) - -__all__ = [ - "CliEventSink", - "DEFAULT_TOOL_NAMES", - "ForgeAgent", - "LLMClient", - "LLMMessage", - "LLMUsage", - "LegacyPythonForgeAgent", - "RUST_LLM_AVAILABLE", - "create_llm_client", - "default_model", - "llm_runtime_options", -] diff --git a/python/pulsing/forge/host/agent.py b/python/pulsing/forge/host/agent.py deleted file mode 100644 index 7c45f4fc0..000000000 --- a/python/pulsing/forge/host/agent.py +++ /dev/null @@ -1,196 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Python client projection for the canonical Rust Forge Agent.""" - -from __future__ import annotations - -import asyncio -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from pulsing.forge.client import ForgeClient -from pulsing.forge.host.cli_events import CliEventSink -from pulsing.forge.result import ToolResult - -DEFAULT_TOOL_NAMES: tuple[str, ...] = ( - "update_plan", - "Glob", - "Read", - "Grep", - "shell_command", -) - -_DEFAULT_SYSTEM = """\ -You are a capable coding agent with filesystem and shell tools. -Use tools to inspect the workspace before answering. -When multi-step work is needed, call update_plan first. -Be concise in final replies.\ -""" - - -@dataclass -class ForgeAgent: - """Client facade; Rust owns the Session, Agent loop, tools, and cancellation.""" - - cwd: Path | str = "." - provider: str = "demo" - model: str = "demo" - api_key: str | None = None - base_url: str | None = None - max_tokens: int = 8192 - max_turns: int = 20 - tool_names: tuple[str, ...] = DEFAULT_TOOL_NAMES - system_prompt: str = _DEFAULT_SYSTEM - sandbox_policy: str = "off" - auto_approve: bool = True - events: CliEventSink = field(default_factory=CliEventSink) - _client: ForgeClient | None = field(default=None, init=False, repr=False) - _session_id: str | None = field(default=None, init=False, repr=False) - _active_turn_id: str | None = field(default=None, init=False, repr=False) - _messages: list[dict[str, Any]] = field( - default_factory=list, init=False, repr=False - ) - - def __post_init__(self) -> None: - self.cwd = Path(self.cwd).resolve() - if self.api_key is not None or self.base_url is not None: - raise ValueError( - "canonical ForgeAgent provider credentials are Rust process " - "configuration; use OPENAI_API_KEY/OPENAI_BASE_URL or " - "ANTHROPIC_API_KEY/ANTHROPIC_BASE_URL" - ) - - def _ensure_client(self) -> ForgeClient: - if self._client is None: - self._client = ForgeClient() - return self._client - - def _ensure_session(self) -> str: - if self._session_id is None: - self._session_id = self._ensure_client().create_session( - cwd=str(self.cwd), - provider=self.provider, - model=self.model, - max_tokens=self.max_tokens, - max_turns=self.max_turns, - sandbox=self.sandbox_policy, - auto_approve=self.auto_approve, - tool_names=self.tool_names, - system_prompt=self.system_prompt, - ) - return self._session_id - - @property - def messages(self) -> list[dict[str, Any]]: - """Client-side conversation projection; never used to drive execution.""" - return list(self._messages) - - @property - def session(self) -> dict[str, Any]: - """Read-only Rust Session snapshot.""" - return self._ensure_client().snapshot(self._ensure_session()) - - async def run(self, prompt: str) -> str: - session_id = self._ensure_session() - self._messages.append({"role": "user", "content": prompt}) - receipt = await asyncio.to_thread( - self._ensure_client().start_turn, - session_id, - prompt, - ) - turn_id = str(receipt["turn_id"]) - self._active_turn_id = turn_id - try: - outcome = await asyncio.to_thread( - self._ensure_client().wait_turn, - session_id, - turn_id, - int(receipt["accepted_seq"]), - ) - finally: - self._active_turn_id = None - - self._project_events(list(outcome.get("events") or [])) - terminal = dict(outcome.get("terminal") or {}) - status = terminal.get("status") - if status == "completed": - return str(terminal.get("text") or "") - if status == "cancelled": - raise asyncio.CancelledError("Forge turn cancelled") - message = str(terminal.get("message") or "Forge turn failed") - raise RuntimeError(message) - - async def cancel(self) -> bool: - if self._session_id is None or self._active_turn_id is None: - return False - await asyncio.to_thread( - self._ensure_client().cancel_turn, - self._session_id, - self._active_turn_id, - ) - return True - - def close(self) -> None: - if ( - self._client is not None - and self._session_id is not None - and self._active_turn_id is not None - ): - try: - self._client.cancel_turn(self._session_id, self._active_turn_id) - except RuntimeError: - pass - self._active_turn_id = None - self._session_id = None - self._client = None - - def _project_events(self, events: list[dict[str, Any]]) -> None: - for event in events: - kind = str(event.get("kind") or "") - payload = dict(event.get("payload") or {}) - if kind == "turn_output_delta": - self.events.on_assistant_delta(str(payload.get("delta") or "")) - elif kind == "tool_started": - name = str(payload.get("name") or "tool") - self.events.on_tool_begin(name, {}) - self._messages.append( - { - "role": "assistant", - "content": [{"type": "tool_use", "name": name}], - } - ) - elif kind == "tool_completed": - name = str(payload.get("name") or "tool") - result = ToolResult( - content=str(payload.get("summary") or ""), - is_error=not bool(payload.get("ok")), - ) - self.events.on_tool_end(name, result) - self._messages.append( - { - "role": "user", - "content": [ - { - "type": "tool_result", - "name": name, - "content": result.content, - "is_error": result.is_error, - } - ], - } - ) - elif kind == "tool_cancelled": - name = str(payload.get("name") or "tool") - self.events.on_tool_end( - name, - ToolResult(content="cancelled", is_error=True), - ) - elif kind == "turn_completed": - text = str(payload.get("text") or "") - self._messages.append({"role": "assistant", "content": text}) - self.events.on_assistant_end() - elif kind == "turn_failed": - self.events.on_error(str(payload.get("message") or "Forge turn failed")) - - -__all__ = ["DEFAULT_TOOL_NAMES", "ForgeAgent"] diff --git a/python/pulsing/forge/host/cli_events.py b/python/pulsing/forge/host/cli_events.py deleted file mode 100644 index d889741d4..000000000 --- a/python/pulsing/forge/host/cli_events.py +++ /dev/null @@ -1,95 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Default CLI sink for Forge + LLM streaming events.""" - -from __future__ import annotations - -import json -import sys -from dataclasses import dataclass -from typing import Any, TextIO - -from pulsing.forge.events import ForgeEvent, ForgeEventKind -from pulsing.forge.result import ToolResult - - -def _preview_args(arguments: dict[str, Any], limit: int = 120) -> str: - try: - text = json.dumps(arguments, ensure_ascii=False) - except TypeError: - text = str(arguments) - if len(text) > limit: - return text[: limit - 1] + "…" - return text - - -@dataclass -class CliEventSink: - """Print assistant text and tool activity to a terminal (Codex-like feedback).""" - - stream_assistant: bool = True - verbose_tools: bool = True - out: TextIO = sys.stdout - err: TextIO = sys.stderr - - def on_assistant_delta(self, text: str) -> None: - if self.stream_assistant and text: - print(text, end="", flush=True, file=self.out) - - def on_assistant_end(self) -> None: - if self.stream_assistant: - print(file=self.out, flush=True) - - def on_tool_begin(self, name: str, arguments: dict[str, Any] | None = None) -> None: - args = dict(arguments or {}) - if self.verbose_tools and args: - print(f"\n→ {name}({_preview_args(args)})", flush=True, file=self.out) - else: - print(f"\n→ {name}", flush=True, file=self.out) - - def on_tool_end(self, name: str, result: ToolResult) -> None: - preview = (result.content or "").replace("\n", "\\n")[:200] - tag = "error" if result.is_error else "ok" - print(f"← {name} [{tag}] {preview}", flush=True, file=self.out) - - def on_plan_updated(self, plan: list[dict[str, Any]]) -> None: - if not plan: - return - print("\n── plan ──", file=self.out) - for item in plan: - status = item.get("status", "?") - step = item.get("step", "") - print(f" [{status}] {step}", file=self.out) - print("──────────", flush=True, file=self.out) - - def on_error(self, message: str) -> None: - print(f"\n! {message}", flush=True, file=self.err) - - def on_forge_event(self, raw: dict[str, Any]) -> None: - """Rust Forge ``event_callback`` — tool begin/end handled by Host to avoid dupes.""" - ev = ForgeEvent.from_dict(raw) - kind = ev.kind - if kind in ( - ForgeEventKind.TOOL_BEGIN.value, - ForgeEventKind.TOOL_END.value, - ): - return - if kind == ForgeEventKind.EXEC_OUTPUT_DELTA.value: - chunk = str(ev.payload.get("chunk") or "") - if chunk: - print(chunk, end="", flush=True, file=self.out) - return - if kind == ForgeEventKind.PLAN_UPDATED.value: - plan = ev.payload.get("plan") - if isinstance(plan, list): - self.on_plan_updated(plan) - return - if kind == ForgeEventKind.USER_INPUT_REQUEST.value: - print( - "\n? user input requested (auto-approved in ForgeAgent)", file=self.out - ) - return - if kind == ForgeEventKind.EXEC_APPROVAL_REQUEST.value: - print("\n? exec approval requested (auto-approved)", file=self.out) - return - if kind == ForgeEventKind.REQUEST_PERMISSIONS.value: - print("\n? permissions requested (auto-approved)", file=self.out) diff --git a/python/pulsing/forge/host/legacy_agent.py b/python/pulsing/forge/host/legacy_agent.py deleted file mode 100644 index fc5b9cb6f..000000000 --- a/python/pulsing/forge/host/legacy_agent.py +++ /dev/null @@ -1,229 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Explicit legacy Python-owned Forge loop. - -This module is not used by the default ``ForgeAgent``. It remains temporarily -available for development while Python-only tools move behind worker adapters. -""" - -from __future__ import annotations - -import asyncio -import os -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from pulsing.forge.host.llm import LLMClient, LLMMessage -from pulsing.forge.environment import ForgeEnvironment -from pulsing.forge.host.cli_events import CliEventSink -from pulsing.forge.hybrid_runtime import HybridForgeRuntime -from pulsing.forge.result import ToolResult -from pulsing.forge.rust_runtime import rust_forge_available -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.session import LocalToolSession -from pulsing.forge.tool_calls import ( - anthropic_tool_result_block, - anthropic_tool_results_message, - extract_tool_calls_anthropic, - forge_tool_definitions, -) - -DEFAULT_TOOL_NAMES: tuple[str, ...] = ( - "update_plan", - "Glob", - "Read", - "Grep", - "shell_command", -) - -_DEFAULT_SYSTEM = """\ -You are a capable coding agent with filesystem and shell tools. -Use tools to inspect the workspace before answering. -When multi-step work is needed, call update_plan first. -Be concise in final replies.\ -""" - - -def _text_from_content(content: list[Any]) -> str: - parts: list[str] = [] - for block in content or []: - if isinstance(block, dict) and block.get("type") == "text": - parts.append(str(block.get("text") or "")) - return "".join(parts) - - -@dataclass -class LegacyPythonForgeAgent: - """Thin Host: LLM loop + Forge tools + default CLI event output. - - Example:: - - agent = LegacyPythonForgeAgent(cwd=".", provider="demo") - text = await agent.run("List README files in this project") - """ - - cwd: Path | str = "." - provider: str = "demo" - model: str = "demo" - api_key: str | None = None - base_url: str | None = None - max_tokens: int = 8192 - max_turns: int = 20 - tool_names: tuple[str, ...] = DEFAULT_TOOL_NAMES - system_prompt: str = _DEFAULT_SYSTEM - sandbox_policy: str = "off" - auto_approve: bool = True - events: CliEventSink = field(default_factory=CliEventSink) - _messages: list[dict[str, Any]] = field( - default_factory=list, init=False, repr=False - ) - _runtime: HybridForgeRuntime | LocalToolRuntime | None = field( - default=None, init=False, repr=False - ) - _client: LLMClient | None = field(default=None, init=False, repr=False) - - def __post_init__(self) -> None: - self.cwd = Path(self.cwd).resolve() - if self.provider == "openai" and not self.api_key: - self.api_key = os.environ.get("OPENAI_API_KEY") - self.base_url = self.base_url or os.environ.get("OPENAI_BASE_URL") - elif self.provider == "anthropic" and not self.api_key: - self.api_key = os.environ.get("ANTHROPIC_API_KEY") - self.base_url = self.base_url or os.environ.get("ANTHROPIC_BASE_URL") - - def _ensure_runtime(self) -> HybridForgeRuntime | LocalToolRuntime: - if self._runtime is not None: - return self._runtime - session = LocalToolSession(token_budget=128_000) - if rust_forge_available(): - self._runtime = HybridForgeRuntime.create( - cwd=str(self.cwd), - sandbox_policy=self.sandbox_policy, - session=session, - auto_approve=self.auto_approve, - event_callback=self.events.on_forge_event, - start_mcp=False, - ) - else: - self._runtime = ForgeEnvironment( - cwd=str(self.cwd), - sandbox_policy=self.sandbox_policy, - session=session, - auto_approve=self.auto_approve, - ).runtime() - return self._runtime - - def _ensure_client(self) -> LLMClient: - if self._client is None: - self._client = LLMClient( - provider=self.provider, - api_key=self.api_key, - base_url=self.base_url, - ) - return self._client - - @property - def messages(self) -> list[dict[str, Any]]: - return list(self._messages) - - @property - def session(self) -> LocalToolSession: - rt = self._ensure_runtime() - return rt.python_runtime.session # type: ignore[return-value] - - def close(self) -> None: - if self._runtime is not None: - self._runtime.close() - self._runtime = None - - async def run(self, prompt: str) -> str: - """Run a multi-turn agent session until the model stops calling tools.""" - self._messages = [] - self._messages.append({"role": "user", "content": prompt}) - tools = forge_tool_definitions(list(self.tool_names)) - rt = self._ensure_runtime() - final: LLMMessage | None = None - - for _ in range(self.max_turns): - final = await self._stream_one_llm(self._messages, tools) - self._messages.append({"role": "assistant", "content": list(final.content)}) - self.events.on_assistant_end() - - calls = extract_tool_calls_anthropic(final.content) - if not calls: - return _text_from_content(final.content) - - result_blocks = [] - for call in calls: - result = await self._call_tool(rt, call.name, call.arguments) - result_blocks.append(anthropic_tool_result_block(call.id, result)) - - self._messages.append(anthropic_tool_results_message(result_blocks)) - - if self.session.plan: - self.events.on_plan_updated( - [item.to_dict() for item in self.session.plan] - ) - - text = _text_from_content(final.content) if final else "" - return text or "(max turns reached)" - - async def _call_tool( - self, - rt: HybridForgeRuntime | LocalToolRuntime, - name: str, - arguments: dict[str, Any], - ) -> ToolResult: - self.events.on_tool_begin(name, arguments) - result = await rt.acall_tool(name, arguments) - self.events.on_tool_end(name, result) - return result - - async def _stream_one_llm( - self, - messages: list[dict[str, Any]], - tools: list[dict[str, Any]], - ) -> LLMMessage: - client = self._ensure_client() - q: asyncio.Queue[tuple[str, Any]] = asyncio.Queue() - loop = asyncio.get_running_loop() - - def _producer() -> None: - try: - stream = client.stream_messages( - model=self.model, - max_tokens=self.max_tokens, - system=self.system_prompt, - messages=messages, - tools=tools, - ) - with stream as s: - for text in s.text_stream: - loop.call_soon_threadsafe(q.put_nowait, ("chunk", text)) - loop.call_soon_threadsafe( - q.put_nowait, ("done", s.get_final_message()) - ) - except Exception as exc: - loop.call_soon_threadsafe(q.put_nowait, ("error", exc)) - - producer = asyncio.create_task(asyncio.to_thread(_producer)) - final: LLMMessage | None = None - try: - while True: - kind, payload = await q.get() - if kind == "chunk": - self.events.on_assistant_delta(str(payload)) - elif kind == "done": - final = payload - break - elif kind == "error": - self.events.on_error(str(payload)) - raise payload - finally: - await producer - - assert final is not None - return final - - -__all__ = ["LegacyPythonForgeAgent"] diff --git a/python/pulsing/forge/host/llm.py b/python/pulsing/forge/host/llm.py deleted file mode 100644 index 81921039a..000000000 --- a/python/pulsing/forge/host/llm.py +++ /dev/null @@ -1,68 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""LLM clients for Host applications — backed by Forge (Rust).""" - -from __future__ import annotations - -import os -from typing import Any - -from pulsing.agent.loop.deps import require_provider_deps -from pulsing.forge.llm_client import LLMClient, LLMMessage, LLMUsage, RUST_LLM_AVAILABLE - -__all__ = [ - "LLMClient", - "LLMMessage", - "LLMUsage", - "RUST_LLM_AVAILABLE", - "create_llm_client", - "default_model", - "default_provider", - "llm_runtime_options", -] - - -def default_provider() -> str: - if os.environ.get("ANTHROPIC_API_KEY", "").strip(): - return "anthropic" - if os.environ.get("OPENAI_API_KEY", "").strip(): - return "openai" - return "demo" - - -def default_model(provider: str, explicit: str | None = None) -> str: - if explicit: - return explicit - p = (provider or "anthropic").strip().lower() - if p == "demo": - return "demo" - if p == "openai": - return os.environ.get("OPENAI_MODEL", "gpt-4o") - return os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-4-20250514") - - -def create_llm_client( - *, - provider: str = "demo", - model: str | None = None, - api_key: str | None = None, - base_url: str | None = None, - max_tokens: int = 8192, -) -> LLMClient: - del max_tokens # applied per stream_messages call - require_provider_deps(provider) - return LLMClient(provider=provider, api_key=api_key, base_url=base_url) - - -def llm_runtime_options( - *, - provider: str = "demo", - model: str | None = None, - auto_approve: bool = True, - sandbox: str = "off", -) -> dict[str, Any]: - return { - "provider": provider, - "model": default_model(provider, model), - "auto_approve": auto_approve, - "sandbox": sandbox, - } diff --git a/python/pulsing/forge/hybrid_runtime.py b/python/pulsing/forge/hybrid_runtime.py deleted file mode 100644 index 028a7768a..000000000 --- a/python/pulsing/forge/hybrid_runtime.py +++ /dev/null @@ -1,164 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Legacy hybrid tool adapter. - -This type no longer owns the default Agent loop or Session. Keep its use -explicit while Python-only tools migrate behind Rust-registered workers. -""" - -from __future__ import annotations - -from typing import Any, Callable - -from pulsing.forge.codex_parity import PYTHON_ONLY_HOST -from pulsing.forge.integrated import FORGE_TOOL_NAMES -from pulsing.forge.result import ToolResult -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE, RustForgeAdapter -from pulsing.forge.session import LocalToolSession, ToolSession, UpdatePlanArgs - -# Session tools executed on the Rust path keep state in a separate in-process -# `LocalToolSession` unless an `event_callback` is wired. Mirror successful -# calls onto the Python `ToolSession` so host/tests see one plan snapshot. -_RUST_SESSION_SYNC = frozenset({"update_plan", "new_context"}) - - -class HybridForgeRuntime: - """Explicit compatibility adapter for mixed Rust/Python tool execution. - - Rust executes isolated + most Host tools; Python handles tools without Rust - handlers (``exec``, ``wait``, Extension×8) so all 32 Forge tools are callable. - """ - - def __init__( - self, - *, - python: LocalToolRuntime, - rust: RustForgeAdapter | None, - sync_rust_session: bool = False, - ) -> None: - self._python = python - self._rust = rust - self._rust_names = ( - frozenset(rust.tool_names()) if rust is not None else frozenset() - ) - self._sync_rust_session = sync_rust_session - - @classmethod - def create( - cls, - *, - cwd: str, - sandbox_policy: str = "off", - dangerously_disable_sandbox: bool = False, - session: ToolSession | None = None, - auto_approve: bool = False, - event_callback: Callable[[dict[str, Any]], None] | None = None, - user_input_callback: Callable[[dict[str, Any]], dict[str, Any]] | None = None, - exec_approval_callback: Callable[[dict[str, Any]], str] | None = None, - request_permissions_callback: ( - Callable[[dict[str, Any]], dict[str, Any]] | None - ) = None, - tokens_remaining_callback: Callable[[], int | None] | None = None, - plugin_install_callback: Callable[[dict[str, Any]], bool | str] | None = None, - start_mcp: bool = True, - ) -> HybridForgeRuntime: - sess = session or LocalToolSession() - if tokens_remaining_callback is None: - session_tokens = getattr(sess, "tokens_remaining", None) - if callable(session_tokens): - tokens_remaining_callback = session_tokens - catalog = getattr(sess, "tool_catalog", None) - python = LocalToolRuntime( - cwd=cwd, - sandbox_policy=sandbox_policy, - dangerously_disable_sandbox=dangerously_disable_sandbox, - session=sess, - tool_catalog=catalog, - ) - rust: RustForgeAdapter | None = None - if RUST_FORGE_AVAILABLE: - rust = RustForgeAdapter.create( - cwd=cwd, - sandbox_policy=sandbox_policy, - dangerously_disable_sandbox=dangerously_disable_sandbox, - auto_approve=auto_approve, - event_callback=event_callback, - user_input_callback=user_input_callback, - exec_approval_callback=exec_approval_callback, - request_permissions_callback=request_permissions_callback, - tokens_remaining_callback=tokens_remaining_callback, - plugin_install_callback=plugin_install_callback, - start_mcp=start_mcp, - ) - return cls( - python=python, - rust=rust, - sync_rust_session=event_callback is None, - ) - - @property - def python_runtime(self) -> LocalToolRuntime: - return self._python - - @property - def rust_runtime(self) -> RustForgeAdapter | None: - return self._rust - - def refresh_mcp(self) -> None: - if self._rust is not None: - self._rust.refresh_mcp() - - def close(self) -> None: - self._python.close() - - def tool_names(self) -> list[str]: - return sorted(FORGE_TOOL_NAMES) - - def _mirror_rust_session(self, name: str, args: dict[str, Any]) -> None: - sess = self._python.session - if name == "update_plan": - try: - parsed = UpdatePlanArgs.from_dict(args) - except (TypeError, ValueError): - return - sess.update_plan(parsed) - elif name == "new_context": - sess.request_new_context() - - def _use_python(self, name: str) -> bool: - from pulsing.forge.mcp.naming import is_mcp_dynamic_tool - - if is_mcp_dynamic_tool(name): - return False - if name in PYTHON_ONLY_HOST: - return True - if self._rust is None: - return True - if name in FORGE_TOOL_NAMES and name not in self._rust_names: - return True - return False - - def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> ToolResult: - from pulsing.forge.mcp.naming import is_mcp_dynamic_tool - - args = dict(arguments or {}) - if self._use_python(name): - return self._python.call_tool(name, args) - assert self._rust is not None - out = self._rust.call_tool(name, args) - if ( - out.is_error - and out.content.startswith("Unknown tool:") - and not is_mcp_dynamic_tool(name) - ): - return self._python.call_tool(name, args) - if self._sync_rust_session and not out.is_error and name in _RUST_SESSION_SYNC: - self._mirror_rust_session(name, args) - return out - - async def acall_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> ToolResult: - return self.call_tool(name, arguments) diff --git a/python/pulsing/forge/integrated.py b/python/pulsing/forge/integrated.py deleted file mode 100644 index feb5b5091..000000000 --- a/python/pulsing/forge/integrated.py +++ /dev/null @@ -1,104 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Unified Forge runtime: tools + P2P session hooks on one host link.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.forge.events import ForgeEvent -from pulsing.forge.p2p_session import EmitFn -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.result import ToolResult -from pulsing.forge.session import ToolSession - -# Tools executed in isolated ToolWorkerActor (filesystem + execution). -FORGE_ISOLATED_TOOL_NAMES: frozenset[str] = frozenset( - { - "Read", - "Glob", - "Grep", - "Edit", - "Write", - "Bash", - "shell_command", - "exec_command", - "write_stdin", - "apply_patch", - "view_image", - } -) - -# Session tools run in-process on the host (need UI / agent state). -FORGE_HOST_TOOL_NAMES: frozenset[str] = frozenset( - { - "update_plan", - "new_context", - "get_context_remaining", - "request_user_input", - "request_permissions", - "tool_search", - "list_available_plugins_to_install", - "request_plugin_install", - "list_mcp_resources", - "list_mcp_resource_templates", - "read_mcp_resource", - "exec", - "wait", - "web.run", - "skills.list", - "skills.read", - "memories.list", - "memories.read", - "memories.search", - "memories.add_ad_hoc_note", - "web_search", - } -) - -FORGE_TOOL_NAMES: frozenset[str] = FORGE_ISOLATED_TOOL_NAMES | FORGE_HOST_TOOL_NAMES - - -class ForgeHostLink: - """In-process Forge runtime wired to a host agent via P2P events.""" - - def __init__( - self, - *, - cwd: str, - sandbox_policy: str, - dangerously_disable_sandbox: bool, - session: ToolSession, - emit: EmitFn | None = None, - ) -> None: - self._emit = emit - self._runtime = LocalToolRuntime( - cwd=cwd, - sandbox_policy=sandbox_policy, - dangerously_disable_sandbox=dangerously_disable_sandbox, - session=session, - tool_catalog=getattr(session, "tool_catalog", None), - ) - - @property - def runtime(self) -> LocalToolRuntime: - return self._runtime - - def close(self) -> None: - self._runtime.close() - - def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> ToolResult: - args = dict(arguments or {}) - if self._emit is not None: - self._emit(ForgeEvent.tool_begin(name, args)) - out = self._runtime.call_tool(name, args) - if self._emit is not None: - self._emit( - ForgeEvent.tool_end( - name, - is_error=bool(out.is_error), - content_preview=out.content, - ) - ) - return out diff --git a/python/pulsing/forge/llm_client.py b/python/pulsing/forge/llm_client.py deleted file mode 100644 index 1b2228bad..000000000 --- a/python/pulsing/forge/llm_client.py +++ /dev/null @@ -1,146 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge-native LLM client (Rust ``pulsing-forge`` via ``pulsing._core``).""" - -from __future__ import annotations - -from dataclasses import dataclass -from typing import Any, Iterator - -try: - from pulsing._core import LlmClient as _RustLlmClient - from pulsing._core import LlmStream as _RustLlmStream - - RUST_LLM_AVAILABLE = True -except ImportError: - _RustLlmClient = None # type: ignore[misc, assignment] - _RustLlmStream = None # type: ignore[misc, assignment] - RUST_LLM_AVAILABLE = False - -_VALID_PROVIDERS = frozenset({"anthropic", "openai", "demo"}) - - -@dataclass -class LLMUsage: - input_tokens: int = 0 - output_tokens: int = 0 - - -@dataclass -class LLMMessage: - content: list[dict[str, Any]] - usage: LLMUsage | None = None - stop_reason: str | None = None - - -def _usage_from_dict(raw: Any) -> LLMUsage | None: - if not raw: - return None - if isinstance(raw, LLMUsage): - return raw - if isinstance(raw, dict): - return LLMUsage( - input_tokens=int(raw.get("input_tokens") or 0), - output_tokens=int(raw.get("output_tokens") or 0), - ) - return None - - -def _message_from_dict(raw: Any) -> LLMMessage: - if isinstance(raw, LLMMessage): - return raw - if not isinstance(raw, dict): - return LLMMessage(content=[{"type": "text", "text": str(raw)}]) - content = raw.get("content") or [] - if not isinstance(content, list): - content = [{"type": "text", "text": str(content)}] - return LLMMessage( - content=[dict(b) if isinstance(b, dict) else b for b in content], - usage=_usage_from_dict(raw.get("usage")), - stop_reason=raw.get("stop_reason"), - ) - - -class _RustStreamAdapter: - """Adapt Rust ``LlmStream`` to the Python agent loop protocol.""" - - def __init__(self, inner: Any) -> None: - self._inner = inner - self.text_stream: Iterator[str] = iter(()) - - def __enter__(self) -> _RustStreamAdapter: - self._inner.__enter__() - self.text_stream = iter(self._inner.text_stream) - return self - - def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None: - self._inner.__exit__(exc_type, exc, tb) - - def close(self) -> None: - self._inner.close() - - def get_final_message(self) -> LLMMessage: - return _message_from_dict(self._inner.get_final_message()) - - -class LLMClient: - """Anthropic / OpenAI / demo LLM client backed by ``pulsing-forge``.""" - - def __init__( - self, - *, - provider: str = "anthropic", - api_key: str | None = None, - base_url: str | None = None, - ) -> None: - p = (provider or "anthropic").strip().lower() - if p not in _VALID_PROVIDERS: - raise ValueError( - f"Unsupported provider {provider!r}; use anthropic, openai, or demo", - ) - if not RUST_LLM_AVAILABLE: - raise RuntimeError( - "Rust LLM client unavailable — rebuild with: maturin develop", - ) - self.provider = p - self._client = _RustLlmClient( - provider=p, - api_key=api_key, - base_url=base_url, - ) - - def stream_messages( - self, - *, - model: str, - max_tokens: int, - messages: list[dict[str, Any]], - system: str | None = None, - tools: list[dict[str, Any]] | None = None, - ) -> _RustStreamAdapter: - stream = self._client.stream_messages( - model=model, - max_tokens=max_tokens, - messages=messages, - system=system, - tools=tools or [], - ) - return _RustStreamAdapter(stream) - - @staticmethod - def error_message(exc: Exception) -> str: - return str(getattr(exc, "message", None) or exc) - - def is_authentication_error(self, exc: Exception) -> bool: - if not RUST_LLM_AVAILABLE: - return False - return bool(self._client.is_authentication_error(exc)) - - def is_retryable_error(self, exc: Exception) -> bool: - if not RUST_LLM_AVAILABLE: - return False - return bool(self._client.is_retryable_error(exc)) - - def is_api_error(self, exc: Exception) -> bool: - if not RUST_LLM_AVAILABLE: - return False - return bool(self._client.is_api_error(exc)) diff --git a/python/pulsing/forge/mcp/__init__.py b/python/pulsing/forge/mcp/__init__.py deleted file mode 100644 index f4e401dfc..000000000 --- a/python/pulsing/forge/mcp/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex-aligned MCP runtime for Forge (catalog + connection manager hooks).""" - -from pulsing.forge.mcp.catalog import load_mcp_catalog, parse_plugin_mcp_file -from pulsing.forge.mcp.manager import ( - McpManager, - get_global_mcp_manager, - refresh_global_mcp_manager, -) -from pulsing.forge.mcp.naming import MCP_TOOL_NAME_PREFIX, is_mcp_dynamic_tool -from pulsing.forge.mcp.sync import sync_mcp_tools_to_agent - -__all__ = [ - "MCP_TOOL_NAME_PREFIX", - "McpManager", - "get_global_mcp_manager", - "is_mcp_dynamic_tool", - "load_mcp_catalog", - "parse_plugin_mcp_file", - "refresh_global_mcp_manager", - "sync_mcp_tools_to_agent", -] diff --git a/python/pulsing/forge/mcp/catalog.py b/python/pulsing/forge/mcp/catalog.py deleted file mode 100644 index d6ba804e4..000000000 --- a/python/pulsing/forge/mcp/catalog.py +++ /dev/null @@ -1,126 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""MCP catalog loading — mirrors `pulsing-forge` MCP module (plugin + config.toml).""" - -from __future__ import annotations - -import json -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from pulsing.forge.discovery.codex_manifest import ( - find_plugin_manifest_path, - load_codex_manifest, -) -from pulsing.forge.discovery.codex_paths import codex_home -from pulsing.forge.discovery.plugin_store import PluginStore - - -@dataclass -class McpServerEntry: - name: str - config: dict[str, Any] - source: str - plugin_id: str | None = None - - -@dataclass -class McpCatalogSnapshot: - servers: dict[str, McpServerEntry] = field(default_factory=dict) - - -def _load_config_toml_servers() -> dict[str, dict[str, Any]]: - path = codex_home() / "config.toml" - if not path.is_file(): - return {} - try: - import tomllib - except ModuleNotFoundError: - import tomli as tomllib # type: ignore[no-redef] - - raw = tomllib.loads(path.read_text(encoding="utf-8")) - block = raw.get("mcp_servers") or {} - if not isinstance(block, dict): - return {} - return {str(k): dict(v) if isinstance(v, dict) else {} for k, v in block.items()} - - -def parse_plugin_mcp_file( - plugin_root: Path, mcp_path: Path -) -> dict[str, dict[str, Any]]: - """Parse `.mcp.json` — both `{mcpServers:{}}` and flat server map shapes.""" - raw = json.loads(mcp_path.read_text(encoding="utf-8")) - if isinstance(raw, dict) and "mcpServers" in raw: - servers = raw["mcpServers"] - elif isinstance(raw, dict): - servers = raw - else: - return {} - if not isinstance(servers, dict): - return {} - out: dict[str, dict[str, Any]] = {} - for name, cfg in servers.items(): - if isinstance(cfg, dict): - out[str(name)] = _normalize_plugin_server_config(plugin_root, dict(cfg)) - return out - - -def _normalize_plugin_server_config( - plugin_root: Path, cfg: dict[str, Any] -) -> dict[str, Any]: - cfg.pop("type", None) - oauth = cfg.pop("oauth", None) - if isinstance(oauth, dict): - oauth = dict(oauth) - oauth.pop("callbackPort", None) - if "clientId" in oauth and "client_id" not in oauth: - oauth["client_id"] = oauth.pop("clientId") - if oauth: - cfg["oauth"] = oauth - cwd = cfg.get("cwd") - if isinstance(cwd, str) and cwd and not Path(cwd).is_absolute(): - cfg["cwd"] = str((plugin_root / cwd).resolve()) - return cfg - - -def load_plugin_mcp_servers() -> list[McpServerEntry]: - entries: list[McpServerEntry] = [] - store = PluginStore() - for pid in store.list_installed_plugin_ids(): - root = store.active_plugin_root(pid) - if root is None: - continue - manifest_path = find_plugin_manifest_path(root) - if manifest_path is None: - continue - try: - manifest = load_codex_manifest(root) - except ValueError: - continue - mcp_ref = manifest.mcp_servers_path - if not mcp_ref: - continue - mcp_path = (root / mcp_ref).resolve() - if not mcp_path.is_file(): - continue - plugin_id = pid.id - for name, cfg in parse_plugin_mcp_file(root, mcp_path).items(): - entries.append( - McpServerEntry( - name=name, - config=cfg, - source="plugin", - plugin_id=plugin_id, - ) - ) - return entries - - -def load_mcp_catalog() -> McpCatalogSnapshot: - """Plugin registrations first; `config.toml` overrides (Codex precedence).""" - snap = McpCatalogSnapshot() - for entry in load_plugin_mcp_servers(): - snap.servers[entry.name] = entry - for name, cfg in _load_config_toml_servers().items(): - snap.servers[name] = McpServerEntry(name=name, config=cfg, source="config") - return snap diff --git a/python/pulsing/forge/mcp/hub.py b/python/pulsing/forge/mcp/hub.py deleted file mode 100644 index 35e01a25d..000000000 --- a/python/pulsing/forge/mcp/hub.py +++ /dev/null @@ -1,64 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace MCP hub actor — refresh connections and list live tools.""" - -from __future__ import annotations - -import logging -from typing import Any - -from pulsing.core.proxy import ActorProxy -from pulsing.core.remote import remote, resolve - -from pulsing.forge.mcp.manager import get_global_mcp_manager -from pulsing.forge.naming import mcp_hub_name - -logger = logging.getLogger(__name__) - - -@remote -class McpHubActor: - """Owns a Forge host runtime for MCP refresh and tool discovery.""" - - def __init__(self, cwd: str = ".", *, auto_approve: bool = True) -> None: - from pulsing.forge.backend import ForgeHostConfig, create_host_runtime - - self._cwd = cwd - self._host = create_host_runtime( - ForgeHostConfig(cwd=cwd, auto_approve=auto_approve), - ) - - async def refresh(self) -> dict[str, Any]: - self._host.refresh_mcp() - tools = self.list_tools() - return {"ok": True, "tools": tools, "count": len(tools)} - - def list_tools(self) -> list[dict[str, Any]]: - rust = getattr(self._host, "rust_runtime", None) - mgr = get_global_mcp_manager() - mgr.refresh_catalog() - if rust is not None: - mgr.sync_live_tools_from_rust(rust) - out: list[dict[str, Any]] = [] - seen: set[str] = set() - for stub in mgr.deferred_tool_stubs(): - if stub.model_name in seen: - continue - seen.add(stub.model_name) - out.append( - { - "name": stub.model_name, - "description": stub.description or stub.model_name, - "parameters": dict( - stub.input_schema or {"type": "object", "properties": {}} - ), - } - ) - return out - - -async def ensure_mcp_hub(workspace_id: str, *, cwd: str = ".") -> ActorProxy: - name = mcp_hub_name(workspace_id) - try: - return await resolve(name, cls=McpHubActor, timeout=30.0) - except Exception: - return await McpHubActor.spawn(cwd, name=name, public=True) diff --git a/python/pulsing/forge/mcp/manager.py b/python/pulsing/forge/mcp/manager.py deleted file mode 100644 index 6bca84a5e..000000000 --- a/python/pulsing/forge/mcp/manager.py +++ /dev/null @@ -1,103 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""MCP connection manager — Python host side (Craft session lifecycle).""" - -from __future__ import annotations - -import logging -from dataclasses import dataclass, field -from typing import Any - -from pulsing.forge.mcp.catalog import McpCatalogSnapshot, load_mcp_catalog -from pulsing.forge.mcp.naming import MCP_TOOL_NAME_PREFIX - -logger = logging.getLogger(__name__) - -_GLOBAL: McpManager | None = None - - -@dataclass -class McpToolStub: - model_name: str - server_name: str - tool_name: str - description: str | None = None - input_schema: dict[str, Any] = field(default_factory=dict) - - -@dataclass -class McpManager: - """Host-side MCP state. Live stdio/HTTP connections run in Rust `pulsing-forge` MCP module.""" - - catalog: McpCatalogSnapshot = field(default_factory=McpCatalogSnapshot) - live_tools: list[McpToolStub] = field(default_factory=list) - startup_failures: list[dict[str, str]] = field(default_factory=list) - started: bool = False - - def refresh_catalog(self) -> None: - self.catalog = load_mcp_catalog() - - def deferred_tool_stubs(self) -> list[McpToolStub]: - """Live MCP tools when synced from Rust; else per-server namespace stubs.""" - if self.live_tools: - return list(self.live_tools) - out: list[McpToolStub] = [] - for name, entry in sorted(self.catalog.servers.items()): - if entry.config.get("enabled") is False: - continue - ns = f"{MCP_TOOL_NAME_PREFIX}{name}" - out.append( - McpToolStub( - model_name=ns, - server_name=name, - tool_name=ns, - description=f"MCP server {name} ({entry.source})", - input_schema={"type": "object", "properties": {}}, - ) - ) - return out - - def sync_live_tools_from_rust(self, rust: Any) -> None: - """Pull model-visible MCP function tools from ``RustForgeAdapter``.""" - specs = [] - if hasattr(rust, "mcp_tool_specs"): - specs = list(rust.mcp_tool_specs()) - self.live_tools = [ - McpToolStub( - model_name=str(spec.get("name") or ""), - server_name=str(spec.get("server_name") or ""), - tool_name=str(spec.get("tool_name") or ""), - description=str(spec.get("description") or spec.get("name") or ""), - input_schema=dict( - spec.get("input_schema") or {"type": "object", "properties": {}} - ), - ) - for spec in specs - if spec.get("name") - ] - - async def start(self) -> None: - """Start MCP servers (Rust runtime when maturin binding is wired).""" - self.refresh_catalog() - self.live_tools = self.deferred_tool_stubs() - self.started = True - logger.info( - "MCP catalog loaded: %d servers (live handshake via pulsing-forge mcp)", - len(self.catalog.servers), - ) - - async def stop(self) -> None: - self.started = False - self.live_tools = [] - - -def get_global_mcp_manager() -> McpManager: - global _GLOBAL - if _GLOBAL is None: - _GLOBAL = McpManager() - return _GLOBAL - - -async def refresh_global_mcp_manager() -> McpManager: - mgr = get_global_mcp_manager() - await mgr.start() - return mgr diff --git a/python/pulsing/forge/mcp/naming.py b/python/pulsing/forge/mcp/naming.py deleted file mode 100644 index f03718868..000000000 --- a/python/pulsing/forge/mcp/naming.py +++ /dev/null @@ -1,11 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""MCP dynamic tool naming — aligned with ``pulsing-forge`` ``LEGACY_MCP_TOOL_NAME_PREFIX``.""" - -from __future__ import annotations - -MCP_TOOL_NAME_PREFIX = "mcp__" - - -def is_mcp_dynamic_tool(name: str) -> bool: - """True when ``name`` is a per-server MCP function tool (not a Forge builtin).""" - return name.startswith(MCP_TOOL_NAME_PREFIX) diff --git a/python/pulsing/forge/mcp/sync.py b/python/pulsing/forge/mcp/sync.py deleted file mode 100644 index 629a554bc..000000000 --- a/python/pulsing/forge/mcp/sync.py +++ /dev/null @@ -1,70 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Register MCP tools discovered by the hub into Craft LLM schema.""" - -from __future__ import annotations - -import logging -from typing import Any - -from pulsing.core.remote import resolve - -from pulsing.forge.discovery.deferred import DeferredForgeTool - -logger = logging.getLogger(__name__) - - -async def sync_mcp_tools_to_agent(agent: Any) -> list[str]: - """Refresh hub (if configured) and register MCP tools on the agent LLM.""" - hub_name = getattr(agent, "_mcp_hub_name", None) - specs: list[dict[str, Any]] = [] - if hub_name: - try: - hub = await resolve(hub_name, timeout=30.0) - out = await hub.refresh() - if isinstance(out, dict): - specs = list(out.get("tools") or []) - except Exception as exc: - logger.warning("MCP hub refresh failed: %s", exc) - if not specs: - backend = getattr(agent, "_forge_backend", None) - if backend is not None: - backend.refresh_mcp() - host = getattr(backend, "host", None) - rust = getattr(host, "rust_runtime", None) if host is not None else None - if rust is not None: - from pulsing.forge.mcp.manager import get_global_mcp_manager - - get_global_mcp_manager().sync_live_tools_from_rust(rust) - from pulsing.forge.mcp.manager import get_global_mcp_manager - - mgr = get_global_mcp_manager() - mgr.refresh_catalog() - specs = [ - { - "name": stub.model_name, - "description": stub.description or stub.model_name, - "parameters": dict( - stub.input_schema or {"type": "object", "properties": {}} - ), - } - for stub in mgr.deferred_tool_stubs() - ] - - llm = getattr(agent, "_llm", None) - activated: list[str] = [] - for spec in specs: - name = str(spec.get("name") or "").strip() - if not name or name in agent._tools_by_name: - continue - tool = DeferredForgeTool( - name=name, - description=str(spec.get("description") or name), - parameters=dict( - spec.get("parameters") or {"type": "object", "properties": {}} - ), - ) - agent._tools_by_name[name] = tool - if llm is not None: - llm.register_tool(tool) - activated.append(name) - return activated diff --git a/python/pulsing/forge/naming.py b/python/pulsing/forge/naming.py deleted file mode 100644 index 766329dba..000000000 --- a/python/pulsing/forge/naming.py +++ /dev/null @@ -1,61 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Gossip names for Forge actors on the Pulsing cluster.""" - -from __future__ import annotations - -FORGE_WORKER_SHORT = "_tools" -MCP_HUB_SHORT = "_mcp_hub" -# Gossip namespace for workspace-scoped agents and shared workers. -# Legacy ``craft/ws`` remains the default until a coordinated prefix migration. -DEFAULT_WORKSPACE_PREFIX = "craft/ws" -FUTURE_WORKSPACE_PREFIX = "agent/ws" - - -def shared_tool_worker_name( - workspace_id: str, - *, - prefix: str = DEFAULT_WORKSPACE_PREFIX, -) -> str: - """Public gossip name for a workspace-level shared ``ToolWorkerActor``.""" - ws = (workspace_id or "").strip().strip("/") - if not ws: - raise ValueError("workspace_id must be non-empty") - p = (prefix or DEFAULT_WORKSPACE_PREFIX).strip().strip("/") - return f"{p}/{ws}/{FORGE_WORKER_SHORT}" - - -def forge_event_inbox_name(host_name: str) -> str: - """Named inbox actor that receives Forge tell events for a host agent.""" - host = (host_name or "").strip().strip("/") - if not host: - raise ValueError("host_name must be non-empty") - return f"{host}/events" - - -def worker_supervisor_name(host_name: str) -> str: - """In-process supervisor that wraps an isolated ``ToolWorkerActor``.""" - host = (host_name or "").strip().strip("/") - if not host: - raise ValueError("host_name must be non-empty") - return f"{host}/worker" - - -def mcp_hub_name( - workspace_id: str, - *, - prefix: str = DEFAULT_WORKSPACE_PREFIX, -) -> str: - """Workspace-level MCP connection hub.""" - ws = (workspace_id or "").strip().strip("/") - if not ws: - raise ValueError("workspace_id must be non-empty") - p = (prefix or DEFAULT_WORKSPACE_PREFIX).strip().strip("/") - return f"{p}/{ws}/{MCP_HUB_SHORT}" - - -def code_cell_registry_name(host_name: str) -> str: - """Per-host Code Mode cell registry.""" - host = (host_name or "").strip().strip("/") - if not host: - raise ValueError("host_name must be non-empty") - return f"{host}/code_cells" diff --git a/python/pulsing/forge/p2p_session.py b/python/pulsing/forge/p2p_session.py deleted file mode 100644 index 55f8deea8..000000000 --- a/python/pulsing/forge/p2p_session.py +++ /dev/null @@ -1,74 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""ToolSession that emits Forge events to a single host sink (P2P, not pub/sub).""" - -from __future__ import annotations - -from collections.abc import Callable -from dataclasses import dataclass, field -from typing import Any - -from pulsing.forge.events import ForgeEvent, ForgeEventKind -from pulsing.forge.session import LocalToolSession, PlanItem, UpdatePlanArgs - -EmitFn = Callable[[ForgeEvent], None] - - -@dataclass -class P2PToolSession(LocalToolSession): - """Forwards session hooks to one downstream consumer via ``emit``.""" - - emit: EmitFn | None = None - _pending: list[ForgeEvent] = field(default_factory=list, repr=False) - - def _send(self, event: ForgeEvent) -> None: - self._pending.append(event) - if self.emit is not None: - self.emit(event) - - def drain_pending(self) -> list[ForgeEvent]: - out = list(self._pending) - self._pending.clear() - return out - - def update_plan(self, args: UpdatePlanArgs) -> None: - super().update_plan(args) - self._send( - ForgeEvent( - kind=ForgeEventKind.PLAN_UPDATED.value, - payload={"plan": [p.to_dict() for p in args.plan]}, - ) - ) - - def request_new_context(self) -> None: - super().request_new_context() - self._send(ForgeEvent(kind=ForgeEventKind.NEW_CONTEXT.value, payload={})) - - def request_user_input(self, arguments: dict[str, Any]) -> dict[str, Any]: - from pulsing.forge.session_input import validate_request_user_input - - validate_request_user_input(arguments) - self._send( - ForgeEvent( - kind=ForgeEventKind.USER_INPUT_REQUEST.value, - payload=dict(arguments), - ) - ) - return super().request_user_input(arguments) - - def on_exec_output_delta(self, delta: Any) -> None: - super().on_exec_output_delta(delta) - if hasattr(delta, "session_id"): - session_id = int(delta.session_id) - stream = getattr(getattr(delta, "stream", None), "value", delta.stream) - chunk = str(delta.chunk) - else: - session_id = int(delta["session_id"]) - stream = str(delta.get("stream", "pty")) - chunk = str(delta.get("chunk", "")) - self._send( - ForgeEvent.exec_output_delta( - session_id=session_id, - stream=str(stream), - chunk=chunk, - ) - ) diff --git a/python/pulsing/forge/p2p_transport.py b/python/pulsing/forge/p2p_transport.py deleted file mode 100644 index 273d45cad..000000000 --- a/python/pulsing/forge/p2p_transport.py +++ /dev/null @@ -1,128 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Deliver Forge events to a named Pulsing actor (point-to-point tell).""" - -from __future__ import annotations - -import asyncio -import logging -from typing import Any - -from pulsing.core.remote import resolve - -from pulsing._async_bridge import run_sync -from pulsing.forge.events import ForgeEvent - -logger = logging.getLogger(__name__) - - -async def tell_forge_event(sink_name: str, event: ForgeEvent | dict[str, Any]) -> None: - payload = event.to_dict() if isinstance(event, ForgeEvent) else dict(event) - proxy = await resolve(sink_name) - await proxy.as_any().tell("on_forge_event", payload) - - -async def ask_exec_approval(sink_name: str, request: dict[str, Any]) -> dict[str, Any]: - """Blocking approval RPC: isolated worker → host Agent.""" - if not sink_name: - return {"decision": "denied"} - proxy = await resolve(sink_name) - out = await proxy.as_any().ask("resolve_exec_approval", dict(request)) - return dict(out) if isinstance(out, dict) else {"decision": "denied"} - - -async def ask_request_permissions( - sink_name: str, args: dict[str, Any] -) -> dict[str, Any]: - if not sink_name: - raise RuntimeError("request_permissions requires approval sink") - proxy = await resolve(sink_name) - out = await proxy.as_any().ask("resolve_request_permissions", dict(args)) - if not isinstance(out, dict): - raise RuntimeError("invalid request_permissions response") - return dict(out) - - -def tell_forge_event_sync(sink_name: str, event: ForgeEvent | dict[str, Any]) -> None: - """Best-effort tell from sync code (e.g. exec reader threads).""" - if not sink_name: - return - try: - run_sync(tell_forge_event(sink_name, event), timeout=5.0) - except Exception as e: - logger.debug("forge p2p tell failed sink=%s: %s", sink_name, e) - - -def ask_exec_approval_sync(sink_name: str, request: dict[str, Any]) -> dict[str, Any]: - if not sink_name: - return {"decision": "denied"} - try: - return run_sync(ask_exec_approval(sink_name, request), timeout=120.0) - except Exception as e: - logger.warning("forge exec approval ask failed sink=%s: %s", sink_name, e) - return {"decision": "denied"} - - -def ask_request_permissions_sync( - sink_name: str, args: dict[str, Any] -) -> dict[str, Any]: - if not sink_name: - raise RuntimeError("request_permissions requires approval sink") - try: - return run_sync(ask_request_permissions(sink_name, args), timeout=120.0) - except Exception as e: - logger.warning("forge request_permissions ask failed sink=%s: %s", sink_name, e) - raise - - -class ForgeEventPump: - """Async queue + background task: batches tell to host without blocking tool threads.""" - - def __init__(self, sink_name: str | None) -> None: - self._sink = (sink_name or "").strip() or None - self._queue: asyncio.Queue[ForgeEvent | None] | None = None - self._task: asyncio.Task[None] | None = None - - @property - def enabled(self) -> bool: - return bool(self._sink) - - def start(self) -> None: - if not self.enabled or self._task is not None: - return - self._queue = asyncio.Queue() - self._task = asyncio.create_task(self._run()) - - async def stop(self) -> None: - if self._queue is None: - return - await self._queue.put(None) - if self._task is not None: - await self._task - self._task = None - self._queue = None - - def emit_sync(self, event: ForgeEvent) -> None: - if not self.enabled or self._queue is None: - return - try: - loop = asyncio.get_running_loop() - loop.call_soon_threadsafe(self._queue.put_nowait, event) - except RuntimeError: - tell_forge_event_sync(self._sink or "", event) - - def emit(self, event: ForgeEvent) -> None: - if not self.enabled or self._queue is None: - return - self._queue.put_nowait(event) - - async def _run(self) -> None: - assert self._queue is not None - assert self._sink is not None - while True: - event = await self._queue.get() - if event is None: - return - try: - await tell_forge_event(self._sink, event) - except Exception as e: - logger.warning("forge event pump tell failed: %s", e) diff --git a/python/pulsing/forge/patch_apply.py b/python/pulsing/forge/patch_apply.py deleted file mode 100644 index 3c4c6ef5e..000000000 --- a/python/pulsing/forge/patch_apply.py +++ /dev/null @@ -1,215 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Minimal Codex apply_patch format support (local fs).""" - -from __future__ import annotations - -from dataclasses import dataclass -from pathlib import Path - - -@dataclass -class _UpdateChunk: - old_lines: list[str] - new_lines: list[str] - change_context: str | None = None - is_end_of_file: bool = False - - -def apply_patch_to_fs(patch: str, cwd: Path, *, root: Path | None = None) -> str: - boundary = root or cwd - hunks = _parse_patch(patch) - if not hunks: - raise ValueError("No files were modified.") - added: list[Path] = [] - modified: list[Path] = [] - deleted: list[Path] = [] - for hunk in hunks: - if hunk[0] == "add": - path = _resolve_patch_path(hunk[1], cwd, boundary) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(hunk[2], encoding="utf-8") - added.append(path) - elif hunk[0] == "delete": - path = _resolve_patch_path(hunk[1], cwd, boundary) - if path.is_dir(): - raise ValueError(f"Refusing to delete directory {path}") - path.unlink(missing_ok=False) - deleted.append(path) - elif hunk[0] == "update": - path = _resolve_patch_path(hunk[1], cwd, boundary) - text = path.read_text(encoding="utf-8") - new_text = _apply_update_chunks(text, hunk[2]) - move_to = hunk[3] - if move_to is not None: - dest = _resolve_patch_path(move_to, cwd, boundary) - dest.parent.mkdir(parents=True, exist_ok=True) - dest.write_text(new_text, encoding="utf-8") - path.unlink(missing_ok=False) - modified.append(dest) - else: - path.write_text(new_text, encoding="utf-8") - modified.append(path) - lines: list[str] = [] - for p in added: - lines.append(f"A {p}") - for p in modified: - lines.append(f"M {p}") - for p in deleted: - lines.append(f"D {p}") - return "\n".join(lines) - - -def _resolve_patch_path(rel: str | Path, base: Path, root: Path) -> Path: - p = Path(rel) - joined = p if p.is_absolute() else base / p - target = _normalize_lexically(joined) - boundary = _normalize_lexically(root) - if target != boundary and boundary not in target.parents: - raise ValueError( - f"refusing to apply patch outside working directory: {target} (cwd: {boundary})" - ) - resolved = target.resolve() - root_resolved = boundary.resolve() - if resolved != root_resolved and root_resolved not in resolved.parents: - raise ValueError( - f"refusing to apply patch outside working directory: {target} (cwd: {boundary})" - ) - return target - - -def _normalize_lexically(path: Path) -> Path: - out = Path("") - for part in path.parts: - if part == ".": - continue - if part == "..": - if out.parts and out.parts[-1] not in ("..", ""): - out = out.parent - else: - out = out / part - continue - out = out / part - return out - - -def _apply_update_chunks(text: str, chunks: list[_UpdateChunk]) -> str: - lines = text.split("\n") - if lines and lines[-1] == "": - lines.pop() - for chunk in chunks: - if chunk.change_context: - idx = _seek(lines, [chunk.change_context], 0, False) - if idx is None: - raise ValueError(f"Failed to find context '{chunk.change_context}'") - start = idx + 1 - else: - start = 0 - if not chunk.old_lines: - insert_at = len(lines) if not lines or lines[-1] != "" else len(lines) - 1 - for i, nl in enumerate(chunk.new_lines): - lines.insert(insert_at + i, nl) - continue - found = _seek(lines, chunk.old_lines, start, chunk.is_end_of_file) - if found is None and chunk.old_lines and chunk.old_lines[-1] == "": - found = _seek(lines, chunk.old_lines[:-1], start, chunk.is_end_of_file) - new_lines = ( - chunk.new_lines[:-1] - if chunk.new_lines and chunk.new_lines[-1] == "" - else chunk.new_lines - ) - else: - new_lines = chunk.new_lines - if found is None: - raise ValueError("Failed to find expected lines in update hunk") - del lines[found : found + len(chunk.old_lines)] - for i, nl in enumerate(new_lines): - lines.insert(found + i, nl) - if not lines or lines[-1] != "": - lines.append("") - return "\n".join(lines) - - -def _seek(lines: list[str], pattern: list[str], start: int, eof: bool) -> int | None: - if not pattern: - return start - search_start = ( - max(0, len(lines) - len(pattern)) - if eof and len(lines) >= len(pattern) - else start - ) - for i in range(search_start, len(lines) - len(pattern) + 1): - if lines[i : i + len(pattern)] == pattern: - return i - if all( - lines[i + j].rstrip() == pattern[j].rstrip() for j in range(len(pattern)) - ): - return i - if all(lines[i + j].strip() == pattern[j].strip() for j in range(len(pattern))): - return i - return None - - -def _parse_patch(patch: str) -> list[tuple]: - lines = patch.strip().splitlines() - if not lines or lines[0].strip() != "*** Begin Patch": - raise ValueError("The first line of the patch must be '*** Begin Patch'") - if lines[-1].strip() != "*** End Patch": - raise ValueError("The last line of the patch must be '*** End Patch'") - hunks: list[tuple] = [] - i = 1 - while i < len(lines) - 1: - line = lines[i] - stripped = line.strip() - if stripped.startswith("*** Add File: "): - path = stripped[len("*** Add File: ") :].strip() - i += 1 - content_lines: list[str] = [] - while i < len(lines) - 1 and lines[i].startswith("+"): - content_lines.append(lines[i][1:]) - i += 1 - content = "\n".join(content_lines) - if content and not content.endswith("\n"): - content += "\n" - hunks.append(("add", path, content)) - continue - if stripped.startswith("*** Delete File: "): - path = stripped[len("*** Delete File: ") :].strip() - hunks.append(("delete", path)) - i += 1 - continue - if stripped.startswith("*** Update File: "): - path = stripped[len("*** Update File: ") :].strip() - i += 1 - move_to: str | None = None - if i < len(lines) - 1 and lines[i].strip().startswith("*** Move to: "): - move_to = lines[i].strip()[len("*** Move to: ") :].strip() - i += 1 - chunks: list[_UpdateChunk] = [] - while i < len(lines) - 1 and not lines[i].strip().startswith("***"): - line = lines[i] - if line.strip() == "*** End of File": - if chunks: - chunks[-1].is_end_of_file = True - i += 1 - continue - if line.startswith("@@"): - ctx = line[2:].strip() or None - chunks.append( - _UpdateChunk(old_lines=[], new_lines=[], change_context=ctx) - ) - i += 1 - continue - if not chunks: - chunks.append(_UpdateChunk(old_lines=[], new_lines=[])) - if line.startswith(" "): - chunks[-1].old_lines.append(line[1:]) - chunks[-1].new_lines.append(line[1:]) - elif line.startswith("-"): - chunks[-1].old_lines.append(line[1:]) - elif line.startswith("+"): - chunks[-1].new_lines.append(line[1:]) - i += 1 - hunks.append(("update", path, chunks, move_to)) - continue - i += 1 - return hunks diff --git a/python/pulsing/forge/patch_invocation.py b/python/pulsing/forge/patch_invocation.py deleted file mode 100644 index 272c691d2..000000000 --- a/python/pulsing/forge/patch_invocation.py +++ /dev/null @@ -1,124 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""apply_patch argv detection and pre-apply verification.""" - -from __future__ import annotations - -from dataclasses import dataclass -from enum import Enum -from pathlib import Path -from typing import Any - -from pulsing.forge.patch_apply import ( - _normalize_lexically, - _resolve_patch_path, - apply_patch_to_fs, -) - -APPLY_PATCH_COMMANDS = frozenset({"apply_patch", "applypatch"}) - - -class MaybeApplyPatch(str, Enum): - BODY = "body" - IMPLICIT = "implicit" - NOT = "not" - - -@dataclass -class ParsedPatch: - patch: str - workdir: str | None = None - - -def maybe_parse_apply_patch( - argv: list[str], -) -> tuple[MaybeApplyPatch, ParsedPatch | None]: - if len(argv) == 1 and _looks_like_patch(argv[0]): - return MaybeApplyPatch.IMPLICIT, None - if len(argv) == 2 and argv[0] in APPLY_PATCH_COMMANDS: - return MaybeApplyPatch.BODY, ParsedPatch(patch=argv[1]) - if len(argv) == 3 and _is_shell(argv[0], argv[1]): - if _looks_like_patch(argv[2]): - return MaybeApplyPatch.IMPLICIT, None - parsed = _extract_from_script(argv[2]) - if parsed: - return MaybeApplyPatch.BODY, parsed - return MaybeApplyPatch.NOT, None - - -def apply_parsed_patch(parsed: ParsedPatch, cwd: Path) -> str: - effective = _resolve_effective_cwd(cwd, parsed.workdir) - _verify_patch_text(parsed.patch, effective, cwd) - return apply_patch_to_fs(parsed.patch, effective, root=cwd) - - -def _resolve_effective_cwd(cwd: Path, workdir: str | None) -> Path: - if not workdir: - return _normalize_lexically(cwd) - return _resolve_patch_path(workdir, cwd, cwd) - - -def _verify_patch_text(patch: str, base: Path, root: Path) -> None: - for line in patch.splitlines(): - stripped = line.strip() - if stripped.startswith("*** Add File: "): - rel = stripped.removeprefix("*** Add File: ").strip() - target = _resolve_patch_path(rel, base, root) - if target.exists(): - raise ValueError(f"add file blocked: {target} already exists") - if stripped.startswith("*** Delete File: "): - rel = stripped.removeprefix("*** Delete File: ").strip() - target = _resolve_patch_path(rel, base, root) - if not target.is_file(): - raise ValueError(f"file not found: {target}") - if stripped.startswith("*** Update File: "): - rel = stripped.removeprefix("*** Update File: ").strip() - target = _resolve_patch_path(rel, base, root) - if not target.is_file(): - raise ValueError(f"file not found: {target}") - if stripped.startswith("*** Move to: "): - rel = stripped.removeprefix("*** Move to: ").strip() - _resolve_patch_path(rel, base, root) - - -def _looks_like_patch(text: str) -> bool: - return "*** Begin Patch" in text and "*** End Patch" in text - - -def _is_shell(shell: str, flag: str) -> bool: - name = Path(shell).stem.lower() - return name in {"sh", "bash", "zsh"} and flag in {"-c", "-lc"} - - -def _extract_from_script(script: str) -> ParsedPatch | None: - trimmed = script.strip() - idx = trimmed.find("apply_patch") - if idx < 0: - idx = trimmed.find("applypatch") - if idx < 0: - return None - prefix, rest = trimmed[:idx], trimmed[idx:] - workdir = None - pfx = prefix.strip() - if pfx.startswith("cd ") and pfx.endswith("&&"): - workdir = pfx[3:-2].strip().strip("'\"") - if "<<" not in rest: - return None - after = rest.split("<<", 1)[1].lstrip() - if after.startswith("'"): - end = after.find("'", 1) - delim = after[1:end] - body_start = after.find("\n", end) + 1 - elif after.startswith('"'): - end = after.find('"', 1) - delim = after[1:end] - body_start = after.find("\n", end) + 1 - else: - end = next((i for i, c in enumerate(after) if c.isspace()), len(after)) - delim = after[:end] - body_start = after.find("\n", end) + 1 - region = after[body_start:] - marker = f"\n{delim}" - end_idx = region.rfind(marker) - if end_idx < 0: - return None - return ParsedPatch(patch=region[:end_idx], workdir=workdir) diff --git a/python/pulsing/forge/permissions.py b/python/pulsing/forge/permissions.py deleted file mode 100644 index 1b627bc8f..000000000 --- a/python/pulsing/forge/permissions.py +++ /dev/null @@ -1,110 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge permission / exec-approval helpers (Codex-aligned).""" - -from __future__ import annotations - -import json -from collections.abc import Callable -from typing import Any, Literal - -ExecApprovalDecision = Literal[ - "approved", - "denied", - "approved_for_session", - "approved_with_amendment", - "abort", -] - -CallbackDecision = Literal["allow", "deny", "once"] - - -def is_permission_section_empty(value: Any) -> bool: - if value is None: - return True - if not isinstance(value, dict): - return False - if not value: - return True - if len(value) == 1 and "enabled" in value and value.get("enabled") is None: - return True - entries = value.get("entries") - if isinstance(entries, list) and not entries: - return True - read = value.get("read") - write = value.get("write") - read_empty = not isinstance(read, list) or not read - write_empty = not isinstance(write, list) or not write - if "read" in value or "write" in value: - return read_empty and write_empty - return False - - -def is_permission_profile_effectively_empty(perms: dict[str, Any] | None) -> bool: - if not perms: - return True - net = perms.get("network") - fs = perms.get("file_system") - net_empty = net is None or is_permission_section_empty(net) - fs_empty = fs is None or is_permission_section_empty(fs) - return net_empty and fs_empty - - -class PermissionChecker: - """Shell exec approval for Forge host/worker bridges.""" - - def __init__( - self, - *, - auto_approve: bool = False, - prompt_callback: Callable[[str, str], CallbackDecision] | None = None, - exec_approval_callback: ( - Callable[[dict[str, Any]], ExecApprovalDecision] | None - ) = None, - permissions_callback: Callable[[dict[str, Any]], dict[str, Any]] | None = None, - ) -> None: - self._auto_approve = auto_approve - self._prompt_callback = prompt_callback - self._exec_approval_callback = exec_approval_callback - self._permissions_callback = permissions_callback - - @property - def auto_approve(self) -> bool: - return self._auto_approve - - def prompt_exec_approval(self, request: dict[str, Any]) -> ExecApprovalDecision: - if self._auto_approve: - return "approved" - if self._exec_approval_callback is not None: - return self._exec_approval_callback(request) - if self._prompt_callback is not None: - cmd = " ".join(str(x) for x in (request.get("command") or [])) - reason = str(request.get("reason") or request.get("justification") or "") - summary = f"shell exec: {cmd}\n{reason}".strip() - choice = self._prompt_callback("shell_command", summary) - if choice == "allow": - return "approved_with_amendment" - if choice == "once": - return "approved" - return "denied" - return "denied" - - def prompt_request_permissions(self, args: dict[str, Any]) -> dict[str, Any]: - if self._auto_approve: - perms = args.get("permissions") or {} - return { - "permissions": perms, - "scope": "session", - "strict_auto_review": False, - } - if self._permissions_callback is not None: - return self._permissions_callback(args) - if self._prompt_callback is not None: - summary = json.dumps(args, ensure_ascii=False, default=str)[:4000] - choice = self._prompt_callback("request_permissions", summary) - if choice in ("allow", "once"): - return { - "permissions": args.get("permissions") or {}, - "scope": "session", - "strict_auto_review": choice == "allow", - } - return {"permissions": {}, "scope": "turn", "strict_auto_review": False} diff --git a/python/pulsing/forge/repl/__init__.py b/python/pulsing/forge/repl/__init__.py deleted file mode 100644 index c709e82ea..000000000 --- a/python/pulsing/forge/repl/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Interactive Forge session REPL — manual tool drive and trace replay.""" - -from pulsing.forge.repl.session import ForgeReplSession -from pulsing.forge.repl.trace import TraceRecord, load_trace, save_trace - -__all__ = ["ForgeReplSession", "TraceRecord", "load_trace", "save_trace"] diff --git a/python/pulsing/forge/repl/__main__.py b/python/pulsing/forge/repl/__main__.py deleted file mode 100644 index 17fd4d2c9..000000000 --- a/python/pulsing/forge/repl/__main__.py +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -from pulsing.forge.repl.cli import main - -if __name__ == "__main__": - main() diff --git a/python/pulsing/forge/repl/cli.py b/python/pulsing/forge/repl/cli.py deleted file mode 100644 index 9ec71ffff..000000000 --- a/python/pulsing/forge/repl/cli.py +++ /dev/null @@ -1,126 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""CLI: ``pulsing forge repl`` / ``python -m pulsing.forge.repl``.""" - -from __future__ import annotations - -import argparse -import sys -from pathlib import Path - -from pulsing.forge.repl.rust_dispatch import try_run_rust_repl -from pulsing.forge.repl.session import ForgeReplSession -from pulsing.forge.repl.shell import run_repl - -_PROG = "pulsing forge repl" - - -def build_parser(prog: str = _PROG) -> argparse.ArgumentParser: - p = argparse.ArgumentParser( - prog=prog, - description="Forge session REPL — manual tool calls and trace replay.", - ) - p.add_argument("--cwd", default=".", help="workspace root (default: .)") - p.add_argument( - "--sandbox", - default="off", - choices=("off", "restricted", "bwrap"), - help="sandbox policy", - ) - p.add_argument( - "--dangerously-disable-sandbox", - action="store_true", - help="disable sandbox even when policy is set", - ) - p.add_argument( - "--approve", - choices=("auto", "ask"), - default="auto", - help="exec / user_input / plugin approval (default: auto)", - ) - p.add_argument("--trace", help="JSONL trace to load for replay") - p.add_argument( - "--record", - help="append tool calls / events to JSONL while in REPL", - ) - p.add_argument( - "--fork", - type=int, - metavar="N", - help="after loading --trace, replay tool calls 1..N then enter interactive", - ) - p.add_argument( - "--replay-all", - action="store_true", - help="with --trace: run all tool calls then exit (no interactive)", - ) - p.add_argument( - "--dry-run", - action="store_true", - help="with --replay-all: print calls only", - ) - p.add_argument( - "--verify", - action="store_true", - help="with --replay-all: compare results to trace", - ) - p.add_argument( - "--python", - action="store_true", - help="force Python REPL (skip Rust binary even if installed)", - ) - return p - - -def _argv_for_rust(args: argparse.Namespace) -> list[str]: - out: list[str] = [] - if args.cwd != ".": - out.extend(["--cwd", args.cwd]) - if args.sandbox != "off": - out.extend(["--sandbox", args.sandbox]) - if args.dangerously_disable_sandbox: - out.append("--dangerously-disable-sandbox") - if args.approve != "auto": - out.extend(["--approve", args.approve]) - if args.trace: - out.extend(["--trace", args.trace]) - if args.record: - out.extend(["--record", args.record]) - if args.replay_all: - out.append("--replay-all") - if args.dry_run: - out.append("--dry-run") - if args.verify: - out.append("--verify") - return out - - -def main(argv: list[str] | None = None) -> None: - raw = list(argv if argv is not None else sys.argv[1:]) - args = build_parser().parse_args(raw) - - if not args.python and args.fork is None: - rust_argv = _argv_for_rust(args) - code = try_run_rust_repl(rust_argv) - if code is not None: - raise SystemExit(code) - - session = ForgeReplSession( - cwd=Path(args.cwd), - sandbox_policy=args.sandbox, - dangerously_disable_sandbox=args.dangerously_disable_sandbox, - approval_mode=args.approve, - record_path=Path(args.record) if args.record else None, - ) - if args.trace: - session.load_replay_trace(args.trace) - if args.fork is not None and args.trace: - session.fork_trace(args.fork) - if args.replay_all and args.trace: - for line in session.replay_all(dry_run=args.dry_run, verify=args.verify): - print(line) - return - run_repl(session) - - -if __name__ == "__main__": - main() diff --git a/python/pulsing/forge/repl/parse.py b/python/pulsing/forge/repl/parse.py deleted file mode 100644 index 7108aeba0..000000000 --- a/python/pulsing/forge/repl/parse.py +++ /dev/null @@ -1,124 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""REPL line parser — nu-style ``call Tool {json}`` and bare tool invocations.""" - -from __future__ import annotations - -import json -import re -import shlex -from typing import Any - -from pulsing.forge.integrated import FORGE_TOOL_NAMES - -_META_ALIASES = { - "help": "help", - "?": "help", - "h": "help", - "quit": "quit", - "exit": "quit", - "q": "quit", - "tools": "tools", - "ls": "tools", - "plan": "plan", - "session": "session", - "events": "events", - "approve": "approve", - "replay": "replay", - "trace": "trace", - "call": "call", -} - - -def parse_flags(tokens: list[str]) -> dict[str, Any]: - """Parse ``--key value`` / ``--key=value`` (Nushell-style flags, MVP subset).""" - out: dict[str, Any] = {} - i = 0 - while i < len(tokens): - tok = tokens[i] - if not tok.startswith("--"): - i += 1 - continue - key = tok[2:].split("=", 1)[0] - if "=" in tok: - out[key] = _coerce(tok.split("=", 1)[1]) - i += 1 - continue - if i + 1 < len(tokens) and not tokens[i + 1].startswith("--"): - out[key] = _coerce(tokens[i + 1]) - i += 2 - else: - out[key] = True - i += 1 - return out - - -def _coerce(raw: str) -> Any: - if raw.lower() in ("true", "false"): - return raw.lower() == "true" - try: - return json.loads(raw) - except json.JSONDecodeError: - return raw - - -def parse_json_or_flags(rest: str) -> dict[str, Any]: - rest = rest.strip() - if not rest: - return {} - if rest.startswith("{"): - return dict(json.loads(rest)) - return parse_flags(shlex.split(rest)) - - -def _split_tool_rest(line: str) -> tuple[str, str]: - line = line.strip() - if not line: - return "", "" - tool, _, rest = line.partition(" ") - return tool, rest.strip() - - -def parse_line(line: str) -> tuple[str, dict[str, Any]]: - """Return ``(command, args)`` where command is meta name or ``call``.""" - line = line.strip() - if not line or line.startswith("#"): - return ("noop", {}) - if line.startswith(":"): - parts = shlex.split(line[1:]) - if not parts: - return ("help", {}) - cmd = _META_ALIASES.get(parts[0].lower(), parts[0].lower()) - return (cmd, {"rest": parts[1:]}) - - lower = line.lower() - if lower in _META_ALIASES: - return (_META_ALIASES[lower], {"rest": []}) - - if lower.startswith("approve "): - return ("approve", {"rest": shlex.split(line)[1:]}) - - if lower.startswith("replay"): - return ("replay", {"rest": shlex.split(line)[1:]}) - - if lower.startswith("trace "): - return ("trace", {"rest": shlex.split(line)[1:]}) - - if line.lower().startswith("call "): - tool, rest = _split_tool_rest(line[5:]) - if not tool: - return ("help", {}) - args = parse_json_or_flags(rest) - return ("call", {"tool": tool, "arguments": args}) - - tool, rest = _split_tool_rest(line) - if tool in FORGE_TOOL_NAMES: - args = parse_json_or_flags(rest) - return ("call", {"tool": tool, "arguments": args}) - - # ``tool Read ...`` alias - m = re.match(r"tool\s+(\S+)(?:\s+(.*))?$", line, re.I) - if m: - args = parse_json_or_flags(m.group(2) or "") - return ("call", {"tool": m.group(1), "arguments": args}) - - return ("unknown", {"line": line}) diff --git a/python/pulsing/forge/repl/render.py b/python/pulsing/forge/repl/render.py deleted file mode 100644 index 4528fba2b..000000000 --- a/python/pulsing/forge/repl/render.py +++ /dev/null @@ -1,21 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Nushell-inspired fixed-width table rendering (no extra deps).""" - -from __future__ import annotations - - -def render_table(headers: list[str], rows: list[list[str]]) -> str: - if not rows: - return "(empty)" - widths = [len(h) for h in headers] - for row in rows: - for i, cell in enumerate(row): - if i < len(widths): - widths[i] = max(widths[i], len(cell)) - sep = " │ " - header_line = sep.join(h.ljust(widths[i]) for i, h in enumerate(headers)) - rule = "─┼─".join("─" * w for w in widths) - body = [ - sep.join(row[i].ljust(widths[i]) for i in range(len(headers))) for row in rows - ] - return "\n".join([header_line, rule, *body]) diff --git a/python/pulsing/forge/repl/rust_dispatch.py b/python/pulsing/forge/repl/rust_dispatch.py deleted file mode 100644 index 5c35ee007..000000000 --- a/python/pulsing/forge/repl/rust_dispatch.py +++ /dev/null @@ -1,45 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Locate and run the Rust ``pulsing-forge-repl`` binary.""" - -from __future__ import annotations - -import os -import shutil -import subprocess -import sys -from pathlib import Path - - -def _repo_root() -> Path: - return Path(__file__).resolve().parents[4] - - -def find_forge_repl_binary() -> Path | None: - override = os.environ.get("PULSING_FORGE_REPL_BIN") - if override: - path = Path(override) - if path.is_file(): - return path - - for name in ("pulsing-forge-repl", "pforge"): - found = shutil.which(name) - if found: - return Path(found) - - root = _repo_root() - for rel in ("target/debug/pulsing-forge-repl", "target/release/pulsing-forge-repl"): - candidate = root / rel - if candidate.is_file(): - return candidate - return None - - -def try_run_rust_repl(argv: list[str]) -> int | None: - """Run Rust REPL if binary exists. Returns exit code, or None to use Python.""" - if os.environ.get("PULSING_FORGE_REPL_PYTHON", "").lower() in ("1", "true", "yes"): - return None - binary = find_forge_repl_binary() - if binary is None: - return None - completed = subprocess.run([str(binary), *argv], check=False) - return completed.returncode diff --git a/python/pulsing/forge/repl/session.py b/python/pulsing/forge/repl/session.py deleted file mode 100644 index 8e836b807..000000000 --- a/python/pulsing/forge/repl/session.py +++ /dev/null @@ -1,266 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge REPL session — LocalToolRuntime + trace recording.""" - -from __future__ import annotations - -import json -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any, Literal - -from pulsing.forge.events import ForgeEvent -from pulsing.forge.integrated import FORGE_TOOL_NAMES -from pulsing.forge.p2p_session import P2PToolSession -from pulsing.forge.result import ToolResult -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.session import PlanItem, StepStatus, UpdatePlanArgs -from pulsing.forge.repl.trace import TraceLog, TraceRecord, load_trace, save_trace - -ApprovalMode = Literal["auto", "ask"] - - -@dataclass -class ReplToolSession(P2PToolSession): - """In-process session with REPL-friendly approval hooks.""" - - approval_mode: ApprovalMode = "auto" - repl_input: Any = field(default=None, repr=False) - - def request_user_input(self, arguments: dict[str, Any]) -> dict[str, Any]: - from pulsing.forge.session_input import validate_request_user_input - - validate_request_user_input(arguments) - self._send( - ForgeEvent( - kind="user_input_request", - payload=dict(arguments), - ) - ) - if self.approval_mode == "auto": - questions = arguments.get("questions") or [] - if questions and isinstance(questions[0], dict): - opts = questions[0].get("options") or [] - if opts: - return { - "answers": { - questions[0].get("id", "q0"): opts[0].get("label", opts[0]) - } - } - return {"answers": {}} - if self.repl_input is not None: - return self.repl_input( - f"user_input: {json.dumps(arguments, ensure_ascii=False)[:200]}" - ) - return super().request_user_input(arguments) - - def request_plugin_install(self, args: dict[str, Any]) -> bool: - if self.approval_mode == "auto": - return True - if self.repl_input is not None: - ans = self.repl_input(f"plugin_install {args.get('tool_id')}? [y/N] ") - return str(ans).strip().lower() in ("y", "yes", "allow") - return False - - -@dataclass -class ForgeReplSession: - cwd: Path - sandbox_policy: str = "off" - dangerously_disable_sandbox: bool = False - approval_mode: ApprovalMode = "auto" - record_path: Path | None = None - - session: ReplToolSession = field(init=False) - runtime: LocalToolRuntime = field(init=False) - trace: TraceLog = field(init=False) - events: list[ForgeEvent] = field(init=False, default_factory=list) - _replay_index: int = field(init=False, default=0) - _loaded_trace: TraceLog | None = field(init=False, default=None) - - def __post_init__(self) -> None: - self.cwd = Path(self.cwd).resolve() - self.session = ReplToolSession(approval_mode=self.approval_mode) - self.session.repl_input = self._prompt - self.runtime = LocalToolRuntime( - cwd=str(self.cwd), - sandbox_policy=self.sandbox_policy, - dangerously_disable_sandbox=self.dangerously_disable_sandbox, - session=self.session, - ) - self.trace = TraceLog() - self.events = [] - - def load_replay_trace(self, path: str | Path) -> int: - self._loaded_trace = load_trace(path) - self._replay_index = 0 - return len(self._loaded_trace.tool_calls()) - - def set_approval_mode(self, mode: ApprovalMode) -> None: - self.approval_mode = mode - self.session.approval_mode = mode - - def _prompt(self, message: str) -> str: - try: - return input(f"{message}").strip() - except EOFError: - return "" - - def _capture_events(self) -> None: - for ev in self.session.drain_pending(): - self.events.append(ev) - if self.record_path is not None: - self.trace.append( - TraceRecord( - seq=0, - kind="forge_event", - event=ev.to_dict(), - ) - ) - - def _session_snapshot(self) -> dict[str, Any]: - return { - "cwd": str(self.cwd), - "sandbox_policy": self.sandbox_policy, - "plan": [p.to_dict() for p in self.session.plan], - "new_context_requested": self.session.new_context_requested, - "tokens_remaining": self.session.tokens_remaining(), - } - - def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> ToolResult: - args = dict(arguments or {}) - result = self.runtime.call_tool(name, args) - self._capture_events() - if self.record_path is not None: - self.trace.append( - TraceRecord( - seq=0, - kind="tool_call", - tool=name, - arguments=args, - result=result.to_dict(), - ) - ) - save_trace(self.record_path, self.trace) - return result - - def replay_step( - self, - *, - dry_run: bool = False, - verify: bool = False, - ) -> str: - if self._loaded_trace is None: - return "no trace loaded; start with --trace FILE" - calls = self._loaded_trace.tool_calls() - if self._replay_index >= len(calls): - return "replay complete" - rec = calls[self._replay_index] - self._replay_index += 1 - tool = rec.tool or "?" - args = dict(rec.arguments or {}) - if dry_run: - return ( - f"dry-run #{rec.seq} call {tool} {json.dumps(args, ensure_ascii=False)}" - ) - out = self.call_tool(tool, args) - if verify and rec.result is not None: - exp_err = bool(rec.result.get("is_error")) - if out.is_error != exp_err: - return ( - f"verify FAIL #{rec.seq} {tool}: is_error expected {exp_err} got {out.is_error}\n" - f"{out.content[:500]}" - ) - if ( - not out.is_error - and rec.result.get("content") - and out.content != rec.result.get("content") - ): - return f"verify WARN #{rec.seq} {tool}: content differs (non-error)" - flag = "ERR" if out.is_error else "ok" - preview = out.content[:400].replace("\n", "\\n") - return f"replay #{rec.seq} {tool} [{flag}] {preview}" - - def replay_all(self, *, dry_run: bool = False, verify: bool = False) -> list[str]: - lines: list[str] = [] - while True: - msg = self.replay_step(dry_run=dry_run, verify=verify) - lines.append(msg) - if "complete" in msg or msg.startswith("no trace"): - break - return lines - - def fork_trace(self, step: int) -> None: - """Apply session snapshots and tool calls from trace up to ``step`` (replay index).""" - if self._loaded_trace is None: - return - self._replay_index = 0 - for rec in self._loaded_trace.records: - if rec.seq > step: - break - if rec.kind == "session" and rec.session: - self._apply_session(rec.session) - elif rec.kind == "tool_call" and rec.seq <= step: - if rec.tool and rec.tool in FORGE_TOOL_NAMES: - self.call_tool(rec.tool, rec.arguments) - self._replay_index += 1 - - def _apply_session(self, snap: dict[str, Any]) -> None: - plan_raw = snap.get("plan") or [] - items = [ - PlanItem( - step=str(p.get("step", "")), status=p.get("status", StepStatus.PENDING) - ) - for p in plan_raw - ] - if items: - self.session.update_plan(UpdatePlanArgs(plan=items)) - if snap.get("new_context_requested"): - self.session.new_context_requested = True - if "tokens_remaining" in snap: - self.session.token_budget = snap.get("tokens_remaining") - - def format_session_table(self) -> str: - from pulsing.forge.repl.render import render_table - - snap = self._session_snapshot() - rows = [[k, str(v)] for k, v in snap.items() if k != "plan"] - if self.session.plan: - rows.append(["plan", f"{len(self.session.plan)} items"]) - rows.append(["approval", self.approval_mode]) - rows.append(["events", str(len(self.events))]) - if self._loaded_trace: - total = len(self._loaded_trace.tool_calls()) - rows.append(["replay", f"{self._replay_index}/{total}"]) - return render_table(["field", "value"], rows) - - def format_plan_table(self) -> str: - from pulsing.forge.repl.render import render_table - - if not self.session.plan: - return "(empty plan)" - rows = [[p.step, str(p.status)] for p in self.session.plan] - return render_table(["step", "status"], rows) - - def format_tools_table(self) -> str: - from pulsing.forge.repl.render import render_table - from pulsing.forge.integrated import FORGE_HOST_TOOL_NAMES - - rows = [ - [name, "host" if name in FORGE_HOST_TOOL_NAMES else "isolated"] - for name in sorted(FORGE_TOOL_NAMES) - ] - return render_table(["tool", "zone"], rows) - - def format_events_table(self, limit: int = 12) -> str: - from pulsing.forge.repl.render import render_table - - recent = self.events[-limit:] - if not recent: - return "(no events)" - rows = [] - for ev in recent: - preview = json.dumps(ev.payload, ensure_ascii=False)[:60] - rows.append([ev.kind, ev.source or "", preview]) - return render_table(["kind", "source", "payload"], rows) diff --git a/python/pulsing/forge/repl/shell.py b/python/pulsing/forge/repl/shell.py deleted file mode 100644 index d53378086..000000000 --- a/python/pulsing/forge/repl/shell.py +++ /dev/null @@ -1,163 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Interactive REPL loop (Nushell-inspired tables + structured commands).""" - -from __future__ import annotations - -import json -import sys -from pathlib import Path -from typing import TextIO - -from pulsing.forge.repl.parse import parse_line -from pulsing.forge.repl.session import ForgeReplSession -from pulsing.forge.repl.trace import save_trace - -_HELP = """ -Forge session REPL — drive ToolRuntime directly (no LLM). - -Invocation (Nushell-style): - call Read {"file_path": "README.md"} - Read --file_path README.md - Glob --pattern "*.py" - -Meta (: prefix or bare keyword): - help | :help this help - tools registered tools (table) - session | plan | events - approve auto|ask - replay [dry] [verify] | replay all - trace save PATH - quit - -Replay: ``pulsing forge repl --trace file.jsonl`` then ``replay`` step-by-step -""" - - -def _prompt(session: ForgeReplSession) -> str: - cwd = session.cwd.name or str(session.cwd) - mode = session.approval_mode[0].upper() - return f"forge ⟨{cwd}⟩ {mode}⟩ " - - -def _print_help(out: TextIO) -> None: - out.write(_HELP.strip() + "\n") - - -def _run_call( - session: ForgeReplSession, tool: str, arguments: dict, out: TextIO -) -> None: - result = session.call_tool(tool, arguments) - payload = { - "tool": tool, - "is_error": result.is_error, - "content": result.content[:2000], - } - if result.structured is not None: - payload["structured"] = result.structured - out.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n") - - -def _handle_meta(session: ForgeReplSession, cmd: str, args: dict, out: TextIO) -> bool: - """Returns False to exit REPL.""" - rest: list[str] = list(args.get("rest") or []) - - if cmd == "help": - _print_help(out) - return True - if cmd == "quit": - return False - if cmd == "tools": - out.write(session.format_tools_table() + "\n") - return True - if cmd == "session": - out.write(session.format_session_table() + "\n") - return True - if cmd == "plan": - out.write(session.format_plan_table() + "\n") - return True - if cmd == "events": - out.write(session.format_events_table() + "\n") - return True - if cmd == "approve": - if not rest: - out.write(f"approval mode: {session.approval_mode}\n") - return True - mode = rest[0].lower() - if mode not in ("auto", "ask"): - out.write("usage: approve auto|ask\n") - return True - session.set_approval_mode(mode) # type: ignore[arg-type] - out.write(f"approval → {mode}\n") - return True - if cmd == "replay": - dry = "dry" in rest - verify = "verify" in rest - if "all" in rest: - for line in session.replay_all(dry_run=dry, verify=verify): - out.write(line + "\n") - return True - out.write(session.replay_step(dry_run=dry, verify=verify) + "\n") - return True - if cmd == "trace": - if not rest: - out.write("usage: trace save PATH | trace show\n") - return True - sub = rest[0].lower() - if sub == "show": - if session.record_path: - out.write( - f"recording → {session.record_path} ({len(session.trace.records)} lines)\n" - ) - else: - out.write("(not recording)\n") - elif sub == "save" and len(rest) > 1: - session.record_path = Path(rest[1]) - save_trace(session.record_path, session.trace) - out.write( - f"saved {len(session.trace.records)} records → {session.record_path}\n" - ) - else: - out.write("usage: trace save PATH | trace show\n") - return True - if cmd == "call" and rest: - from pulsing.forge.repl.parse import parse_json_or_flags - - tool = rest[0] - arguments = parse_json_or_flags(" ".join(rest[1:])) - _run_call(session, tool, arguments, out) - return True - out.write(f"unknown command: {cmd}\n") - return True - - -def run_repl(session: ForgeReplSession, *, stdin=None, stdout=None) -> None: - out: TextIO = stdout or sys.stdout - inp = stdin or sys.stdin - _print_help(out) - if session._loaded_trace is not None: - n = len(session._loaded_trace.tool_calls()) - out.write(f"loaded trace: {n} tool calls (replay / replay all)\n") - - while True: - try: - if inp is sys.stdin: - line = input(_prompt(session)) - else: - line = inp.readline() - if not line: - break - except (EOFError, KeyboardInterrupt): - out.write("\n") - break - - cmd, args = parse_line(line) - if cmd == "noop": - continue - if cmd == "unknown": - out.write(f"unknown: {args.get('line')!r} (help)\n") - continue - if cmd == "call": - _run_call(session, args["tool"], args.get("arguments") or {}, out) - continue - if not _handle_meta(session, cmd, args, out): - break diff --git a/python/pulsing/forge/repl/trace.py b/python/pulsing/forge/repl/trace.py deleted file mode 100644 index 3ac5ea04b..000000000 --- a/python/pulsing/forge/repl/trace.py +++ /dev/null @@ -1,77 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""JSONL trace format for Forge session replay.""" - -from __future__ import annotations - -import json -from dataclasses import asdict, dataclass, field -from pathlib import Path -from typing import Any, Literal - -TraceKind = Literal["tool_call", "forge_event", "session", "meta"] - - -@dataclass -class TraceRecord: - seq: int - kind: TraceKind - tool: str | None = None - arguments: dict[str, Any] | None = None - result: dict[str, Any] | None = None - event: dict[str, Any] | None = None - session: dict[str, Any] | None = None - meta: dict[str, Any] | None = None - - def to_dict(self) -> dict[str, Any]: - out = asdict(self) - return {k: v for k, v in out.items() if v is not None} - - @classmethod - def from_dict(cls, raw: dict[str, Any]) -> TraceRecord: - return cls( - seq=int(raw.get("seq", 0)), - kind=str(raw.get("kind", "meta")), # type: ignore[arg-type] - tool=raw.get("tool"), - arguments=dict(raw.get("arguments") or {}) or None, - result=dict(raw.get("result") or {}) or None, - event=dict(raw.get("event") or {}) or None, - session=dict(raw.get("session") or {}) or None, - meta=dict(raw.get("meta") or {}) or None, - ) - - -@dataclass -class TraceLog: - records: list[TraceRecord] = field(default_factory=list) - _next_seq: int = 1 - - def append(self, record: TraceRecord) -> None: - if record.seq <= 0: - record.seq = self._next_seq - self._next_seq += 1 - else: - self._next_seq = max(self._next_seq, record.seq + 1) - self.records.append(record) - - def tool_calls(self) -> list[TraceRecord]: - return [r for r in self.records if r.kind == "tool_call"] - - -def load_trace(path: str | Path) -> TraceLog: - log = TraceLog() - text = Path(path).read_text(encoding="utf-8") - for line in text.splitlines(): - line = line.strip() - if not line or line.startswith("#"): - continue - log.append(TraceRecord.from_dict(json.loads(line))) - if log.records: - log._next_seq = max(r.seq for r in log.records) + 1 - return log - - -def save_trace(path: str | Path, log: TraceLog) -> None: - p = Path(path) - p.parent.mkdir(parents=True, exist_ok=True) - lines = [json.dumps(r.to_dict(), ensure_ascii=False) for r in log.records] - p.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8") diff --git a/python/pulsing/forge/result.py b/python/pulsing/forge/result.py deleted file mode 100644 index 9df8217a4..000000000 --- a/python/pulsing/forge/result.py +++ /dev/null @@ -1,28 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Picklable tool call result.""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Any - - -@dataclass -class ToolResult: - content: str - is_error: bool = False - structured: dict[str, Any] | None = field(default=None) - - def to_dict(self) -> dict[str, Any]: - out: dict[str, Any] = {"content": self.content, "is_error": self.is_error} - if self.structured is not None: - out["structured"] = self.structured - return out - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ToolResult: - return cls( - content=str(data.get("content") or ""), - is_error=bool(data.get("is_error", False)), - structured=data.get("structured"), - ) diff --git a/python/pulsing/forge/runtime.py b/python/pulsing/forge/runtime.py deleted file mode 100644 index b0c427be7..000000000 --- a/python/pulsing/forge/runtime.py +++ /dev/null @@ -1,67 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""In-process tool runtime — dispatches calls within a Forge environment.""" - -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.discovery.catalog import ToolCatalog -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.result import ToolResult -from pulsing.forge.session import LocalToolSession, NullToolSession, ToolSession - - -class LocalToolRuntime: - """Framework-agnostic local tool dispatch.""" - - def __init__( - self, - *, - cwd: str = ".", - sandbox_policy: str = "off", - dangerously_disable_sandbox: bool = False, - session: ToolSession | None = None, - tool_catalog: ToolCatalog | None = None, - ) -> None: - catalog = tool_catalog or ToolCatalog() - if tool_catalog is None: - catalog.load_codex_plugins() - self._ctx = ToolCallContext( - cwd=Path(cwd), - sandbox_policy=sandbox_policy, - dangerously_disable_sandbox=dangerously_disable_sandbox, - session=session or LocalToolSession(), - tool_catalog=catalog, - ) - - @property - def context(self) -> ToolCallContext: - return self._ctx - - @property - def session(self) -> ToolSession: - return self._ctx.session_nonnull - - def set_code_mode(self, code_mode: Any) -> None: - self._ctx.code_mode = code_mode - - def close(self) -> None: - """Kill background exec sessions (PTY/subprocess) — avoid orphaned children.""" - self._ctx.exec.stop_all() - - def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> ToolResult: - return dispatch_tool(name, dict(arguments or {}), ctx=self._ctx) - - async def acall_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> ToolResult: - return self.call_tool(name, arguments) - - def tool_names(self) -> list[str]: - from pulsing.forge.integrated import FORGE_TOOL_NAMES - - return sorted(FORGE_TOOL_NAMES) diff --git a/python/pulsing/forge/rust_runtime.py b/python/pulsing/forge/rust_runtime.py deleted file mode 100644 index 5e8eeedbe..000000000 --- a/python/pulsing/forge/rust_runtime.py +++ /dev/null @@ -1,96 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Rust-native Forge runtime (``pulsing._core.ForgeRuntime``) with Python fallback.""" - -from __future__ import annotations - -from typing import Any, Callable - -from pulsing.forge.events import ForgeEvent -from pulsing.forge.result import ToolResult - -try: - from pulsing._core import ForgeRuntime as _RustForgeRuntime - - RUST_FORGE_AVAILABLE = True -except ImportError: - _RustForgeRuntime = None # type: ignore[misc, assignment] - RUST_FORGE_AVAILABLE = False - - -def rust_forge_available() -> bool: - return RUST_FORGE_AVAILABLE - - -class RustForgeAdapter: - """Thin wrapper around ``pulsing._core.ForgeRuntime``.""" - - def __init__(self, inner: Any) -> None: - self._inner = inner - - @classmethod - def create( - cls, - *, - cwd: str, - sandbox_policy: str = "off", - dangerously_disable_sandbox: bool = False, - event_callback: Callable[[dict[str, Any]], None] | None = None, - user_input_callback: Callable[[dict[str, Any]], dict[str, Any]] | None = None, - exec_approval_callback: Callable[[dict[str, Any]], str] | None = None, - request_permissions_callback: ( - Callable[[dict[str, Any]], dict[str, Any]] | None - ) = None, - tokens_remaining_callback: Callable[[], int | None] | None = None, - plugin_install_callback: Callable[[dict[str, Any]], bool | str] | None = None, - auto_approve: bool = False, - start_mcp: bool = True, - ) -> RustForgeAdapter: - if not RUST_FORGE_AVAILABLE: - raise RuntimeError( - "Rust ForgeRuntime is not available; rebuild with maturin develop" - ) - rt = _RustForgeRuntime( - cwd, - sandbox_policy, - dangerously_disable_sandbox, - auto_approve, - event_callback, - user_input_callback, - exec_approval_callback, - request_permissions_callback, - tokens_remaining_callback, - plugin_install_callback, - start_mcp, - ) - return cls(rt) - - def tool_names(self) -> list[str]: - return list(self._inner.tool_names()) - - def refresh_mcp(self) -> None: - self._inner.refresh_mcp() - - def mcp_tool_names(self) -> list[str]: - if hasattr(self._inner, "mcp_tool_names"): - return list(self._inner.mcp_tool_names()) - return [] - - def mcp_tool_specs(self) -> list[dict[str, Any]]: - if hasattr(self._inner, "mcp_tool_specs"): - raw = self._inner.mcp_tool_specs() - return [dict(item) for item in raw] - return [] - - def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> ToolResult: - raw = self._inner.call_tool(name, dict(arguments or {})) - return ToolResult( - content=str(raw.get("content", "")), - is_error=bool(raw.get("is_error")), - structured=raw.get("structured"), - ) - - -def forge_event_dict(event: ForgeEvent) -> dict[str, Any]: - return event.to_dict() diff --git a/python/pulsing/forge/sandbox.py b/python/pulsing/forge/sandbox.py deleted file mode 100644 index 2b298d96f..000000000 --- a/python/pulsing/forge/sandbox.py +++ /dev/null @@ -1,95 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Bash sandbox strategies (aligned with Codex/Craft MVP).""" - -from __future__ import annotations - -import os -import shutil -from pathlib import Path - - -def normalize_policy(raw: str | None) -> str: - p = (raw or "off").strip().lower() - if p in ("0", "false", "none", ""): - return "off" - if p not in ("off", "restricted", "bwrap"): - return "off" - return p - - -def build_bash_exec( - command: str, - *, - cwd: str | None, - policy: str, - dangerously_disable_sandbox: bool = False, - timeout: int, - login: bool = False, -) -> tuple[list[str], dict[str, str] | None, str]: - """Build argv/env for `command` under `policy`. - - `login` requests login-shell semantics (`bash -l`, profile sourcing) - instead of a plain `-c` invocation. It must never disable the sandbox - wrapper itself; only `dangerously_disable_sandbox` may do that, and - callers are expected to gate it behind approval. - """ - _ = timeout - wd = str(Path(cwd or ".").resolve()) - pol = "off" if dangerously_disable_sandbox else normalize_policy(policy) - shell_flag = "-lc" if login else "-c" - - if pol == "off": - argv = ["bash", "-lc", command] if login else ["/bin/sh", "-c", command] - return (argv, None, "subprocess shell (sandbox=off)") - - if pol == "bwrap" and shutil.which("bwrap"): - argv: list[str] = [ - "bwrap", - "--die-with-parent", - "--unshare-pid", - "--tmpfs", - "/tmp", - "--proc", - "/proc", - "--dev", - "/dev", - "--ro-bind", - "/usr", - "/usr", - "--ro-bind", - "/bin", - "/bin", - "--ro-bind", - "/lib", - "/lib", - ] - if Path("/lib64").is_dir(): - argv.extend(["--ro-bind", "/lib64", "/lib64"]) - argv.extend( - [ - "--bind", - wd, - "/work", - "--chdir", - "/work", - "bash", - shell_flag, - command, - ], - ) - return (argv, None, "bubblewrap (minimal profile; Linux)") - - env = { - "HOME": os.environ.get("HOME", "/tmp"), - "PATH": "/usr/bin:/bin:/usr/local/bin", - "LANG": os.environ.get("LANG", "C.UTF-8"), - "USER": os.environ.get("USER", "user"), - } - env_argv = ["env", "-i", *[f"{k}={v}" for k, v in env.items()]] - if login: - argv = [*env_argv, "bash", "-lc", command] - label = "restricted env (env -i + bash -l)" - else: - argv = [*env_argv, "bash", "--norc", "--noprofile", "-c", command] - label = "restricted env (env -i + bash --norc)" - return (argv, env, label) diff --git a/python/pulsing/forge/session.py b/python/pulsing/forge/session.py deleted file mode 100644 index 9781f8b3e..000000000 --- a/python/pulsing/forge/session.py +++ /dev/null @@ -1,162 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Session / plan abstractions for Pulsing Forge.""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from enum import Enum -from typing import Any, Callable, Protocol - - -class StepStatus(str, Enum): - PENDING = "pending" - IN_PROGRESS = "in_progress" - COMPLETED = "completed" - - -@dataclass -class PlanItem: - step: str - status: StepStatus | str - - def to_dict(self) -> dict[str, str]: - status = ( - self.status.value - if isinstance(self.status, StepStatus) - else str(self.status) - ) - return {"step": self.step, "status": status} - - -@dataclass -class UpdatePlanArgs: - plan: list[PlanItem] - explanation: str | None = None - - @classmethod - def from_dict(cls, raw: dict[str, Any]) -> UpdatePlanArgs: - """Parse `update_plan` arguments, mirroring Codex's `UpdatePlanArgs` - (vendor/codex-rs/protocol/src/plan_tool.rs): `plan` and each item's - `step`/`status` are required; `status` must be a known enum value. - """ - if not isinstance(raw, dict): - raise TypeError("update_plan arguments must be an object") - unknown = set(raw) - {"plan", "explanation"} - if unknown: - names = ", ".join(sorted(unknown)) - raise ValueError(f"unknown field(s): {names}") - - if "plan" not in raw: - raise ValueError("missing required field 'plan'") - plan_raw = raw["plan"] - if not isinstance(plan_raw, list): - raise ValueError("field 'plan' must be a list") - - items: list[PlanItem] = [] - for idx, item in enumerate(plan_raw): - if not isinstance(item, dict): - raise ValueError(f"plan[{idx}] must be an object") - item_unknown = set(item) - {"step", "status"} - if item_unknown: - names = ", ".join(sorted(item_unknown)) - raise ValueError(f"plan[{idx}] has unknown field(s): {names}") - if "step" not in item: - raise ValueError(f"plan[{idx}] missing required field 'step'") - step = item["step"] - if not isinstance(step, str): - raise ValueError(f"plan[{idx}].step must be a string") - if "status" not in item: - raise ValueError(f"plan[{idx}] missing required field 'status'") - try: - status = StepStatus(item["status"]) - except ValueError: - valid = ", ".join(s.value for s in StepStatus) - raise ValueError( - f"plan[{idx}].status must be one of [{valid}], got {item['status']!r}" - ) from None - items.append(PlanItem(step=step, status=status)) - - in_progress = sum(1 for item in items if item.status == StepStatus.IN_PROGRESS) - if in_progress > 1: - raise ValueError( - 'update_plan allows at most one step with status "in_progress"' - ) - - explanation = raw.get("explanation") - if explanation is not None and not isinstance(explanation, str): - raise ValueError("field 'explanation' must be a string") - return cls(plan=items, explanation=explanation) - - -class ToolSession(Protocol): - def update_plan(self, args: UpdatePlanArgs) -> None: ... - - def request_new_context(self) -> None: ... - - def tokens_remaining(self) -> int | None: ... - - def request_user_input(self, arguments: dict[str, Any]) -> dict[str, Any]: ... - - def request_plugin_install(self, args: dict[str, Any]) -> bool: ... - - def on_exec_output_delta(self, delta: Any) -> None: ... - - -@dataclass -class LocalToolSession: - """Default in-process session store for local tool runs.""" - - token_budget: int | None = None - plan: list[PlanItem] = field(default_factory=list) - new_context_requested: bool = False - user_input: Callable[[dict[str, Any]], dict[str, Any]] | None = None - plugin_install: Callable[[dict[str, Any]], bool] | None = None - exec_deltas: list[Any] = field(default_factory=list) - - def update_plan(self, args: UpdatePlanArgs) -> None: - self.plan = list(args.plan) - - def request_new_context(self) -> None: - self.new_context_requested = True - - def tokens_remaining(self) -> int | None: - return self.token_budget - - def request_user_input(self, arguments: dict[str, Any]) -> dict[str, Any]: - if self.user_input is None: - raise RuntimeError( - "request_user_input is not configured on this ToolSession" - ) - return self.user_input(arguments) - - def request_plugin_install(self, args: dict[str, Any]) -> bool: - if self.plugin_install is None: - raise RuntimeError( - "request_plugin_install is not configured on this ToolSession" - ) - return self.plugin_install(args) - - def on_exec_output_delta(self, delta: Any) -> None: - self.exec_deltas.append(delta) - - -class NullToolSession: - def update_plan(self, args: UpdatePlanArgs) -> None: - del args - - def request_new_context(self) -> None: - return None - - def tokens_remaining(self) -> int | None: - return None - - def request_user_input(self, arguments: dict[str, Any]) -> dict[str, Any]: - del arguments - raise RuntimeError("request_user_input is not available in this runtime") - - def request_plugin_install(self, args: dict[str, Any]) -> bool: - del args - raise RuntimeError("request_plugin_install is not available in this runtime") - - def on_exec_output_delta(self, delta: Any) -> None: - del delta diff --git a/python/pulsing/forge/session_input.py b/python/pulsing/forge/session_input.py deleted file mode 100644 index 6df18b1c2..000000000 --- a/python/pulsing/forge/session_input.py +++ /dev/null @@ -1,212 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex-compatible `request_user_input` validation and resolution.""" - -from __future__ import annotations - -import concurrent.futures -from dataclasses import dataclass -from typing import Any, Callable - -# Codex: core/src/tools/handlers/request_user_input_spec.rs -MIN_AUTO_RESOLUTION_MS = 60_000 -MAX_AUTO_RESOLUTION_MS = 240_000 - - -@dataclass -class RequestUserInputQuestionOption: - label: str - description: str = "" - - -@dataclass -class RequestUserInputQuestion: - id: str - header: str - question: str - is_other: bool = False - is_secret: bool = False - options: list[RequestUserInputQuestionOption] | None = None - - -@dataclass -class RequestUserInputArgs: - questions: list[RequestUserInputQuestion] - auto_resolution_ms: int | None = None - - -def validate_request_user_input(raw: dict[str, Any]) -> RequestUserInputArgs: - questions_raw = raw.get("questions") - if questions_raw is None: - raise ValueError("request_user_input requires at least one question") - if not isinstance(questions_raw, list): - raise ValueError("field 'questions' must be a list") - if not questions_raw: - raise ValueError("request_user_input requires at least one question") - - questions: list[RequestUserInputQuestion] = [] - seen: set[str] = set() - for item in questions_raw: - if not isinstance(item, dict): - raise ValueError("each question must be an object") - qid = str(item.get("id", "")).strip() - if not qid: - raise ValueError("each question requires a non-empty id") - if qid in seen: - raise ValueError(f"duplicate question id {qid!r}") - seen.add(qid) - question = str(item.get("question", "")).strip() - if not question: - raise ValueError(f"question {qid!r} requires non-empty question text") - opts_raw = item.get("options") - options: list[RequestUserInputQuestionOption] | None = None - if opts_raw is not None: - if not isinstance(opts_raw, list) or not opts_raw: - raise ValueError(f"question {qid!r} has empty options array") - options = [] - for opt in opts_raw: - if not isinstance(opt, dict): - raise ValueError(f"question {qid!r} option must be an object") - label = str(opt.get("label", "")).strip() - if not label: - raise ValueError(f"question {qid!r} has option with empty label") - options.append( - RequestUserInputQuestionOption( - label=label, - description=str(opt.get("description", "")), - ) - ) - questions.append( - RequestUserInputQuestion( - id=qid, - header=str(item.get("header", "")), - question=question, - is_other=bool(item.get("isOther") or item.get("is_other")), - is_secret=bool(item.get("isSecret") or item.get("is_secret")), - options=options, - ) - ) - - auto_ms_raw = raw.get("autoResolutionMs", raw.get("auto_resolution_ms")) - if auto_ms_raw is None: - auto_resolution_ms = None - elif isinstance(auto_ms_raw, bool) or not isinstance(auto_ms_raw, int): - raise ValueError(f"autoResolutionMs must be an integer, got {auto_ms_raw!r}") - else: - auto_resolution_ms = normalize_auto_resolution_ms(auto_ms_raw) - return RequestUserInputArgs( - questions=questions, auto_resolution_ms=auto_resolution_ms - ) - - -def normalize_auto_resolution_ms(value: int) -> int: - """Clamp to Codex's [MIN, MAX] auto-resolution window (core/src/tools/handlers/request_user_input_spec.rs).""" - return max(MIN_AUTO_RESOLUTION_MS, min(MAX_AUTO_RESOLUTION_MS, value)) - - -def args_to_payload(args: RequestUserInputArgs) -> dict[str, Any]: - payload: dict[str, Any] = { - "questions": [ - { - "id": q.id, - "header": q.header, - "question": q.question, - "isOther": q.is_other, - "isSecret": q.is_secret, - **( - { - "options": [ - {"label": o.label, "description": o.description} - for o in q.options - ] - } - if q.options - else {} - ), - } - for q in args.questions - ], - } - if args.auto_resolution_ms is not None: - payload["autoResolutionMs"] = args.auto_resolution_ms - return payload - - -def default_auto_answers(args: RequestUserInputArgs) -> dict[str, Any]: - """Pick first option per question (Codex: recommended option should be first).""" - answers: dict[str, Any] = {} - for q in args.questions: - default = q.options[0].label if q.options else "" - answers[q.id] = {"answers": [default]} - return {"answers": answers} - - -def resolve_user_input( - args: RequestUserInputArgs, - *, - auto_approve: bool = False, - user_input_callback: Callable[[dict[str, Any]], dict[str, Any]] | None = None, - prompt_callback: Callable[[str, str], str] | None = None, -) -> dict[str, Any]: - """Resolve `request_user_input` with optional autoResolutionMs timeout → defaults.""" - if auto_approve: - return default_auto_answers(args) - - payload = args_to_payload(args) - ms = args.auto_resolution_ms - - if user_input_callback is not None: - if ms is None: - return user_input_callback(payload) - return _run_with_deadline( - lambda: user_input_callback(payload), - ms, - default=lambda: default_auto_answers(args), - ) - - if ms is not None: - if prompt_callback is not None: - prompt_callback("request_user_input", format_questions_summary(args)) - _run_with_deadline(lambda: _wait_ms(ms), ms + 1000, default=lambda: None) - return default_auto_answers(args) - - if prompt_callback is not None: - summary = format_questions_summary(args) - choice = prompt_callback("request_user_input", summary) - if choice in ("allow", "once"): - return default_auto_answers(args) - raise RuntimeError("user denied request_user_input") - - raise RuntimeError("request_user_input is not configured on this ToolSession") - - -def _run_with_deadline( - fn: Callable[[], Any], timeout_ms: int, *, default: Callable[[], Any] -) -> Any: - """Run `fn` in a worker thread, falling back to `default()` once `timeout_ms` elapses.""" - with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: - future = pool.submit(fn) - try: - return future.result(timeout=timeout_ms / 1000.0) - except concurrent.futures.TimeoutError: - return default() - - -def format_questions_summary(args: RequestUserInputArgs) -> str: - lines = ["request_user_input"] - for q in args.questions: - opts = "" - if q.options: - labels = ", ".join(o.label for o in q.options) - opts = f" [{labels}]" - lines.append(f"- {q.header}: {q.question}{opts}") - if args.auto_resolution_ms is not None: - lines.append( - f"(auto-resolves in {args.auto_resolution_ms}ms with recommended defaults)" - ) - return "\n".join(lines) - - -def _wait_ms(ms: int) -> None: - import time - - time.sleep(ms / 1000.0) diff --git a/python/pulsing/forge/setup_actors.py b/python/pulsing/forge/setup_actors.py deleted file mode 100644 index 9e95802c7..000000000 --- a/python/pulsing/forge/setup_actors.py +++ /dev/null @@ -1,97 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Bootstrap Forge Pulsing actors for a Craft host agent.""" - -from __future__ import annotations - -import asyncio -import logging -from typing import Any - -from pulsing.forge.code_mode.remote import RemoteCodeModeClient -from pulsing.forge.code_mode.registry import ensure_code_cell_registry -from pulsing.forge.event_inbox import ensure_forge_event_inbox -from pulsing.forge.mcp.hub import ensure_mcp_hub -from pulsing.forge.naming import ( - code_cell_registry_name, - forge_event_inbox_name, - mcp_hub_name, -) - -logger = logging.getLogger(__name__) - - -async def ensure_forge_actors(agent: Any) -> None: - """Spawn inbox / MCP hub / code registry and wire host runtime helpers.""" - if getattr(agent, "_forge_actors_ready", False): - return - - host = getattr(agent, "_forge_host_name", None) - if not host: - agent._forge_actors_ready = True - return - - # Independent actor lookups (each with its own resolve timeout) — run - # concurrently so startup latency isn't the sum of all three timeouts. - await asyncio.gather( - _setup_inbox(agent, host), - _setup_mcp_hub(agent), - _setup_code_registry(agent, host), - ) - - try: - from pulsing.forge.mcp.sync import sync_mcp_tools_to_agent - - await sync_mcp_tools_to_agent(agent) - except Exception as exc: - logger.debug("MCP tool sync skipped: %s", exc) - - worker = getattr(agent, "_forge_worker", None) - if worker is not None: - worker._cfg.event_sink_name = agent._event_sink_name - worker._cfg.host_name = host - agent._forge_backend = None - agent._forge_actors_ready = True - logger.debug("forge actors ready host=%s inbox=%s", host, agent._event_sink_name) - - -async def _setup_inbox(agent: Any, host: str) -> None: - try: - inbox = await ensure_forge_event_inbox(host) - agent._forge_inbox_proxy = inbox - agent._event_sink_name = forge_event_inbox_name(host) - except Exception as exc: - logger.warning("forge inbox setup failed, falling back to host tell: %s", exc) - agent._event_sink_name = host - - -async def _setup_mcp_hub(agent: Any) -> None: - ws = getattr(agent, "_workspace_id", None) - if not ws: - return - try: - agent._mcp_hub_name = mcp_hub_name(ws) - await ensure_mcp_hub(ws, cwd=getattr(agent, "_cwd", ".")) - except Exception as exc: - logger.warning("MCP hub setup failed: %s", exc) - agent._mcp_hub_name = None - - -async def _setup_code_registry(agent: Any, host: str) -> None: - try: - registry_name = code_cell_registry_name(host) - agent._code_cell_registry_name = registry_name - await ensure_code_cell_registry(host) - _wire_remote_code_mode(agent, host_name=host, registry_name=registry_name) - except Exception as exc: - logger.warning("code cell registry setup failed: %s", exc) - agent._code_cell_registry_name = None - - -def _wire_remote_code_mode(agent: Any, *, host_name: str, registry_name: str) -> None: - host_rt = getattr(agent, "_forge_host", None) - if host_rt is None: - return - client = RemoteCodeModeClient(registry_name, host_name) - py_rt = getattr(host_rt, "python_runtime", None) - if py_rt is not None and hasattr(py_rt, "set_code_mode"): - py_rt.set_code_mode(client) diff --git a/python/pulsing/forge/tool_calls.py b/python/pulsing/forge/tool_calls.py deleted file mode 100644 index bbc7f5c86..000000000 --- a/python/pulsing/forge/tool_calls.py +++ /dev/null @@ -1,275 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Parse LLM tool calls and build tool-result messages for custom agent frameworks. - -Forge executes tools; this module bridges **provider wire formats** (OpenAI, -Anthropic) and Forge's ``ToolResult`` so Host code stays small. - -Typical loop:: - - calls = extract_tool_calls(assistant_message, provider="openai") - for call in calls: - result = await runtime.call_tool(call.name, call.arguments) - messages.append(openai_tool_message(call.id, result)) -""" - -from __future__ import annotations - -import json -from dataclasses import dataclass -from typing import Any, Literal - -from pulsing.forge.result import ToolResult - -Provider = Literal["auto", "openai", "anthropic"] - - -@dataclass(frozen=True) -class ParsedToolCall: - """Normalized tool invocation from an LLM response.""" - - id: str - name: str - arguments: dict[str, Any] - raw_arguments: str | None = None - - -def parse_tool_arguments(raw: str | dict[str, Any] | None) -> dict[str, Any]: - """Parse tool arguments from JSON string or dict; never raises.""" - if raw is None: - return {} - if isinstance(raw, dict): - return dict(raw) - text = str(raw).strip() - if not text: - return {} - try: - parsed = json.loads(text) - except json.JSONDecodeError: - return {} - return dict(parsed) if isinstance(parsed, dict) else {} - - -def extract_tool_calls_openai(message: dict[str, Any]) -> list[ParsedToolCall]: - """Extract from an OpenAI-style assistant message (``tool_calls`` field).""" - out: list[ParsedToolCall] = [] - for entry in message.get("tool_calls") or []: - if not isinstance(entry, dict): - continue - fn = entry.get("function") or {} - if not isinstance(fn, dict): - fn = {} - raw_args = fn.get("arguments", "") - out.append( - ParsedToolCall( - id=str(entry.get("id", "")), - name=str(fn.get("name", "")), - arguments=parse_tool_arguments(raw_args), - raw_arguments=str(raw_args) if raw_args else None, - ) - ) - return [c for c in out if c.name] - - -def extract_tool_calls_anthropic(content: list[Any]) -> list[ParsedToolCall]: - """Extract from Anthropic ``content`` blocks (``type: tool_use``).""" - out: list[ParsedToolCall] = [] - for block in content or []: - if isinstance(block, dict): - if block.get("type") != "tool_use": - continue - name = str(block.get("name", "")) - args = block.get("input", {}) - call_id = str(block.get("id", "")) - else: - if getattr(block, "type", None) != "tool_use": - continue - name = str(getattr(block, "name", "")) - args = getattr(block, "input", {}) - call_id = str(getattr(block, "id", "")) - out.append( - ParsedToolCall( - id=call_id, - name=name, - arguments=dict(args) if isinstance(args, dict) else {}, - ) - ) - return [c for c in out if c.name] - - -def extract_tool_calls( - message: dict[str, Any], - *, - provider: Provider = "auto", -) -> list[ParsedToolCall]: - """Unified extractor for assistant messages or Anthropic-shaped dicts. - - * ``provider="openai"`` — expects ``message["tool_calls"]``. - * ``provider="anthropic"`` — expects ``message["content"]`` as block list. - * ``provider="auto"`` — OpenAI if ``tool_calls`` present, else Anthropic blocks. - """ - if provider == "openai": - return extract_tool_calls_openai(message) - if provider == "anthropic": - content = message.get("content", []) - return extract_tool_calls_anthropic( - content if isinstance(content, list) else [] - ) - - if message.get("tool_calls"): - return extract_tool_calls_openai(message) - content = message.get("content") - if isinstance(content, list): - calls = extract_tool_calls_anthropic(content) - if calls: - return calls - return [] - - -def openai_tool_message(call_id: str, result: ToolResult) -> dict[str, Any]: - """Build an OpenAI ``role: tool`` message from a Forge result.""" - return { - "role": "tool", - "tool_call_id": call_id, - "content": result.content, - } - - -def anthropic_tool_result_block(call_id: str, result: ToolResult) -> dict[str, Any]: - """Build an Anthropic ``tool_result`` content block.""" - block: dict[str, Any] = { - "type": "tool_result", - "tool_use_id": call_id, - "content": result.content, - } - if result.is_error: - block["is_error"] = True - return block - - -def anthropic_tool_results_message(blocks: list[dict[str, Any]]) -> dict[str, Any]: - """Wrap tool-result blocks in a user message (Anthropic API shape).""" - return {"role": "user", "content": blocks} - - -def to_openai_tools( - tools: list[dict[str, Any]], -) -> list[dict[str, Any]]: - """Convert Anthropic-style ``{name, description, input_schema}`` to OpenAI tools.""" - out: list[dict[str, Any]] = [] - for tool in tools: - if tool.get("type") == "function" and isinstance(tool.get("function"), dict): - out.append(tool) - continue - out.append( - { - "type": "function", - "function": { - "name": tool.get("name", ""), - "description": tool.get("description", ""), - "parameters": tool.get("input_schema") - or tool.get("parameters") - or {}, - }, - } - ) - return out - - -def to_anthropic_tools( - tools: list[dict[str, Any]], -) -> list[dict[str, Any]]: - """Convert OpenAI ``tools`` to Anthropic ``tools`` list.""" - out: list[dict[str, Any]] = [] - for tool in tools: - if tool.get("name") and tool.get("input_schema") is not None: - out.append( - { - "name": tool["name"], - "description": tool.get("description", ""), - "input_schema": tool["input_schema"], - } - ) - continue - fn = tool.get("function") or {} - if not isinstance(fn, dict): - continue - out.append( - { - "name": fn.get("name", ""), - "description": fn.get("description", ""), - "input_schema": fn.get("parameters") or {}, - } - ) - return [t for t in out if t.get("name")] - - -class OpenAIToolCallAccumulator: - """Accumulate streaming OpenAI ``delta.tool_calls`` chunks into parsed calls.""" - - def __init__(self) -> None: - self._calls: dict[int, dict[str, str]] = {} - - def feed_chunk(self, chunk: dict[str, Any]) -> None: - """Feed one streaming chunk (``choices[0].delta`` shape or full chunk).""" - choices = chunk.get("choices") or [] - if not choices: - return - delta = choices[0].get("delta") or {} - for tool_call in delta.get("tool_calls") or []: - if not isinstance(tool_call, dict): - continue - index = int(tool_call.get("index", 0) or 0) - entry = self._calls.setdefault( - index, {"id": "", "name": "", "arguments": ""} - ) - if tool_call.get("id"): - entry["id"] = str(tool_call["id"]) - fn = tool_call.get("function") or {} - if isinstance(fn, dict): - if fn.get("name"): - entry["name"] = str(fn["name"]) - if fn.get("arguments"): - entry["arguments"] += str(fn["arguments"]) - - def finish(self) -> list[ParsedToolCall]: - """Return accumulated calls after the stream ends.""" - out: list[ParsedToolCall] = [] - for index in sorted(self._calls): - entry = self._calls[index] - raw_args = entry.get("arguments", "") - out.append( - ParsedToolCall( - id=entry.get("id", ""), - name=entry.get("name", ""), - arguments=parse_tool_arguments(raw_args), - raw_arguments=raw_args or None, - ) - ) - return [c for c in out if c.name] - - def reset(self) -> None: - self._calls.clear() - - -def forge_tool_definitions( - names: list[str] | None = None, -) -> list[dict[str, Any]]: - """Anthropic-shaped tool defs for Forge tools (``name`` / ``description`` / ``input_schema``). - - Full set (32 tools) requires ``pulsing.agent`` templates; falls back to a - minimal filesystem + shell subset when unavailable. - """ - try: - from pulsing.agent.loop.forge_tools import all_forge_tool_templates - - templates = all_forge_tool_templates() - defs = [t.to_api_schema() for t in templates] - except ImportError: - from pulsing.forge.tool_definitions import minimal_forge_tool_definitions - - defs = minimal_forge_tool_definitions() - - if names is None: - return defs - wanted = set(names) - return [d for d in defs if d.get("name") in wanted] diff --git a/python/pulsing/forge/tool_coverage.py b/python/pulsing/forge/tool_coverage.py deleted file mode 100644 index e44b3dafb..000000000 --- a/python/pulsing/forge/tool_coverage.py +++ /dev/null @@ -1,37 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge tool registry coverage checks (CI / tests).""" - -from __future__ import annotations - -from pulsing.forge.handlers import _ALL as _HANDLER_TOOL_NAMES -from pulsing.forge.integrated import ( - FORGE_HOST_TOOL_NAMES, - FORGE_ISOLATED_TOOL_NAMES, - FORGE_TOOL_NAMES, -) - -# Host tools routed via Rust MCP / approval RPC rather than Python handlers. -_RPC_HOST_TOOL_NAMES: frozenset[str] = frozenset( - { - "request_permissions", - "list_mcp_resources", - "list_mcp_resource_templates", - "read_mcp_resource", - }, -) - - -def forge_dispatch_tool_names() -> frozenset[str]: - return _HANDLER_TOOL_NAMES | _RPC_HOST_TOOL_NAMES - - -def assert_forge_tool_coverage() -> None: - """Every registered Forge tool must partition cleanly and be dispatchable.""" - assert FORGE_TOOL_NAMES == FORGE_ISOLATED_TOOL_NAMES | FORGE_HOST_TOOL_NAMES - assert not (FORGE_ISOLATED_TOOL_NAMES & FORGE_HOST_TOOL_NAMES) - - dispatchable = forge_dispatch_tool_names() - assert dispatchable == FORGE_TOOL_NAMES, ( - sorted(dispatchable - FORGE_TOOL_NAMES), - sorted(FORGE_TOOL_NAMES - dispatchable), - ) diff --git a/python/pulsing/forge/tool_definitions.py b/python/pulsing/forge/tool_definitions.py deleted file mode 100644 index aecb433e6..000000000 --- a/python/pulsing/forge/tool_definitions.py +++ /dev/null @@ -1,80 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Minimal Forge tool schemas (no agent.loop dependency).""" - -from __future__ import annotations - -from typing import Any - -from pulsing.forge.tool_schema import json_schema_object - - -def minimal_forge_tool_definitions() -> list[dict[str, Any]]: - """Core tools for custom agent frameworks without pulling agent.loop.""" - return [ - { - "name": "update_plan", - "description": "Publish or revise the task plan visible to the user.", - "input_schema": json_schema_object( - { - "plan": { - "type": "array", - "items": { - "type": "object", - "properties": { - "step": {"type": "string"}, - "status": { - "type": "string", - "enum": ["pending", "in_progress", "completed"], - }, - }, - "required": ["step", "status"], - }, - }, - "explanation": {"type": "string"}, - }, - required=["plan"], - ), - }, - { - "name": "Glob", - "description": "Find files matching a glob pattern under a directory.", - "input_schema": json_schema_object( - { - "pattern": {"type": "string"}, - "path": {"type": "string"}, - }, - required=["pattern"], - ), - }, - { - "name": "Read", - "description": "Read a text file from the workspace.", - "input_schema": json_schema_object( - {"file_path": {"type": "string"}}, - required=["file_path"], - ), - }, - { - "name": "Grep", - "description": "Search file contents with a regex pattern.", - "input_schema": json_schema_object( - { - "pattern": {"type": "string"}, - "path": {"type": "string"}, - "glob": {"type": "string"}, - }, - required=["pattern"], - ), - }, - { - "name": "shell_command", - "description": "Run a shell command in the workspace.", - "input_schema": json_schema_object( - { - "command": {"type": "string"}, - "workdir": {"type": "string"}, - }, - required=["command"], - ), - }, - ] diff --git a/python/pulsing/forge/tool_schema.py b/python/pulsing/forge/tool_schema.py deleted file mode 100644 index 49650e912..000000000 --- a/python/pulsing/forge/tool_schema.py +++ /dev/null @@ -1,16 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""JSON-schema helpers for Forge LLM tool definitions.""" - -from __future__ import annotations - -from typing import Any - - -def json_schema_object( - properties: dict[str, Any], - required: list[str] | None = None, -) -> dict[str, Any]: - schema: dict[str, Any] = {"type": "object", "properties": properties} - if required: - schema["required"] = required - return schema diff --git a/python/pulsing/forge/unified_exec.py b/python/pulsing/forge/unified_exec.py deleted file mode 100644 index 4a1124a10..000000000 --- a/python/pulsing/forge/unified_exec.py +++ /dev/null @@ -1,415 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""UnifiedExec sessions for exec_command / write_stdin.""" - -from __future__ import annotations - -import json -import os -import pty -import select -import subprocess -import threading -import time -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Callable - -from pulsing.forge.context import ToolCallContext, resolve_within_cwd -from pulsing.forge.exec_output import ( - DEFAULT_MAX_OUTPUT_TOKENS, - MAX_STDIN_BYTES, - ExecCommandOutput, - ExecOutputDelta, - ExecStream, - OutputBuffer, - Utf8ChunkDecoder, - clamp_yield_ms, -) -from pulsing.forge.result import ToolResult -from pulsing.forge.sandbox import build_bash_exec, normalize_policy - - -@dataclass -class _PtyHandle: - master_fd: int - proc: subprocess.Popen[str] - - def write_stdin(self, data: bytes) -> None: - os.write(self.master_fd, data) - - def kill(self) -> None: - self.proc.kill() - - def poll(self) -> int | None: - return self.proc.poll() - - def close(self) -> None: - try: - os.close(self.master_fd) - except OSError: - pass - - -@dataclass -class _ExecSession: - proc: subprocess.Popen[str] | None - pty: _PtyHandle | None - buffer: OutputBuffer - started: float - tty: bool - - -class UnifiedExecManager: - def __init__(self) -> None: - self._next_id = 1 - self._sessions: dict[int, _ExecSession] = {} - self._lock = threading.Lock() - - def __del__(self) -> None: - try: - self.stop_all() - except Exception: - pass - - def exec_command(self, ctx: ToolCallContext, args: dict[str, Any]) -> ToolResult: - cmd = args.get("cmd") or args.get("command") - if not cmd: - return ToolResult(content="missing cmd/command", is_error=True) - try: - workdir = _resolve_workdir(ctx, args) - except ValueError as e: - return ToolResult(content=str(e), is_error=True) - tty = bool(args.get("tty", True)) - login = bool(args.get("login", False)) - yield_ms = clamp_yield_ms(args.get("yield_time_ms")) - max_tokens = int(args.get("max_output_tokens") or DEFAULT_MAX_OUTPUT_TOKENS) - policy = _effective_policy(ctx, args) - if tty and normalize_policy(policy) != "off": - return ToolResult( - content=( - "tty exec_command sessions cannot use sandbox policy; " - "set tty=false or sandbox_permissions=require_escalated" - ), - is_error=True, - ) - - argv, env, _label = build_bash_exec( - str(cmd), - cwd=str(workdir), - policy=normalize_policy(policy), - dangerously_disable_sandbox=bool( - args.get("dangerously_disable_sandbox", ctx.dangerously_disable_sandbox) - ), - timeout=120, - login=login, - ) - - buffer = OutputBuffer() - session_id = self._next_id - self._next_id += 1 - on_delta = _stream_hook(ctx, session_id) - - if tty: - pty_handle = _spawn_pty(argv, workdir, env, buffer, session_id, on_delta) - with self._lock: - self._sessions[session_id] = _ExecSession( - proc=None, - pty=pty_handle, - buffer=buffer, - started=time.time(), - tty=True, - ) - else: - proc = _spawn_pipe(argv, workdir, env, buffer, session_id, on_delta) - with self._lock: - self._sessions[session_id] = _ExecSession( - proc=proc, - pty=None, - buffer=buffer, - started=time.time(), - tty=False, - ) - - time.sleep(yield_ms / 1000.0) - return self._poll(session_id, max_tokens) - - def write_stdin(self, ctx: ToolCallContext, args: dict[str, Any]) -> ToolResult: - _ = ctx - raw_session_id = args.get("session_id") - if raw_session_id is None: - return ToolResult(content="missing session_id", is_error=True) - try: - session_id = int(raw_session_id) - except (TypeError, ValueError): - return ToolResult( - content=f"invalid session_id {raw_session_id!r}", is_error=True - ) - chars = args["chars"] if "chars" in args else args.get("input") - if chars is None: - return ToolResult(content="missing chars", is_error=True) - chars = str(chars) - char_bytes = len(chars.encode("utf-8", errors="surrogateescape")) - if char_bytes > MAX_STDIN_BYTES: - return ToolResult( - content=( - f"stdin input too large: {char_bytes} bytes (max {MAX_STDIN_BYTES})" - ), - is_error=True, - ) - yield_ms = clamp_yield_ms(args.get("yield_time_ms")) - max_tokens = int(args.get("max_output_tokens") or DEFAULT_MAX_OUTPUT_TOKENS) - - # Hold the lock across the actual write so it can't race a concurrent - # `_poll` that closes/pops this session out from under us. - with self._lock: - session = self._sessions.get(session_id) - if session is None: - return ToolResult( - content=f"unknown session_id {session_id}", is_error=True - ) - if chars != "\x03": - exit_code = ( - session.pty.poll() - if session.pty is not None - else session.proc.poll() - if session.proc is not None - else None - ) - if exit_code is not None: - return ToolResult( - content=f"session {session_id} has already exited", - is_error=True, - ) - try: - if chars == "\x03": - if session.pty is not None: - session.pty.kill() - elif session.proc is not None: - session.proc.kill() - elif not session.tty: - return ToolResult( - content="stdin writes require tty=true exec_command sessions", - is_error=True, - ) - elif session.pty is not None: - session.pty.write_stdin( - chars.encode("utf-8", errors="surrogateescape") - ) - elif session.proc is not None and session.proc.stdin is not None: - session.proc.stdin.write(chars) - session.proc.stdin.flush() - else: - return ToolResult(content="session stdin is closed", is_error=True) - except (OSError, ValueError) as e: - return ToolResult(content=f"write stdin failed: {e}", is_error=True) - - time.sleep(yield_ms / 1000.0) - return self._poll(session_id, max_tokens) - - def stop_all(self) -> int: - """Kill every live session (host/agent teardown — avoid orphaned children).""" - with self._lock: - sessions = self._sessions - self._sessions = {} - for session in sessions.values(): - proc = session.pty.proc if session.pty is not None else session.proc - try: - if session.pty is not None: - session.pty.kill() - session.pty.close() - elif proc is not None: - proc.kill() - if proc is not None: - proc.wait(timeout=3) - except (OSError, subprocess.TimeoutExpired): - pass - return len(sessions) - - def _poll(self, session_id: int, max_tokens: int) -> ToolResult: - with self._lock: - session = self._sessions.get(session_id) - if session is None: - return ToolResult(content=f"unknown session_id {session_id}", is_error=True) - - if session.pty is not None: - exit_code = session.pty.poll() - else: - assert session.proc is not None - exit_code = session.proc.poll() - - wall = time.time() - session.started - session.buffer.truncate_to_tokens(max_tokens) - output = session.buffer.snapshot() - structured = ExecCommandOutput.build( - output=output, - wall_time_seconds=wall, - exit_code=exit_code, - session_id=None if exit_code is not None else session_id, - ) - if exit_code is not None: - with self._lock: - closed = self._sessions.pop(session_id, None) - if closed and closed.pty is not None: - closed.pty.close() - payload = structured.to_dict() - return ToolResult( - content=json.dumps(payload, indent=2), - is_error=exit_code is not None and exit_code != 0, - structured=payload, - ) - - -def _stream_hook( - ctx: ToolCallContext, - session_id: int, -) -> Callable[[ExecOutputDelta], None] | None: - session = ctx.session - if session is None: - return None - - def emit(delta: ExecOutputDelta) -> None: - session.on_exec_output_delta(delta) - - return emit - - -def _emit_delta( - on_delta: Callable[[ExecOutputDelta], None] | None, - session_id: int, - stream: ExecStream, - chunk: str, -) -> None: - if not chunk or on_delta is None: - return - on_delta(ExecOutputDelta(session_id=session_id, stream=stream, chunk=chunk)) - - -def _spawn_pty( - argv: list[str], - workdir: Path, - env: dict[str, str] | None, - buffer: OutputBuffer, - session_id: int, - on_delta: Callable[[ExecOutputDelta], None] | None, -) -> _PtyHandle: - master_fd, slave_fd = pty.openpty() - popen_kw: dict[str, Any] = { - "args": argv, - "cwd": str(workdir), - "stdin": slave_fd, - "stdout": slave_fd, - "stderr": slave_fd, - "text": True, - "close_fds": True, - } - if env is not None: - popen_kw["env"] = env - proc = subprocess.Popen(**popen_kw) - os.close(slave_fd) - - def _reader() -> None: - decoder = Utf8ChunkDecoder() - while True: - if proc.poll() is not None: - break - try: - ready, _, _ = select.select([master_fd], [], [], 0.05) - except OSError: - break - if not ready: - continue - try: - chunk = os.read(master_fd, 4096) - except OSError: - break - if not chunk: - break - text = decoder.decode(chunk) - if text: - buffer.push(text) - _emit_delta(on_delta, session_id, ExecStream.PTY, text) - while True: - try: - chunk = os.read(master_fd, 4096) - except OSError: - break - if not chunk: - break - text = decoder.decode(chunk) - if text: - buffer.push(text) - _emit_delta(on_delta, session_id, ExecStream.PTY, text) - tail = decoder.finish() - if tail: - buffer.push(tail) - _emit_delta(on_delta, session_id, ExecStream.PTY, tail) - - threading.Thread(target=_reader, daemon=True).start() - return _PtyHandle(master_fd=master_fd, proc=proc) - - -def _spawn_pipe( - argv: list[str], - workdir: Path, - env: dict[str, str] | None, - buffer: OutputBuffer, - session_id: int, - on_delta: Callable[[ExecOutputDelta], None] | None, -) -> subprocess.Popen[str]: - popen_kw: dict[str, Any] = { - "args": argv, - "cwd": str(workdir), - "stdout": subprocess.PIPE, - "stderr": subprocess.PIPE, - "stdin": subprocess.DEVNULL, - "text": True, - "bufsize": 1, - } - if env is not None: - popen_kw["env"] = env - proc = subprocess.Popen(**popen_kw) - - def _reader() -> None: - assert proc.stdout is not None - assert proc.stderr is not None - while proc.poll() is None: - if proc.stdout.readable(): - chunk = proc.stdout.read(4096) - if chunk: - buffer.push(chunk) - _emit_delta(on_delta, session_id, ExecStream.STDOUT, chunk) - if proc.stderr.readable(): - chunk = proc.stderr.read(4096) - if chunk: - buffer.push(chunk) - _emit_delta(on_delta, session_id, ExecStream.STDERR, chunk) - time.sleep(0.01) - rest_out = proc.stdout.read() or "" - rest_err = proc.stderr.read() or "" - if rest_out: - buffer.push(rest_out) - _emit_delta(on_delta, session_id, ExecStream.STDOUT, rest_out) - if rest_err: - buffer.push(rest_err) - _emit_delta(on_delta, session_id, ExecStream.STDERR, rest_err) - - threading.Thread(target=_reader, daemon=True).start() - return proc - - -def _resolve_workdir(ctx: ToolCallContext, args: dict[str, Any]) -> Path: - raw = args.get("workdir") or args.get("cwd") - if raw is None: - return ctx.cwd - return resolve_within_cwd(ctx.cwd, str(raw)) - - -def _effective_policy(ctx: ToolCallContext, args: dict[str, Any]) -> str: - if args.get("dangerously_disable_sandbox", ctx.dangerously_disable_sandbox): - return "off" - perm = args.get("sandbox_permissions") - if perm == "require_escalated": - return "off" - if perm == "with_additional_permissions": - return "restricted" - return ctx.sandbox_policy diff --git a/python/pulsing/forge/worker.py b/python/pulsing/forge/worker.py deleted file mode 100644 index 963623950..000000000 --- a/python/pulsing/forge/worker.py +++ /dev/null @@ -1,202 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Isolated tool worker as a Pulsing actor.""" - -from __future__ import annotations - -from typing import Any - -from pulsing.core.remote import remote - -from pulsing.forge.approval_bridge import ( - make_worker_exec_approval_callback, - make_worker_permissions_callback, -) -from pulsing.forge.config import ToolWorkerConfig -from pulsing.forge.context import ToolCallContext -from pulsing.forge.events import ForgeEvent -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.p2p_session import P2PToolSession -from pulsing.forge.p2p_transport import ForgeEventPump, tell_forge_event_sync -from pulsing.forge.hybrid_runtime import HybridForgeRuntime -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.session import NullToolSession - -_ISOLATED_ACTOR_NAME = "pulsing_forge_worker" - - -def _event_callback_for_sink( - sink: str | None, - pump: ForgeEventPump, - default_sink: str | None, -) -> Any: - if not sink: - return None - - def _cb(raw: dict[str, Any]) -> None: - event = ForgeEvent.from_dict(raw) - if sink == default_sink and pump.enabled: - pump.emit_sync(event) - else: - tell_forge_event_sync(sink, event) - - return _cb - - -@remote -class ToolWorkerActor: - """Filesystem/shell tools; returns picklable dicts for RPC.""" - - def __init__(self, config: ToolWorkerConfig | None = None) -> None: - self._cfg = config or ToolWorkerConfig() - self._pump: ForgeEventPump | None = None - self._hybrid: HybridForgeRuntime | None = None - self._runtime: LocalToolRuntime | None = None - - async def on_start(self, actor_id) -> None: - self._pump = ForgeEventPump(self._cfg.event_sink_name) - self._pump.start() - self._runtime = LocalToolRuntime( - cwd=self._cfg.cwd, - sandbox_policy=self._cfg.sandbox_policy, - dangerously_disable_sandbox=self._cfg.dangerously_disable_sandbox, - session=NullToolSession(), - ) - if RUST_FORGE_AVAILABLE: - cb = _event_callback_for_sink( - self._cfg.event_sink_name, - self._pump, - self._cfg.event_sink_name, - ) - sink = self._cfg.event_sink_name - approval = self._cfg.approval_sink() - self._hybrid = HybridForgeRuntime.create( - cwd=self._cfg.cwd, - sandbox_policy=self._cfg.sandbox_policy, - dangerously_disable_sandbox=self._cfg.dangerously_disable_sandbox, - auto_approve=self._cfg.auto_approve, - session=NullToolSession(), - event_callback=cb, - exec_approval_callback=make_worker_exec_approval_callback(approval), - request_permissions_callback=make_worker_permissions_callback(approval), - ) - - async def on_stop(self) -> None: - if self._hybrid is not None: - self._hybrid.close() - elif self._runtime is not None: - self._runtime.close() - if self._pump is not None: - await self._pump.stop() - - def ping(self) -> dict[str, Any]: - return { - "ok": True, - "kind": "tool_worker", - "rust_forge": self._hybrid is not None - and self._hybrid.rust_runtime is not None, - } - - def call_tool( - self, - name: str, - arguments: dict[str, Any] | None = None, - *, - event_sink: str | None = None, - ) -> dict[str, Any]: - sink = (event_sink or self._cfg.event_sink_name or "").strip() or None - if self._hybrid is not None: - return self._hybrid.call_tool(name, arguments).to_dict() - - emit = self._emit_fn(sink) - session = P2PToolSession(emit=emit) - if emit is not None: - emit(ForgeEvent.tool_begin(name, arguments)) - out = self._dispatch(name, arguments, session=session) - if emit is not None: - emit( - ForgeEvent.tool_end( - name, - is_error=bool(out.is_error), - content_preview=out.content, - ) - ) - return out.to_dict() - - def _emit_fn(self, sink: str | None): - if not sink or self._pump is None: - return None - if sink == self._cfg.event_sink_name and self._pump.enabled: - return self._pump.emit_sync - return lambda event: tell_forge_event_sync(sink, event) - - def _dispatch( - self, - name: str, - arguments: dict[str, Any] | None, - *, - session: P2PToolSession, - ): - if self._runtime is None: - # on_start hasn't run yet (direct construction, or a message racing - # startup) — build the local runtime lazily instead of crashing. - self._runtime = LocalToolRuntime( - cwd=self._cfg.cwd, - sandbox_policy=self._cfg.sandbox_policy, - dangerously_disable_sandbox=self._cfg.dangerously_disable_sandbox, - session=NullToolSession(), - ) - ctx = ToolCallContext( - cwd=self._runtime.context.cwd, - sandbox_policy=self._runtime.context.sandbox_policy, - dangerously_disable_sandbox=self._runtime.context.dangerously_disable_sandbox, - session=session, - exec=self._runtime.context.exec, - ) - return dispatch_tool(name, dict(arguments or {}), ctx=ctx) - - def _tool(self, name: str, kwargs: dict[str, Any]) -> dict[str, Any]: - sink = kwargs.pop("_event_sink", None) - return self.call_tool(name, kwargs, event_sink=sink) - - def Read(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("Read", kwargs) - - def Glob(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("Glob", kwargs) - - def Grep(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("Grep", kwargs) - - def Edit(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("Edit", kwargs) - - def Write(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("Write", kwargs) - - def Bash(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("Bash", kwargs) - - def shell_command(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("shell_command", kwargs) - - def exec_command(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("exec_command", kwargs) - - def write_stdin(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("write_stdin", kwargs) - - def apply_patch(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("apply_patch", kwargs) - - def view_image(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("view_image", kwargs) - - def update_plan(self, **kwargs: Any) -> dict[str, Any]: - return self._tool("update_plan", kwargs) - - -def default_worker_name(workspace_id: str) -> str: - from pulsing.forge.naming import shared_tool_worker_name - - return shared_tool_worker_name(workspace_id) diff --git a/python/pulsing/forge/worker_supervisor.py b/python/pulsing/forge/worker_supervisor.py deleted file mode 100644 index 24bb040d8..000000000 --- a/python/pulsing/forge/worker_supervisor.py +++ /dev/null @@ -1,131 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Supervise isolated ToolWorkerActor lifecycle (respawn on failure).""" - -from __future__ import annotations - -import asyncio -import logging -from typing import Any - -from pulsing.core.isolated_bridge import IsolatedSpawnHandle -from pulsing.core.proxy import ActorProxy - -from pulsing.forge.config import ToolWorkerConfig -from pulsing.forge.p2p_transport import ForgeEventPump -from pulsing.forge.worker import ToolWorkerActor - -logger = logging.getLogger(__name__) - - -class ForgeWorkerSupervisor: - """In-process supervisor for one ``ToolWorkerActor`` child process. - - Must run in the host process — ``new_process`` spawn cannot run safely - from inside another actor's mailbox handler. - """ - - def __init__(self, worker_cfg: ToolWorkerConfig) -> None: - self._cfg = worker_cfg - self._pump = ForgeEventPump(worker_cfg.event_sink_name) - self._spawn: IsolatedSpawnHandle | None = None - self._proxy: ActorProxy | None = None - self._lock = asyncio.Lock() - - @property - def proxy(self) -> ActorProxy | None: - return self._proxy - - async def close(self) -> None: - async with self._lock: - await self._pump.stop() - await self._teardown_locked() - - def terminate_process(self) -> None: - if self._spawn is None: - return - proc = self._spawn.process - if proc.returncode is None: - proc.terminate() - - async def ping(self) -> dict[str, Any]: - await self.ensure_ready(reason="ping") - assert self._proxy is not None - return await self._proxy.ping() - - async def ensure_ready(self, *, reason: str = "startup") -> None: - async with self._lock: - await self._ensure_worker_locked(reason=reason) - - async def call_tool( - self, - name: str, - arguments: dict[str, Any] | None = None, - *, - event_sink: str | None = None, - ) -> dict[str, Any]: - last_exc: BaseException | None = None - for attempt in range(2): - try: - async with self._lock: - await self._ensure_worker_locked(reason=f"tool {name!r}") - assert self._proxy is not None - kw = dict(arguments or {}) - sink = ( - event_sink or self._cfg.event_sink_name or "" - ).strip() or None - kw["_event_sink"] = sink - caller = getattr(self._proxy, name, None) - if caller is not None: - return await caller(**kw) - return await self._proxy.as_any().call_tool( - name, kw, event_sink=sink - ) - except BaseException as exc: - last_exc = exc - logger.warning( - "supervised worker tool %s failed (attempt %s): %s", - name, - attempt + 1, - exc, - ) - async with self._lock: - await self._teardown_locked() - raise RuntimeError(f"supervised worker failed after retry: {last_exc!r}") - - async def _ensure_worker_locked(self, *, reason: str) -> None: - import pulsing as pul - - if self._spawn is not None and self._spawn.process.returncode is None: - return - await self._teardown_locked() - self._pump.start() - logger.info("supervisor spawning ToolWorkerActor (%s)", reason) - actor = ToolWorkerActor(self._cfg) - h = await pul.spawn( - actor, - new_process=True, - name="pulsing_forge_worker", - public=False, - restart_policy="never", - ) - if not isinstance(h, IsolatedSpawnHandle): - raise TypeError("expected IsolatedSpawnHandle from isolated spawn") - self._spawn = h - self._proxy = ActorProxy( - h.ref, ToolWorkerActor._methods, ToolWorkerActor._async_methods - ) - - async def _teardown_locked(self) -> None: - if self._spawn is None: - self._proxy = None - return - proc = self._spawn.process - if proc.returncode is None: - proc.terminate() - try: - await asyncio.wait_for(proc.wait(), timeout=8.0) - except asyncio.TimeoutError: - proc.kill() - await proc.wait() - self._spawn = None - self._proxy = None diff --git a/python/pulsing/serving/__init__.py b/python/pulsing/serving/__init__.py deleted file mode 100644 index d7b40bf56..000000000 --- a/python/pulsing/serving/__init__.py +++ /dev/null @@ -1,58 +0,0 @@ -"""Pulsing Actors - Distributed LLM inference components""" - -# Worker -# Router -# Stream load subscription -from .load_stream import LoadSnapshot, LoadStreamConsumer, StreamLoadScheduler -from .router import Router, start_router, stop_router - -# Scheduler -from .scheduler import ( # Base class; Python schedulers; Rust high-performance schedulers; Factory function - RUST_POLICIES_AVAILABLE, - LeastConnectionScheduler, - RandomScheduler, - RoundRobinScheduler, - RustCacheAwareScheduler, - RustConsistentHashScheduler, - RustPowerOfTwoScheduler, - RustRandomScheduler, - RustRoundRobinScheduler, - Scheduler, - get_scheduler, -) -from .vllm import VllmWorker -from .worker import GenerationConfig, TransformersWorker - -# Backward compatibility alias -TransformersWorkerActor = TransformersWorker - - -__all__ = [ - # Core API - "Router", - "TransformersWorker", - "VllmWorker", - "GenerationConfig", - "start_router", - "stop_router", - # Scheduler base class and Python implementations - "Scheduler", - "RoundRobinScheduler", - "RandomScheduler", - "LeastConnectionScheduler", - # Rust high-performance schedulers - "RustRandomScheduler", - "RustRoundRobinScheduler", - "RustPowerOfTwoScheduler", - "RustConsistentHashScheduler", - "RustCacheAwareScheduler", - # Stream load subscription (recommended for load-aware scheduling) - "LoadSnapshot", - "LoadStreamConsumer", - "StreamLoadScheduler", - # Factory function - "get_scheduler", - "RUST_POLICIES_AVAILABLE", - # Compatibility aliases - "TransformersWorkerActor", -] diff --git a/python/pulsing/serving/load_stream.py b/python/pulsing/serving/load_stream.py deleted file mode 100644 index b87e103cf..000000000 --- a/python/pulsing/serving/load_stream.py +++ /dev/null @@ -1,300 +0,0 @@ -"""Load information subscription based on streaming requests - -Architecture: - Scheduler (LoadStreamConsumer) calls worker_ref.as_any().subscribe_load() - and iterates the async generator; Worker yields load snapshot dicts. - - ┌─────────┐ ┌─────────┐ - │ Scheduler│ ─ subscribe_load() ►│ Worker │ - │ (Consumer)│ │ @remote │ - │ │ ◄── async for ────── │ │ - │ │ {load: 5} │ │ - │ │ ◄── {load: 3} ────── │ │ - └─────────┘ └─────────┘ - -Usage: - # Router side - scheduler = StreamLoadScheduler(actor_system, "worker") - await scheduler.start() - worker_ref = await scheduler.select_worker() -""" - -import asyncio -import time -from collections.abc import Callable -from dataclasses import dataclass - -from pulsing.core import ActorRef - -from .scheduler import Scheduler - - -@dataclass -class LoadSnapshot: - """Load snapshot""" - - worker_id: str - node_id: str - load: int - capacity: int - processed: int - timestamp: float - - @property - def load_ratio(self) -> float: - return self.load / max(1, self.capacity) - - @classmethod - def from_dict(cls, data: dict) -> "LoadSnapshot": - return cls( - worker_id=data.get("worker_id", ""), - node_id=data.get("node_id", ""), - load=data.get("load", 0), - capacity=data.get("capacity", 100), - processed=data.get("processed", 0), - timestamp=data.get("timestamp", time.time()), - ) - - -class LoadStreamConsumer: - """Router side: Load stream consumer - - Subscribes to load streams from multiple Workers, aggregates and maintains load snapshots. - """ - - def __init__(self, stale_timeout: float = 10.0): - self._stale_timeout = stale_timeout - self._loads: dict[str, LoadSnapshot] = {} - self._subscriptions: dict[str, asyncio.Task] = {} - self._lock = asyncio.Lock() - self._on_update: Callable[[LoadSnapshot], None] | None = None - self._on_disconnect: Callable[[str], None] | None = None - - async def subscribe(self, worker_ref: ActorRef, worker_id: str = None): - """Subscribe to Worker's load stream via @remote subscribe_load().""" - wid = worker_id or str(worker_ref.actor_id) - await self.unsubscribe(wid) - - async def consume(): - try: - proxy = worker_ref.as_any() - async for chunk in proxy.subscribe_load(): - data = ( - chunk - if isinstance(chunk, dict) - else (chunk.to_json() if hasattr(chunk, "to_json") else {}) - ) - snapshot = LoadSnapshot.from_dict(data) - async with self._lock: - self._loads[snapshot.worker_id] = snapshot - if self._on_update: - try: - self._on_update(snapshot) - except Exception: - pass - except asyncio.CancelledError: - pass - except Exception: - pass - finally: - async with self._lock: - self._loads.pop(wid, None) - if self._on_disconnect: - try: - self._on_disconnect(wid) - except Exception: - pass - - task = asyncio.create_task(consume()) - self._subscriptions[wid] = task - - def on_disconnect(self, callback: Callable[[str], None]): - self._on_disconnect = callback - - async def unsubscribe(self, worker_id: str): - if worker_id in self._subscriptions: - self._subscriptions[worker_id].cancel() - try: - await self._subscriptions[worker_id] - except asyncio.CancelledError: - pass - del self._subscriptions[worker_id] - async with self._lock: - self._loads.pop(worker_id, None) - - async def unsubscribe_all(self): - for wid in list(self._subscriptions.keys()): - await self.unsubscribe(wid) - - def get_load(self, worker_id: str) -> LoadSnapshot | None: - snapshot = self._loads.get(worker_id) - if snapshot and time.time() - snapshot.timestamp <= self._stale_timeout: - return snapshot - return None - - def get_all_loads(self) -> dict[str, LoadSnapshot]: - now = time.time() - return { - wid: snap - for wid, snap in self._loads.items() - if now - snap.timestamp <= self._stale_timeout - } - - def get_lowest_load_worker(self) -> str | None: - valid = self.get_all_loads() - return min(valid.keys(), key=lambda w: valid[w].load) if valid else None - - def on_update(self, callback: Callable[[LoadSnapshot], None]): - self._on_update = callback - - -class StreamLoadScheduler(Scheduler): - """Load-aware scheduler based on stream subscription - - - Automatically discovers new Workers and subscribes - - Detects Worker offline and cleans up - - Selects Worker with lowest load - """ - - def __init__( - self, - actor_system, - worker_name: str = "worker", - auto_discover: bool = True, - discover_interval: float = 10.0, - ): - super().__init__(actor_system, worker_name) - self._auto_discover = auto_discover - self._discover_interval = discover_interval - - self._consumer = LoadStreamConsumer() - self._worker_refs: dict[str, ActorRef] = {} - self._subscribed_workers: set = set() - self._running = False - self._discover_task: asyncio.Task | None = None - - self._on_worker_added: Callable[[str], None] | None = None - self._on_worker_removed: Callable[[str], None] | None = None - - async def start(self): - """Start scheduler""" - self._running = True - self._consumer.on_disconnect(self._handle_worker_disconnect) - await self._discover_and_subscribe() - if self._auto_discover: - self._discover_task = asyncio.create_task(self._auto_discover_loop()) - - def _handle_worker_disconnect(self, node_id: str): - self._subscribed_workers.discard(node_id) - self._worker_refs.pop(node_id, None) - if self._on_worker_removed: - try: - self._on_worker_removed(node_id) - except Exception: - pass - - async def stop(self): - """Stop scheduler""" - self._running = False - if self._discover_task: - self._discover_task.cancel() - try: - await self._discover_task - except asyncio.CancelledError: - pass - await self._consumer.unsubscribe_all() - self._subscribed_workers.clear() - self._worker_refs.clear() - - async def _discover_and_subscribe(self): - """Discover and subscribe to Workers""" - try: - # Use get_named_instances instead of unbound lookup_named_actor - workers = await self._system.get_named_instances(self._worker_name) - current = {w.get("node_id") for w in workers if w.get("node_id")} - - async with self._lock: - # New Workers - for node_id in current - self._subscribed_workers: - await self._subscribe_worker(node_id) - # Offline Workers - for node_id in self._subscribed_workers - current: - await self._unsubscribe_worker(node_id) - except Exception as e: - print(f"[StreamLoadScheduler] Discover error: {e}") - pass - - async def _subscribe_worker(self, node_id: str): - if node_id in self._subscribed_workers: - return - try: - # Use resolve_named instead of unbound get_actor_ref - # node_id is string from members(), convert to int for resolve_named - worker_ref = await self._system.resolve_named( - self._worker_name, node_id=int(node_id) - ) - if worker_ref: - self._worker_refs[node_id] = worker_ref - await self._consumer.subscribe(worker_ref, node_id) - self._subscribed_workers.add(node_id) - if self._on_worker_added: - try: - self._on_worker_added(node_id) - except Exception: - pass - except Exception as e: - print(f"[StreamLoadScheduler] Subscribe error for node {node_id}: {e}") - pass - - async def _unsubscribe_worker(self, node_id: str): - if node_id not in self._subscribed_workers: - return - await self._consumer.unsubscribe(node_id) - self._subscribed_workers.discard(node_id) - self._worker_refs.pop(node_id, None) - if self._on_worker_removed: - try: - self._on_worker_removed(node_id) - except Exception: - pass - - async def _auto_discover_loop(self): - while self._running: - await asyncio.sleep(self._discover_interval) - await self._discover_and_subscribe() - - async def select_worker( - self, - request_text: str = None, - headers: dict[str, str] = None, - ) -> ActorRef | None: - """Select Worker with lowest load""" - worker_id = self._consumer.get_lowest_load_worker() - if worker_id and worker_id in self._worker_refs: - return self._worker_refs[worker_id] - if self._worker_refs: - import random - - return random.choice(list(self._worker_refs.values())) - return None - - def get_all_loads(self) -> dict[str, LoadSnapshot]: - return self._consumer.get_all_loads() - - async def get_worker_count(self) -> int: - return len(self._subscribed_workers) - - async def get_healthy_worker_count(self) -> int: - return len(self._consumer.get_all_loads()) - - def get_subscribed_workers(self) -> set: - return self._subscribed_workers.copy() - - def on_load_update(self, callback: Callable[[LoadSnapshot], None]): - self._consumer.on_update(callback) - - def on_worker_added(self, callback: Callable[[str], None]): - self._on_worker_added = callback - - def on_worker_removed(self, callback: Callable[[str], None]): - self._on_worker_removed = callback diff --git a/python/pulsing/serving/router.py b/python/pulsing/serving/router.py deleted file mode 100644 index c046a422a..000000000 --- a/python/pulsing/serving/router.py +++ /dev/null @@ -1,474 +0,0 @@ -"""OpenAI-compatible HTTP API router.""" - -import asyncio -import json -import time -import uuid -from dataclasses import dataclass - -from aiohttp import web - -from pulsing.core import ActorId, ActorSystem, get_system, remote -from pulsing.serving.scheduler import Scheduler # noqa: F401 (used in type annotation) - - -@dataclass -class ChatCompletionRequest: - model: str - messages: list[dict[str, str]] - temperature: float = 1.0 - top_p: float = 1.0 - stream: bool = False - max_tokens: int | None = None - - @classmethod - def from_dict(cls, data: dict) -> "ChatCompletionRequest": - return cls( - model=data.get("model", ""), - messages=data.get("messages", []), - temperature=data.get("temperature", 1.0), - top_p=data.get("top_p", 1.0), - stream=data.get("stream", False), - max_tokens=data.get("max_tokens"), - ) - - -@dataclass -class CompletionRequest: - model: str - prompt: str | list[str] - max_tokens: int = 16 - temperature: float = 1.0 - stream: bool = False - - @classmethod - def from_dict(cls, data: dict) -> "CompletionRequest": - return cls( - model=data.get("model", ""), - prompt=data.get("prompt", ""), - max_tokens=data.get("max_tokens", 16), - temperature=data.get("temperature", 1.0), - stream=data.get("stream", False), - ) - - -class _OpenAIHandler: - """OpenAI-compatible HTTP request handler.""" - - def __init__( - self, actor_system: ActorSystem, model_name: str, scheduler: Scheduler - ): - self._actor_system = actor_system - self.model_name = model_name - self._request_count = 0 - self._scheduler = scheduler - - async def index(self, request: web.Request) -> web.Response: - return web.json_response( - { - "service": "Pulsing OpenAI-Compatible API", - "model": self.model_name, - } - ) - - async def health_check(self, request: web.Request) -> web.Response: - total_workers = await self._scheduler.get_worker_count() - healthy_workers = await self._scheduler.get_healthy_worker_count() - - return web.json_response( - { - "status": "healthy" if healthy_workers > 0 else "degraded", - "model": self.model_name, - "total_workers": total_workers, - "healthy_workers": healthy_workers, - "request_count": self._request_count, - } - ) - - async def list_models(self, request: web.Request) -> web.Response: - return web.json_response( - { - "object": "list", - "data": [ - { - "id": self.model_name, - "object": "model", - "created": int(time.time()), - "owned_by": "pulsing", - } - ], - } - ) - - async def chat_completions(self, request: web.Request) -> web.Response: - self._request_count += 1 - request_id = f"chatcmpl-{uuid.uuid4().hex[:24]}" - try: - data = await request.json() - except Exception: - return web.json_response({"error": {"message": "Invalid JSON"}}, status=400) - - req = ChatCompletionRequest.from_dict(data) - worker_ref = await self._scheduler.select_worker() - if not worker_ref: - return web.json_response( - {"error": {"message": "No available workers"}}, status=503 - ) - - prompt = self._build_chat_prompt(req.messages) - if req.stream: - return await self._stream_generate( - request, - request_id, - req.model, - prompt, - worker_ref, - req.max_tokens or 512, - is_chat=True, - ) - else: - return await self._sync_generate( - request_id, - req.model, - prompt, - worker_ref, - req.max_tokens or 512, - is_chat=True, - ) - - async def completions(self, request: web.Request) -> web.Response: - self._request_count += 1 - request_id = f"cmpl-{uuid.uuid4().hex[:24]}" - try: - data = await request.json() - except Exception: - return web.json_response({"error": {"message": "Invalid JSON"}}, status=400) - - req = CompletionRequest.from_dict(data) - worker_ref = await self._scheduler.select_worker() - if not worker_ref: - return web.json_response( - {"error": {"message": "No available workers"}}, status=503 - ) - - prompt = req.prompt if isinstance(req.prompt, str) else req.prompt[0] - if req.stream: - return await self._stream_generate( - request, - request_id, - req.model, - prompt, - worker_ref, - req.max_tokens, - is_chat=False, - ) - else: - return await self._sync_generate( - request_id, req.model, prompt, worker_ref, req.max_tokens, is_chat=False - ) - - def _build_chat_prompt(self, messages: list[dict]) -> str: - parts = [ - f"{msg.get('role', 'user').capitalize()}: {msg.get('content', '')}" - for msg in messages - ] - return "\n".join(parts + ["Assistant:"]) - - async def _sync_generate( - self, - request_id: str, - model: str, - prompt: str, - worker_ref, - max_tokens: int, - is_chat: bool, - ) -> web.Response: - created = int(time.time()) - - try: - worker = worker_ref.as_any() - result = await worker.generate(prompt=prompt, max_new_tokens=max_tokens) - if isinstance(result, dict) and "error" in result: - text = f"[Error: {result['error']}]" - prompt_tokens = completion_tokens = 0 - else: - text = result.get("text", "") - prompt_tokens = result.get("prompt_tokens", 0) - completion_tokens = result.get("completion_tokens", 0) - except Exception as e: - text = f"[Error: {e}]" - prompt_tokens = completion_tokens = 0 - - res_data = { - "id": request_id, - "object": "chat.completion" if is_chat else "text_completion", - "created": created, - "model": model or self.model_name, - "choices": [{"index": 0, "finish_reason": "stop"}], - "usage": { - "prompt_tokens": prompt_tokens, - "completion_tokens": completion_tokens, - "total_tokens": prompt_tokens + completion_tokens, - }, - } - if is_chat: - res_data["choices"][0]["message"] = {"role": "assistant", "content": text} - else: - res_data["choices"][0]["text"] = text - return web.json_response(res_data) - - def _build_chunk( - self, request_id, obj_type, created, model, text, finish_reason, is_chat - ) -> dict: - choice: dict = {"index": 0, "finish_reason": finish_reason} - if is_chat: - choice["delta"] = {"content": text} if text else {} - else: - choice["text"] = text or "" - return { - "id": request_id, - "object": obj_type, - "created": created, - "model": model or self.model_name, - "choices": [choice], - } - - async def _stream_generate( - self, - request: web.Request, - request_id: str, - model: str, - prompt: str, - worker_ref, - max_tokens: int, - is_chat: bool, - ) -> web.StreamResponse: - created = int(time.time()) - stream_response = web.StreamResponse( - headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"} - ) - await stream_response.prepare(request) - - obj_type = "chat.completion.chunk" if is_chat else "text_completion" - - async def _send(data: dict): - await stream_response.write(f"data: {json.dumps(data)}\n\n".encode()) - - try: - worker = worker_ref.as_any() - stream = worker.generate_stream(prompt=prompt, max_new_tokens=max_tokens) - - async for chunk in stream: - if isinstance(chunk, dict) and chunk.get("error"): - await _send({"error": chunk["error"]}) - await stream_response.write(b"data: [DONE]\n\n") - return stream_response - try: - finish_reason = chunk.get("finish_reason") - text = chunk.get("text", "") - - if finish_reason: - if text: - await _send( - self._build_chunk( - request_id, - obj_type, - created, - model, - text, - finish_reason, - is_chat, - ) - ) - break - - if text: - await _send( - self._build_chunk( - request_id, - obj_type, - created, - model, - text, - None, - is_chat, - ) - ) - except json.JSONDecodeError: - continue - except Exception as e: - await _send({"error": str(e)}) - - await _send( - self._build_chunk( - request_id, - obj_type, - created, - model, - "", - "stop", - is_chat, - ) - ) - await stream_response.write(b"data: [DONE]\n\n") - return stream_response - - -def _create_app(system: ActorSystem, model_name: str, scheduler) -> web.Application: - """Build the aiohttp Application with OpenAI-compatible routes.""" - handler = _OpenAIHandler(system, model_name, scheduler) - app = web.Application() - app.router.add_get("/", handler.index) - app.router.add_get("/health", handler.health_check) - app.router.add_get("/v1/models", handler.list_models) - app.router.add_post("/v1/chat/completions", handler.chat_completions) - app.router.add_post("/v1/completions", handler.completions) - app["scheduler"] = scheduler - return app - - -def _build_scheduler(system: ActorSystem, worker_name: str, scheduler_type: str): - """Create a Scheduler instance from scheduler_type string.""" - from .load_stream import StreamLoadScheduler - from .scheduler import get_scheduler - - if scheduler_type == "stream_load": - return StreamLoadScheduler(system, worker_name) - return get_scheduler(scheduler_type, system, worker_name) - - -@remote -class Router: - """OpenAI-compatible HTTP API router Actor. - - Starts an HTTP server on ``on_start`` and stops it on ``on_stop``. - Exposes ``health_check`` and ``get_config`` as remote-callable methods. - - CLI usage:: - - pulsing actor pulsing.serving.Router --addr 0.0.0.0:8000 -- \\ - --http_port 8080 --model_name my-model - - Args: - http_host: HTTP listen address (default: "0.0.0.0") - http_port: HTTP listen port (default: 8080) - model_name: Model name returned in API responses (default: "pulsing-model") - worker_name: Worker actor name to route to (default: "worker") - scheduler_type: Scheduling policy — stream_load (default) / random / - round_robin / power_of_two / cache_aware - """ - - def __init__( - self, - http_host: str = "0.0.0.0", - http_port: int = 8080, - model_name: str = "pulsing-model", - worker_name: str = "worker", - scheduler_type: str = "stream_load", - ): - self.http_host = http_host - self.http_port = http_port - self.model_name = model_name - self.worker_name = worker_name - self.scheduler_type = scheduler_type - - self._runner: web.AppRunner | None = None - self._scheduler: Scheduler | None = None - - async def on_start(self, actor_id: ActorId) -> None: - system = get_system() - self._scheduler = _build_scheduler( - system, self.worker_name, self.scheduler_type - ) - await self._scheduler.start() - - app = _create_app(system, self.model_name, self._scheduler) - self._runner = web.AppRunner(app) - await self._runner.setup() - await web.TCPSite(self._runner, self.http_host, self.http_port).start() - - print( - f"[Router] HTTP server started at http://{self.http_host}:{self.http_port}" - ) - print(f"[Router] Actor started: {actor_id}") - - def on_stop(self) -> None: - if self._runner: - asyncio.create_task(self._shutdown()) - - async def _shutdown(self) -> None: - if self._scheduler: - await self._scheduler.stop() - self._scheduler = None - if self._runner: - await self._runner.cleanup() - self._runner = None - print("[Router] HTTP server stopped") - - def metadata(self) -> dict[str, str]: - return { - "type": "router", - "http_host": self.http_host, - "http_port": str(self.http_port), - "model_name": self.model_name, - "worker_name": self.worker_name, - "scheduler_type": self.scheduler_type, - } - - def health_check(self) -> dict: - return { - "status": "healthy", - "http_port": self.http_port, - "model_name": self.model_name, - } - - def get_config(self) -> dict: - return { - "http_host": self.http_host, - "http_port": self.http_port, - "model_name": self.model_name, - "worker_name": self.worker_name, - "scheduler_type": self.scheduler_type, - } - - -async def start_router( - system: ActorSystem, - http_host: str = "0.0.0.0", - http_port: int = 8080, - model_name: str = "pulsing-model", - worker_name: str = "worker", - scheduler_type: str = "stream_load", - scheduler=None, -) -> web.AppRunner: - """Start an OpenAI-compatible HTTP server without creating a Router actor. - - Useful for embedding the router in an existing asyncio application. - For CLI / Actor-lifecycle usage prefer the ``Router`` actor class instead. - - Returns: - ``web.AppRunner`` — pass to ``stop_router()`` for cleanup. - """ - if scheduler is None: - scheduler = _build_scheduler(system, worker_name, scheduler_type) - - await scheduler.start() - - app = _create_app(system, model_name, scheduler) - runner = web.AppRunner(app) - await runner.setup() - await web.TCPSite(runner, http_host, http_port).start() - - print(f"[Router] HTTP server started at http://{http_host}:{http_port}") - return runner - - -async def stop_router(runner: web.AppRunner) -> None: - """Stop a router started via ``start_router()``.""" - if not runner: - return - scheduler = runner.app.get("scheduler") - if scheduler: - await scheduler.stop() - await runner.cleanup() - print("[Router] HTTP server stopped") diff --git a/python/pulsing/serving/scheduler.py b/python/pulsing/serving/scheduler.py deleted file mode 100644 index 7d528b779..000000000 --- a/python/pulsing/serving/scheduler.py +++ /dev/null @@ -1,338 +0,0 @@ -"""Worker scheduler - Load balancing strategies - -Supports the following scheduling strategies (all Rust-implemented): -- RustRandomScheduler: Random selection -- RustRoundRobinScheduler: Round-robin selection -- RustPowerOfTwoScheduler: Power-of-Two Choices -- RustConsistentHashScheduler: Consistent hashing (session affinity) -- RustCacheAwareScheduler: Cache-aware routing (Radix Tree prefix matching) -- LeastConnectionScheduler: Least connections (Python) - -For load-aware scheduling, use StreamLoadScheduler from load_stream module. -""" - -import asyncio -from abc import ABC, abstractmethod -from typing import Any - -import pulsing - -# Import Rust policies if available -try: - from pulsing._core import ( - CacheAwareConfig, - CacheAwarePolicy, - ConsistentHashPolicy, - PowerOfTwoPolicy, - RandomPolicy, - RoundRobinPolicy, - WorkerInfo, - ) - - RUST_POLICIES_AVAILABLE = True -except ImportError: - RUST_POLICIES_AVAILABLE = False - # Placeholder types when Rust not available - WorkerInfo = Any - RandomPolicy = None - RoundRobinPolicy = None - PowerOfTwoPolicy = None - ConsistentHashPolicy = None - CacheAwarePolicy = None - CacheAwareConfig = None - - -class Scheduler(ABC): - """Scheduler base class - - All scheduler implementations must inherit from this class. - Provides default lifecycle (start/stop) and health query methods. - """ - - def __init__(self, actor_system, worker_name: str = "worker"): - self._system = actor_system - self._worker_name = worker_name - self._lock = asyncio.Lock() - - async def start(self): - """Start the scheduler. Override for schedulers that need background tasks.""" - - async def stop(self): - """Stop the scheduler. Override for schedulers that need cleanup.""" - - async def get_available_workers(self): - try: - return await self._system.get_named_instances(self._worker_name) - except Exception: - return [] - - async def get_worker_count(self) -> int: - return len(await self.get_available_workers()) - - async def get_healthy_worker_count(self) -> int: - workers = await self.get_available_workers() - return sum(1 for w in workers if w.get("status") == "Alive") - - async def _resolve_worker(self, node_id: int | None = None): - try: - return await self._system.resolve_named(self._worker_name, node_id=node_id) - except Exception: - return None - - @abstractmethod - async def select_worker( - self, - request_text: str | None = None, - headers: dict[str, str] | None = None, - ): - """Select a worker, returns ActorRef or None - - Args: - request_text: Request text (for cache-aware and consistent hash routing) - headers: HTTP request headers (for consistent hash routing) - """ - pass - - -# ============================================================================ -# Python-implemented schedulers -# ============================================================================ - - -class LeastConnectionScheduler(Scheduler): - """Least connections scheduler (Python implementation)""" - - def __init__(self, actor_system, worker_name: str = "worker"): - super().__init__(actor_system, worker_name) - self._request_counts = {} - - async def select_worker( - self, - request_text: str | None = None, - headers: dict[str, str] | None = None, - ): - workers = await self.get_available_workers() - if not workers: - return None - - async with self._lock: - selected_worker = min( - workers, key=lambda w: self._request_counts.get(w.get("node_id"), 0) - ) - node_id = selected_worker.get("node_id") - self._request_counts[node_id] = self._request_counts.get(node_id, 0) + 1 - - return await pulsing.refer(selected_worker.get("actor_id")) - - -# ============================================================================ -# Rust-implemented schedulers (high performance) -# ============================================================================ - - -class RustSchedulerBase(Scheduler): - """Rust scheduler base class — provides shared select_worker implementation.""" - - def __init__(self, actor_system, worker_name: str = "worker"): - if not RUST_POLICIES_AVAILABLE: - raise ImportError("Rust policies not available. Rebuild with maturin.") - super().__init__(actor_system, worker_name) - self._worker_info_cache: dict[str, WorkerInfo] = {} - self._policy = None # subclasses set this - - def _get_worker_info(self, worker_data: dict) -> WorkerInfo: - node_id = worker_data.get("node_id", "") - if node_id not in self._worker_info_cache: - url = worker_data.get("addr", f"http://{node_id}") - model_id = worker_data.get("model_id", "default") - self._worker_info_cache[node_id] = WorkerInfo(url, model_id) - worker_info = self._worker_info_cache[node_id] - worker_info.is_healthy = worker_data.get("status") == "Alive" - return worker_info - - def _workers_to_info_list(self, workers: list) -> list: - return [self._get_worker_info(w) for w in workers] - - def _pre_select(self, worker_infos: list) -> None: - """Hook for subclasses that need setup before selection (e.g. CacheAware).""" - - def _do_select(self, worker_infos, request_text, headers): - """Invoke the Rust policy. Override for policies that need extra args (e.g. headers).""" - return self._policy.select_worker(worker_infos, request_text) - - async def select_worker( - self, - request_text: str | None = None, - headers: dict[str, str] | None = None, - ): - workers = await self.get_available_workers() - if not workers: - return None - - worker_infos = self._workers_to_info_list(workers) - self._pre_select(worker_infos) - selected_idx = self._do_select(worker_infos, request_text, headers) - - if selected_idx is None: - return None - return await pulsing.refer(workers[selected_idx].get("actor_id")) - - -class RustRandomScheduler(RustSchedulerBase): - """Random scheduler (Rust implementation, high performance)""" - - def __init__(self, actor_system, worker_name: str = "worker"): - super().__init__(actor_system, worker_name) - self._policy = RandomPolicy() - - -class RustRoundRobinScheduler(RustSchedulerBase): - """Round-robin scheduler (Rust implementation)""" - - def __init__(self, actor_system, worker_name: str = "worker"): - super().__init__(actor_system, worker_name) - self._policy = RoundRobinPolicy() - - def reset(self): - self._policy.reset() - - -class RustPowerOfTwoScheduler(RustSchedulerBase): - """Power-of-Two Choices scheduler (Rust implementation)""" - - def __init__(self, actor_system, worker_name: str = "worker"): - super().__init__(actor_system, worker_name) - self._policy = PowerOfTwoPolicy() - - def update_loads(self, loads: dict[str, int]): - self._policy.update_loads(loads) - - -class RustConsistentHashScheduler(RustSchedulerBase): - """Consistent hash scheduler (Rust implementation) - - Routes based on session ID or user ID, ensuring requests from the same user - are always routed to the same worker. - """ - - def __init__(self, actor_system, worker_name: str = "worker"): - super().__init__(actor_system, worker_name) - self._policy = ConsistentHashPolicy() - - def _do_select(self, worker_infos, request_text, headers): - return self._policy.select_worker(worker_infos, request_text, headers) - - def reset(self): - self._policy.reset() - - -class RustCacheAwareScheduler(RustSchedulerBase): - """Cache-aware scheduler (Rust implementation) - - Combines cache affinity and load balancing. Suitable for LLM inference - scenarios to improve KV Cache hit rate. - """ - - def __init__( - self, - actor_system, - worker_name: str = "worker", - cache_threshold: float = 0.5, - balance_abs_threshold: int = 32, - balance_rel_threshold: float = 1.0001, - eviction_interval_secs: int = 60, - max_tree_size: int = 100000, - ): - super().__init__(actor_system, worker_name) - config = CacheAwareConfig( - cache_threshold=cache_threshold, - balance_abs_threshold=balance_abs_threshold, - balance_rel_threshold=balance_rel_threshold, - eviction_interval_secs=eviction_interval_secs, - max_tree_size=max_tree_size, - ) - self._policy = CacheAwarePolicy(config) - - def _pre_select(self, worker_infos: list) -> None: - self._policy.init_workers(worker_infos) - - def add_worker(self, url: str, model_id: str = "default"): - self._policy.add_worker(url, model_id) - - def remove_worker(self, url: str): - self._policy.remove_worker(url) - - def evict_cache(self, max_size: int): - self._policy.evict_cache(max_size) - - -# ============================================================================ -# Factory function -# ============================================================================ - - -def get_scheduler( - policy_name: str, actor_system, worker_name: str = "worker", **kwargs -) -> Scheduler: - """Get scheduler instance - - Args: - policy_name: Policy name, supports: - - "random": Random - - "round_robin": Round robin - - "power_of_two": Power-of-Two Choices - - "consistent_hash": Consistent hash - - "cache_aware": Cache-aware - - "least_connection": Least connections (Python) - actor_system: Actor system instance - worker_name: Worker actor name - **kwargs: Policy-specific parameters (e.g., cache_threshold, etc.) - - Returns: - Scheduler instance - - Note: - For load-aware scheduling, recommend using StreamLoadScheduler from load_stream module - - Examples: - # Use cache-aware scheduler - scheduler = get_scheduler("cache_aware", actor_system, "worker", - cache_threshold=0.5) - - # Use round-robin scheduler - scheduler = get_scheduler("round_robin", actor_system, "worker") - """ - policy_map = { - "random": RustRandomScheduler, - "round_robin": RustRoundRobinScheduler, - "power_of_two": RustPowerOfTwoScheduler, - "consistent_hash": RustConsistentHashScheduler, - "cache_aware": RustCacheAwareScheduler, - "least_connection": LeastConnectionScheduler, - } - - scheduler_class = policy_map.get(policy_name) - if scheduler_class is None: - raise ValueError( - f"Unknown policy: {policy_name}. Available: {list(policy_map.keys())}" - ) - - # Policies that support kwargs - if policy_name == "cache_aware": - return scheduler_class(actor_system, worker_name, **kwargs) - else: - return scheduler_class(actor_system, worker_name) - - -# Exports -__all__ = [ - "Scheduler", - "LeastConnectionScheduler", - "RustRandomScheduler", - "RustRoundRobinScheduler", - "RustPowerOfTwoScheduler", - "RustConsistentHashScheduler", - "RustCacheAwareScheduler", - "get_scheduler", - "RUST_POLICIES_AVAILABLE", -] diff --git a/python/pulsing/serving/vllm/__init__.py b/python/pulsing/serving/vllm/__init__.py deleted file mode 100644 index da0c9ad98..000000000 --- a/python/pulsing/serving/vllm/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -"""vLLM Worker - High-performance inference Worker based on vLLM V1 engine - -Referencing Dynamo implementation, supports: -1. Prefill/Decode separation (PD Disaggregation) -2. Multimodal input processing (images) -3. KV Cache management and cleanup -4. LoRA dynamic loading/unloading -5. OpenAI-compatible text input/output mode -6. Engine monitoring and health checks -""" - -from .worker import VllmWorker - -__all__ = ["VllmWorker"] diff --git a/python/pulsing/serving/vllm/handlers.py b/python/pulsing/serving/vllm/handlers.py deleted file mode 100644 index 416891b9b..000000000 --- a/python/pulsing/serving/vllm/handlers.py +++ /dev/null @@ -1,706 +0,0 @@ -"""vLLM Worker Actor - High-performance inference Worker based on vLLM V1 engine - -Referencing Dynamo implementation, supports: -1. Prefill/Decode separation (PD Disaggregation) -2. Multimodal input processing (images) -3. KV Cache management and cleanup -4. LoRA dynamic loading/unloading -5. OpenAI-compatible text input/output mode -6. Engine monitoring and health checks -""" - -# Worker handlers: BaseWorkerHandler, PrefillWorkerHandler, DecodeWorkerHandler - -import asyncio -import logging -import tempfile -import time -import uuid -from abc import ABC, abstractmethod -from collections.abc import AsyncGenerator, Callable -from typing import Any - -from .sampling import build_sampling_params, build_sampling_params_openai -from .utils import ( - IMAGE_URL_KEY, - URL_VARIANT_KEY, - VIDEO_URL_KEY, - ImageLoader, - VllmEngineMonitor, - handle_engine_dead_error, - lora_name_to_id, -) - -try: - from vllm.inputs import TextPrompt, TokensPrompt - from vllm.lora.request import LoRARequest - from vllm.outputs import RequestOutput - from vllm.sampling_params import SamplingParams - from vllm.v1.engine.async_llm import AsyncLLM - from vllm.v1.engine.exceptions import EngineDeadError - - VLLM_AVAILABLE = True -except ImportError: - VLLM_AVAILABLE = False - EngineDeadError = Exception # Fallback for type hints - -logger = logging.getLogger(__name__) - - -class BaseWorkerHandler(ABC): - """Base Worker handler class, provides common functionality""" - - def __init__( - self, - engine: AsyncLLM, - default_sampling_params: dict[str, Any], - model_max_len: int | None = None, - enable_multimodal: bool = False, - use_vllm_tokenizer: bool = False, - on_engine_dead: Callable[[], None] | None = None, - ): - self.engine_client = engine - self.default_sampling_params = default_sampling_params - self.model_max_len = model_max_len - self.enable_multimodal = enable_multimodal - self.use_vllm_tokenizer = use_vllm_tokenizer - self.image_loader = ImageLoader() - self.temp_dirs: list[tempfile.TemporaryDirectory] = [] - # LoRA tracking - self.lora_id_for_name: dict[str, int] = {} - self.lora_name_to_path: dict[str, str] = {} - # Engine monitoring (unified management of callbacks and health status) - self._on_engine_dead = on_engine_dead - self.engine_monitor = VllmEngineMonitor(engine, on_engine_dead=on_engine_dead) - - @abstractmethod - async def generate(self, request: dict[str, Any]) -> AsyncGenerator[dict, None]: - raise NotImplementedError - - async def _extract_multimodal_data( - self, request: dict[str, Any] - ) -> dict[str, Any] | None: - """Extract and decode multimodal data""" - if "multi_modal_data" not in request or request["multi_modal_data"] is None: - return None - - # Safety check: reject if multimodal is not enabled - if not self.enable_multimodal: - raise ValueError( - "Received multimodal data but multimodal processing is not enabled" - ) - - mm_map = request["multi_modal_data"] - vllm_mm_data = {} - - # Process images - images = [] - for item in mm_map.get(IMAGE_URL_KEY, []): - if isinstance(item, dict) and URL_VARIANT_KEY in item: - url = item[URL_VARIANT_KEY] - try: - image = await self.image_loader.load_image(url) - images.append(image) - logger.debug(f"Loaded image from URL: {url[:80]}...") - except Exception: - logger.exception(f"Failed to load image from {url[:80]}...") - raise - - if images: - vllm_mm_data["image"] = images[0] if len(images) == 1 else images - logger.debug(f"Extracted {len(images)} image(s) for multimodal processing") - - # Process video (future extension) - if VIDEO_URL_KEY in mm_map: - logger.warning("Video multimodal data not yet supported") - - return vllm_mm_data if vllm_mm_data else None - - @staticmethod - def _build_completion_usage(request_output: RequestOutput) -> dict[str, Any]: - """Build usage statistics""" - return { - "prompt_tokens": ( - len(request_output.prompt_token_ids) - if request_output.prompt_token_ids - else None - ), - "completion_tokens": len(request_output.outputs[0].token_ids), - "total_tokens": ( - len(request_output.prompt_token_ids) - + len(request_output.outputs[0].token_ids) - if request_output.prompt_token_ids - else None - ), - "prompt_tokens_details": ( - {"cached_tokens": request_output.num_cached_tokens} - if request_output.num_cached_tokens - else None - ), - } - - @staticmethod - def _extract_logprobs( - output, num_output_tokens_so_far: int - ) -> tuple[list[float] | None, list[list[dict]] | None]: - """Extract logprobs information""" - if output.logprobs is None: - return None, None - - new_logprobs = output.logprobs[num_output_tokens_so_far:] - if not new_logprobs: - return None, None - - log_probs = [] - top_logprobs = [] - - for token_idx, token_logprobs_dict in enumerate(new_logprobs): - if token_logprobs_dict is None: - continue - - actual_token_id = output.token_ids[num_output_tokens_so_far + token_idx] - selected_logprob = token_logprobs_dict[actual_token_id] - log_probs.append(float(selected_logprob.logprob)) - - token_top_logprobs = [] - for tok_id, logprob_info in token_logprobs_dict.items(): - token_top_logprobs.append( - { - "rank": ( - logprob_info.rank if hasattr(logprob_info, "rank") else 0 - ), - "token_id": tok_id, - "token": ( - logprob_info.decoded_token - if hasattr(logprob_info, "decoded_token") - else None - ), - "logprob": float(logprob_info.logprob), - } - ) - top_logprobs.append(token_top_logprobs) - - return log_probs if log_probs else None, top_logprobs if top_logprobs else None - - async def generate_tokens( - self, - prompt, - sampling_params, - request_id, - lora_request=None, - data_parallel_rank: int | None = None, - ): - """Generate tokens - - Args: - prompt: Input prompt (TokensPrompt or TextPrompt) - sampling_params: Sampling parameters - request_id: Request ID - lora_request: LoRA request (optional) - data_parallel_rank: Data parallel rank (optional, for DP deployment) - """ - try: - if lora_request: - logger.debug( - f"Starting token generation for request {request_id} with LoRA: " - f"{lora_request.lora_name} (ID: {lora_request.lora_int_id})" - f"{f', dp_rank={data_parallel_rank}' if data_parallel_rank is not None else ''}" - ) - else: - logger.debug( - f"Starting token generation for request {request_id} (no LoRA)" - f"{f', dp_rank={data_parallel_rank}' if data_parallel_rank is not None else ''}" - ) - - gen = self.engine_client.generate( - prompt, - sampling_params, - request_id, - lora_request=lora_request, - data_parallel_rank=data_parallel_rank, - ) - - num_output_tokens_so_far = 0 - async for res in gen: - if not res.outputs: - if lora_request: - logger.debug( - f"Request {request_id} with LoRA {lora_request.lora_name} " - "returned no outputs" - ) - yield {"finish_reason": "error", "token_ids": []} - break - - output = res.outputs[0] - next_total_toks = len(output.token_ids) - out = {"token_ids": output.token_ids[num_output_tokens_so_far:]} - - # Extract logprobs - log_probs, top_logprobs = self._extract_logprobs( - output, num_output_tokens_so_far - ) - if log_probs is not None: - out["log_probs"] = log_probs - if top_logprobs is not None: - out["top_logprobs"] = top_logprobs - - if output.finish_reason: - out["finish_reason"] = output.finish_reason - out["completion_usage"] = BaseWorkerHandler._build_completion_usage( - request_output=res - ) - if lora_request: - logger.debug( - f"Completed token generation for request {request_id} with LoRA " - f"{lora_request.lora_name}: {next_total_toks} output tokens, " - f"finish_reason={output.finish_reason}" - ) - else: - logger.debug( - f"Completed token generation for request {request_id}: " - f"{next_total_toks} output tokens, finish_reason={output.finish_reason}" - ) - if output.stop_reason: - out["stop_reason"] = output.stop_reason - yield out - num_output_tokens_so_far = next_total_toks - - except asyncio.CancelledError: - raise GeneratorExit( - "Engine was shut down during token generation" - ) from None - except EngineDeadError as e: - handle_engine_dead_error(e, "token generation", self._on_engine_dead) - raise - except Exception as e: - logger.exception(f"Error in token generation: {e}") - raise - - async def clear_kv_cache(self) -> dict[str, Any]: - """Clear KV Cache""" - try: - await self.engine_client.reset_prefix_cache() - return {"status": "success", "message": "KV cache cleared"} - except Exception as e: - logger.exception("Failed to clear KV cache") - return {"status": "error", "message": str(e)} - - async def load_lora(self, lora_name: str, lora_path: str) -> dict[str, Any]: - """Dynamically load LoRA adapter - - Args: - lora_name: LoRA adapter name - lora_path: LoRA adapter path (local filesystem path) - - Returns: - Dictionary containing status - """ - try: - if lora_name in self.lora_id_for_name: - return { - "status": "error", - "message": f"LoRA adapter '{lora_name}' is already loaded", - } - - # Generate deterministic ID - lora_id = lora_name_to_id(lora_name) - - # Add LoRA to engine - await self.engine_client.add_lora( - LoRARequest( - lora_name=lora_name, lora_int_id=lora_id, lora_path=lora_path - ) - ) - - # Track LoRA - self.lora_id_for_name[lora_name] = lora_id - self.lora_name_to_path[lora_name] = lora_path - logger.info( - f"Successfully loaded LoRA adapter: {lora_name} with ID {lora_id}" - ) - - return { - "status": "success", - "message": f"LoRA adapter '{lora_name}' loaded successfully", - "lora_name": lora_name, - "lora_id": lora_id, - } - except Exception as e: - logger.exception(f"Failed to load LoRA adapter: {e}") - return {"status": "error", "message": str(e)} - - async def unload_lora(self, lora_name: str) -> dict[str, Any]: - """Unload LoRA adapter - - Args: - lora_name: LoRA adapter name - - Returns: - Dictionary containing status - """ - try: - if lora_name not in self.lora_id_for_name: - return { - "status": "error", - "message": f"LoRA adapter '{lora_name}' not found. Available LoRAs: {list(self.lora_id_for_name.keys())}", - } - - logger.debug(f"Unloading LoRA adapter: {lora_name}") - lora_id = self.lora_id_for_name[lora_name] - - await self.engine_client.remove_lora(lora_id) - - # Remove from tracking dictionary - del self.lora_id_for_name[lora_name] - if lora_name in self.lora_name_to_path: - del self.lora_name_to_path[lora_name] - - logger.info( - f"Successfully unloaded LoRA adapter: {lora_name} with ID {lora_id}" - ) - return { - "status": "success", - "message": f"LoRA adapter '{lora_name}' unloaded successfully", - "lora_name": lora_name, - "lora_id": lora_id, - } - except Exception as e: - logger.exception(f"Failed to unload LoRA adapter: {e}") - return {"status": "error", "message": str(e)} - - async def list_loras(self) -> dict[str, Any]: - """List all loaded LoRA adapters - - Returns: - Dictionary containing LoRA list - """ - try: - loras = dict(self.lora_id_for_name) - return { - "status": "success", - "loras": loras, - "count": len(loras), - } - except Exception as e: - logger.exception(f"Failed to list LoRA adapters: {e}") - return {"status": "error", "message": str(e)} - - def add_temp_dir(self, temp_dir: tempfile.TemporaryDirectory) -> None: - """Add temporary directory for later cleanup""" - if temp_dir is not None: - self.temp_dirs.append(temp_dir) - - def cleanup(self): - """Clean up resources""" - for temp_dir in self.temp_dirs: - try: - temp_dir.cleanup() - except Exception as e: - logger.warning(f"Failed to clean up temp directory: {e}") - - -class PrefillWorkerHandler(BaseWorkerHandler): - """Prefill Worker handler - only executes prefill phase""" - - async def generate(self, request: dict[str, Any]) -> AsyncGenerator[dict, None]: - """Generate prefill results""" - request_id = f"prefill-{uuid.uuid4().hex[:8]}" - logger.debug(f"Prefill Request ID: {request_id}") - - # Extract multimodal data - multi_modal_data = await self._extract_multimodal_data(request) - - token_ids = request.get("token_ids", []) - prompt = TokensPrompt( - prompt_token_ids=token_ids, multi_modal_data=multi_modal_data - ) - - # Build sampling parameters - sampling_params = build_sampling_params( - request, self.default_sampling_params, self.model_max_len - ) - - # Configure prefill mode: only generate 1 token, enable remote decode - if sampling_params.extra_args is None: - sampling_params.extra_args = {} - sampling_params.extra_args["kv_transfer_params"] = { - "do_remote_decode": True, - } - sampling_params.max_tokens = 1 - sampling_params.min_tokens = 1 - - # LoRA support - lora_request = None - model_name = request.get("model") - if model_name and model_name in self.lora_id_for_name: - lora_id = self.lora_id_for_name[model_name] - lora_request = LoRARequest( - lora_name=model_name, - lora_int_id=lora_id, - lora_path=self.lora_name_to_path[model_name], - ) - logger.info( - f"Prefill request {request_id} will use LoRA adapter: {model_name} (ID: {lora_id})" - ) - - # Get data_parallel_rank (referencing Dynamo handlers.py) - dp_rank = request.get("dp_rank", None) - - try: - gen = self.engine_client.generate( - prompt, - sampling_params, - request_id, - lora_request=lora_request, - data_parallel_rank=dp_rank, - ) - - async for res in gen: - logger.debug(f"kv transfer params: {res.kv_transfer_params}") - - token_ids = res.outputs[0].token_ids if res.outputs else [] - - output: dict[str, Any] = { - "token_ids": list(token_ids), - "disaggregated_params": ( - {"kv_transfer_params": res.kv_transfer_params} - if res.kv_transfer_params - else None - ), - "completion_usage": BaseWorkerHandler._build_completion_usage( - request_output=res - ), - } - - if lora_request: - logger.info( - f"Prefill completed for request {request_id} with LoRA {lora_request.lora_name}: " - f"generated {len(token_ids)} token(s), " - f"has_kv_params={res.kv_transfer_params is not None}" - ) - - yield output - except asyncio.CancelledError: - raise GeneratorExit("Prefill engine was shut down") from None - except EngineDeadError as e: - handle_engine_dead_error(e, "prefill", self._on_engine_dead) - raise - - -class DecodeWorkerHandler(BaseWorkerHandler): - """Decode Worker handler - executes decode phase or full inference""" - - async def generate(self, request: dict[str, Any]) -> AsyncGenerator[dict, None]: - """Generate decode results""" - request_id = f"decode-{uuid.uuid4().hex[:8]}" - logger.debug( - f"Decode Request ID: {request_id}, request keys: {list(request.keys())}" - ) - - # Auto-detect input type - has_token_ids = "token_ids" in request - has_text_input = "prompt" in request or "messages" in request - - if self.use_vllm_tokenizer or (has_text_input and not has_token_ids): - # Text input/output mode - async for chunk in self._generate_text_mode(request, request_id): - yield chunk - elif has_token_ids: - # Token input/output mode - async for chunk in self._generate_token_mode(request, request_id): - yield chunk - else: - # Neither token_ids nor text input - raise ValueError( - "Request must contain either 'token_ids' or 'prompt'/'messages' field" - ) - - async def _generate_token_mode( - self, request: dict[str, Any], request_id: str - ) -> AsyncGenerator[dict, None]: - """Token input/output mode generation""" - # Extract multimodal data - multi_modal_data = await self._extract_multimodal_data(request) - - # Check if token_ids exist - if "token_ids" not in request: - raise ValueError( - "Request must contain 'token_ids' field for token mode generation. " - "Use 'use_vllm_tokenizer=True' for text mode." - ) - - prompt = TokensPrompt( - prompt_token_ids=request["token_ids"], multi_modal_data=multi_modal_data - ) - - # Build sampling parameters - sampling_params = build_sampling_params( - request, self.default_sampling_params, self.model_max_len - ) - - # Handle prefill result (if in PD separation mode) - prefill_result = request.get("prefill_result") - if prefill_result and isinstance(prefill_result, dict): - kv_params = prefill_result.get("disaggregated_params", {}).get( - "kv_transfer_params" - ) - if kv_params is not None: - if sampling_params.extra_args is None: - sampling_params.extra_args = {} - sampling_params.extra_args["kv_transfer_params"] = kv_params - logger.debug( - f"Using disaggregated params from prefill for request {request_id}" - ) - - prefill_prompt_tokens_details = ( - prefill_result.get("prompt_tokens_details") if prefill_result else None - ) - - # LoRA support - lora_request = None - model_name = request.get("model") - if model_name and model_name in self.lora_id_for_name: - lora_id = self.lora_id_for_name[model_name] - lora_request = LoRARequest( - lora_name=model_name, - lora_int_id=lora_id, - lora_path=self.lora_name_to_path[model_name], - ) - logger.info( - f"Decode request {request_id} will use LoRA adapter: {model_name} (ID: {lora_id})" - ) - - # Get data_parallel_rank (referencing Dynamo handlers.py) - dp_rank = request.get("dp_rank", None) - - try: - async for tok in self.generate_tokens( - prompt, - sampling_params, - request_id, - lora_request=lora_request, - data_parallel_rank=dp_rank, - ): - if prefill_result is not None and "completion_usage" in tok: - tok["completion_usage"]["prompt_tokens_details"] = ( - prefill_prompt_tokens_details - ) - yield tok - except Exception as e: - logger.exception(f"Error in decode generation: {e}") - raise - - async def _generate_text_mode( - self, request: dict[str, Any], request_id: str - ) -> AsyncGenerator[dict, None]: - """Text input/output mode generation (OpenAI compatible)""" - # Get text input - prompt_text = None - - # Try different input formats - if "prompt" in request: - prompt_text = request["prompt"] - elif "messages" in request: - messages = request["messages"] - if isinstance(messages, list) and len(messages) > 0: - # If message list, take last message content - last_message = messages[-1] - if isinstance(last_message, dict): - prompt_text = last_message.get("content", "") - else: - prompt_text = str(last_message) - else: - prompt_text = str(messages) - elif "text" in request: - prompt_text = request["text"] - - if not prompt_text: - raise ValueError( - "Request must contain 'prompt', 'messages', or 'text' field for text mode generation" - ) - - # Critical fix: In text mode, must first use tokenizer to convert text to token_ids - # This is because vLLM needs prompt_token_ids when applying penalties - # Referencing Dynamo's InputParamManager implementation - - # Get tokenizer - tokenizer = getattr(self.engine_client, "tokenizer", None) - if not tokenizer: - raise ValueError( - "Tokenizer not available. Text mode requires tokenizer to convert text to token_ids. " - "This is necessary for applying sampling penalties." - ) - - # Use tokenizer to convert text to token_ids - try: - token_ids = tokenizer.encode(prompt_text) - prompt = TokensPrompt(prompt_token_ids=token_ids) - except Exception as e: - logger.exception(f"Failed to tokenize prompt: {e}") - raise ValueError(f"Failed to tokenize prompt: {e}") from e - - # Build sampling parameters - sampling_params = build_sampling_params_openai( - request, self.default_sampling_params - ) - - # Get data_parallel_rank (referencing Dynamo handlers.py) - dp_rank = request.get("dp_rank", None) - - openai_request_id = request.get("id") or request.get("request_id", request_id) - previous_text = "" - - try: - gen = self.engine_client.generate( - prompt, - sampling_params, - request_id, - data_parallel_rank=dp_rank, - ) - - async for res in gen: - if not res.outputs: - yield { - "id": openai_request_id, - "created": int(time.time()), - "object": "chat.completion.chunk", - "model": "unknown", - "choices": [ - { - "index": 0, - "delta": {"role": "assistant", "content": ""}, - "finish_reason": "error", - } - ], - } - break - - output = res.outputs[0] - delta_text = output.text[len(previous_text) :] - previous_text = output.text - - choice_data = { - "index": 0, - "delta": { - "role": "assistant", - "content": delta_text, - }, - "finish_reason": output.finish_reason, - } - - chunk = { - "id": openai_request_id, - "created": int(time.time()), - "object": "chat.completion.chunk", - "model": "unknown", - "choices": [choice_data], - } - - yield chunk - - except EngineDeadError as e: - handle_engine_dead_error(e, "text mode generation", self._on_engine_dead) - raise - except Exception as e: - logger.exception(f"Error in text mode generation: {e}") - raise diff --git a/python/pulsing/serving/vllm/sampling.py b/python/pulsing/serving/vllm/sampling.py deleted file mode 100644 index 67e2d3110..000000000 --- a/python/pulsing/serving/vllm/sampling.py +++ /dev/null @@ -1,123 +0,0 @@ -"""Sampling parameter construction functions - -Provides two modes of sampling parameter construction: -- build_sampling_params: Token mode -- build_sampling_params_openai: OpenAI-compatible text mode -""" - -import logging -from typing import Any - -try: - from PIL import Image - from vllm.engine.arg_utils import AsyncEngineArgs - from vllm.inputs import TextPrompt, TokensPrompt - from vllm.lora.request import LoRARequest - from vllm.outputs import RequestOutput - from vllm.sampling_params import SamplingParams - from vllm.usage.usage_lib import UsageContext - from vllm.v1.engine.async_llm import AsyncLLM - from vllm.v1.engine.exceptions import EngineDeadError - - VLLM_AVAILABLE = True -except ImportError: - VLLM_AVAILABLE = False - - -logger = logging.getLogger(__name__) - - -def build_sampling_params( - request: dict[str, Any], - default_sampling_params: dict[str, Any], - model_max_len: int | None = None, -) -> SamplingParams: - """Build SamplingParams from request - - Args: - request: Request dictionary - default_sampling_params: Default sampling parameters - model_max_len: Model maximum length - - Returns: - Configured SamplingParams - """ - sampling_params = SamplingParams(**default_sampling_params) - - # Apply sampling options - sampling_options = request.get("sampling_options", {}) - for key, value in sampling_options.items(): - if value is not None and hasattr(sampling_params, key): - setattr(sampling_params, key, value) - - # Apply stop conditions - stop_conditions = request.get("stop_conditions", {}) - for key, value in stop_conditions.items(): - if value is not None and hasattr(sampling_params, key): - setattr(sampling_params, key, value) - - # Handle max_tokens - provided_max_tokens = stop_conditions.get("max_tokens") - token_ids = request.get("token_ids", []) - input_length = len(token_ids) - if model_max_len is not None and provided_max_tokens is None: - # Ensure default generates at least 1 token - dynamic_default = max(1, model_max_len - input_length) - sampling_params.max_tokens = dynamic_default - - return sampling_params - - -def build_sampling_params_openai( - request: dict[str, Any], - default_sampling_params: dict[str, Any], -) -> SamplingParams: - """Build SamplingParams from OpenAI-compatible request - - Args: - request: OpenAI-style request dictionary - default_sampling_params: Default sampling parameters - - Returns: - Configured SamplingParams - """ - sampling_params = SamplingParams(**default_sampling_params) - sampling_params.detokenize = True - - # Map OpenAI parameters to SamplingParams - openai_mapping = { - "temperature": "temperature", - "top_p": "top_p", - "presence_penalty": "presence_penalty", - "frequency_penalty": "frequency_penalty", - "seed": "seed", - "top_k": "top_k", - "repetition_penalty": "repetition_penalty", - "min_p": "min_p", - "length_penalty": "length_penalty", - "use_beam_search": "use_beam_search", - } - - for req_key, param_key in openai_mapping.items(): - if req_key in request and request[req_key] is not None: - if hasattr(sampling_params, param_key): - setattr(sampling_params, param_key, request[req_key]) - - # Handle max_tokens (supports both max_tokens and max_new_tokens) - max_tokens_value = request.get("max_tokens") or request.get("max_new_tokens") - if max_tokens_value is not None: - sampling_params.max_tokens = max_tokens_value - - # Handle stop sequences - if "stop" in request and request["stop"] is not None: - sampling_params.stop = request["stop"] - - # Handle ignore_eos - if "ignore_eos" in request and request["ignore_eos"] is not None: - sampling_params.ignore_eos = request["ignore_eos"] - - # Handle min_tokens - if "min_tokens" in request and request["min_tokens"] is not None: - sampling_params.min_tokens = request["min_tokens"] - - return sampling_params diff --git a/python/pulsing/serving/vllm/utils.py b/python/pulsing/serving/vllm/utils.py deleted file mode 100644 index 7c18f88c9..000000000 --- a/python/pulsing/serving/vllm/utils.py +++ /dev/null @@ -1,358 +0,0 @@ -"""vLLM Worker utility functions and helper classes - -Contains: -- VllmEngineMonitor: Engine health monitoring -- ImageLoader: Multimodal image loading -- Environment variable setup functions -""" - -import asyncio -import base64 -import hashlib -import logging -import os -import platform -from collections.abc import Callable -from io import BytesIO -from typing import Any, Final - -try: - from PIL import Image - from vllm.engine.arg_utils import AsyncEngineArgs - from vllm.inputs import TextPrompt, TokensPrompt - from vllm.lora.request import LoRARequest - from vllm.outputs import RequestOutput - from vllm.sampling_params import SamplingParams - from vllm.usage.usage_lib import UsageContext - from vllm.v1.engine.async_llm import AsyncLLM - from vllm.v1.engine.exceptions import EngineDeadError - - VLLM_AVAILABLE = True -except ImportError: - VLLM_AVAILABLE = False - - -logger = logging.getLogger(__name__) - - -# ===== EngineDeadError unified handling ===== - - -def handle_engine_dead_error( - error: Exception, - context: str, - on_engine_dead: Callable[[], None] | None = None, -) -> None: - """Unified handling of EngineDeadError - - Args: - error: Caught exception - context: Description of the context where error occurred - on_engine_dead: Engine dead callback function - """ - logger.error(f"vLLM EngineDeadError during {context}: {error}") - if on_engine_dead is not None: - logger.warning(f"Calling on_engine_dead callback from {context}...") - try: - on_engine_dead() - except Exception as callback_error: - logger.exception(f"Error in on_engine_dead callback: {callback_error}") - - -# Multimodal data dictionary keys -IMAGE_URL_KEY: Final = "image_url" -VIDEO_URL_KEY: Final = "video_url" -URL_VARIANT_KEY: Final = "Url" -DECODED_VARIANT_KEY: Final = "Decoded" - - -# ===== Utility functions ===== - - -def lora_name_to_id(lora_name: str) -> int: - """Generate deterministic integer ID from LoRA name - - Uses blake2b hash algorithm to generate 64-bit integer ID - - Args: - lora_name: LoRA adapter name - - Returns: - 64-bit integer ID - """ - # Use blake2b to generate 8-byte hash - hash_digest = hashlib.blake2b(lora_name.encode("utf-8"), digest_size=8).digest() - # Convert to unsigned 64-bit integer - return int.from_bytes(hash_digest, byteorder="big", signed=False) - - -def _is_macos() -> bool: - """Detect if running on macOS""" - return platform.system() == "Darwin" - - -class VllmEngineMonitor: - """vLLM engine monitor for collecting engine runtime statistics and continuous health checks - - Referencing Dynamo engine_monitor.py implementation, supports: - 1. Static configuration information retrieval - 2. Continuous background health checks - 3. Engine death detection and callback notification - """ - - # Health check interval (seconds) - HEALTH_CHECK_INTERVAL = 2 - # Engine shutdown timeout (seconds) - ENGINE_SHUTDOWN_TIMEOUT = 30 - - def __init__( - self, - engine: "AsyncLLM", - on_engine_dead: "Callable[[], None] | None" = None, - ): - """Initialize engine monitor - - Args: - engine: vLLM AsyncLLM engine instance - on_engine_dead: Callback function when engine dies (optional) - """ - self.engine = engine - self._on_engine_dead = on_engine_dead - self._monitor_task: asyncio.Task | None = None - self._is_healthy = True - self._last_error: str | None = None - - def start_monitoring( - self, on_engine_dead: "Callable[[], None] | None" = None - ) -> None: - """Start background health check task - - Args: - on_engine_dead: Callback function when engine dies (optional, overrides constructor setting) - """ - if on_engine_dead is not None: - self._on_engine_dead = on_engine_dead - - if self._monitor_task is not None and not self._monitor_task.done(): - logger.warning("Health check task already running") - return - - self._monitor_task = asyncio.create_task(self._health_check_loop()) - logger.info( - f"VllmEngineMonitor started, health check interval: {self.HEALTH_CHECK_INTERVAL}s" - ) - - def stop_monitoring(self) -> None: - """Stop background health check task""" - if self._monitor_task is not None and not self._monitor_task.done(): - self._monitor_task.cancel() - logger.info("VllmEngineMonitor stopped") - - async def _health_check_loop(self) -> None: - """Continuous health check loop (referencing Dynamo engine_monitor.py)""" - while True: - try: - # Call vLLM engine health check method - await self.engine.check_health() - self._is_healthy = True - self._last_error = None - await asyncio.sleep(self.HEALTH_CHECK_INTERVAL) - - except Exception as e: - # Check if it's EngineDeadError - error_name = type(e).__name__ - if error_name == "EngineDeadError" or "EngineDeadError" in str(type(e)): - logger.error(f"vLLM EngineDeadError detected: {e}") - self._is_healthy = False - self._last_error = str(e) - - # Try to shutdown engine - await self._shutdown_engine() - - # Call callback function - if self._on_engine_dead is not None: - logger.warning("Calling on_engine_dead callback...") - try: - self._on_engine_dead() - except Exception as callback_error: - logger.exception( - f"Error in on_engine_dead callback: {callback_error}" - ) - - # Exit health check loop - break - else: - # Other exceptions, log but continue checking - logger.warning(f"Health check failed with non-fatal error: {e}") - self._is_healthy = False - self._last_error = str(e) - await asyncio.sleep(self.HEALTH_CHECK_INTERVAL) - - except asyncio.CancelledError: - logger.debug("Health check loop cancelled") - break - - async def _shutdown_engine(self) -> None: - """Shutdown vLLM engine (with timeout protection)""" - logger.warning("Initiating vLLM engine shutdown...") - - try: - # Use asyncio.wait_for to add timeout protection - await asyncio.wait_for( - asyncio.to_thread(self.engine.shutdown), - timeout=self.ENGINE_SHUTDOWN_TIMEOUT, - ) - logger.info("vLLM engine shutdown completed") - except asyncio.TimeoutError: - logger.error( - f"vLLM engine shutdown timed out after {self.ENGINE_SHUTDOWN_TIMEOUT}s" - ) - except Exception as e: - logger.warning(f"vLLM engine shutdown failed: {e}") - - @property - def is_healthy(self) -> bool: - """Return whether engine is healthy""" - return self._is_healthy - - @property - def last_error(self) -> str | None: - """Return last error message""" - return self._last_error - - def get_cache_info(self) -> dict[str, Any]: - """Get cache configuration information""" - try: - config = self.engine.vllm_config - return { - "num_gpu_blocks": config.cache_config.num_gpu_blocks, - "max_num_seqs": config.scheduler_config.max_num_seqs, - "max_num_batched_tokens": config.scheduler_config.max_num_batched_tokens, - "block_size": config.cache_config.block_size, - } - except Exception as e: - logger.warning(f"Failed to get cache info: {e}") - return {} - - def get_model_config(self) -> dict[str, Any]: - """Get model configuration information""" - try: - config = self.engine.vllm_config - model_config = config.model_config - return { - "max_model_len": model_config.max_model_len, - "vocab_size": model_config.vocab_size, - "dtype": str(model_config.dtype), - } - except Exception as e: - logger.warning(f"Failed to get model config: {e}") - return {} - - def get_health_status(self) -> dict[str, Any]: - """Get engine health status""" - try: - cache_info = self.get_cache_info() - model_config = self.get_model_config() - - status = "healthy" if self._is_healthy else "unhealthy" - - result = { - "status": status, - "cache_info": cache_info, - "model_config": model_config, - } - - if self._last_error: - result["last_error"] = self._last_error - - return result - except Exception as e: - logger.exception(f"Failed to get health status: {e}") - return { - "status": "unhealthy", - "error": str(e), - } - - def __del__(self): - """Destructor, ensure monitoring task is stopped""" - self.stop_monitoring() - - -def _setup_macos_metal_env( - mlx_device: str | None = None, - metal_memory_fraction: float | None = None, -) -> None: - """Setup macOS Metal/MLX environment variables - - Args: - mlx_device: MLX device type ('gpu' or 'cpu'), default 'gpu' - metal_memory_fraction: Metal memory usage ratio (0.0-1.0), default 0.8 - """ - if not _is_macos(): - return - - # Set MLX device - if mlx_device is None: - mlx_device = os.environ.get("VLLM_MLX_DEVICE", "gpu") - - if "VLLM_MLX_DEVICE" not in os.environ: - os.environ["VLLM_MLX_DEVICE"] = mlx_device - logger.info(f"Set VLLM_MLX_DEVICE={mlx_device} for macOS Metal support") - - # Set Metal memory usage ratio - if metal_memory_fraction is None: - metal_memory_fraction_str = os.environ.get("VLLM_METAL_MEMORY_FRACTION") - if metal_memory_fraction_str: - metal_memory_fraction = float(metal_memory_fraction_str) - else: - metal_memory_fraction = 0.8 # Default 80% - - if "VLLM_METAL_MEMORY_FRACTION" not in os.environ: - os.environ["VLLM_METAL_MEMORY_FRACTION"] = str(metal_memory_fraction) - logger.info( - f"Set VLLM_METAL_MEMORY_FRACTION={metal_memory_fraction} for macOS Metal support" - ) - - -class ImageLoader: - """Image loader, supports URL and Base64 encoded images""" - - def __init__(self, cache_size: int = 100): - self._cache: dict[str, Image.Image] = {} - self._cache_size = cache_size - - async def load_image(self, image_source: str) -> Image.Image: - """Load image, supports Data URL (Base64) and HTTP(S) URL - - Args: - image_source: Image source, can be data: URL or http(s): URL - - Returns: - PIL Image object - """ - # Check cache - if image_source in self._cache: - logger.debug(f"Image cache hit: {image_source[:80]}...") - return self._cache[image_source] - - if image_source.startswith("data:image"): - try: - # data:image/png;base64,xxxx - header, data = image_source.split(",", 1) - image_bytes = base64.b64decode(data) - image = await asyncio.to_thread(Image.open, BytesIO(image_bytes)) - self._add_to_cache(image_source, image) - return image - except Exception as e: - raise ValueError(f"Failed to decode base64 image: {e}") from e - - # HTTP URL download not yet supported, recommend converting to Base64 by frontend/Processor - raise ValueError(f"Unsupported image source: {image_source[:20]}...") - - def _add_to_cache(self, key: str, image: Image.Image) -> None: - """Add to cache, clean old entries if size limit exceeded""" - if len(self._cache) >= self._cache_size: - # Simple FIFO strategy - oldest_key = next(iter(self._cache)) - del self._cache[oldest_key] - self._cache[key] = image diff --git a/python/pulsing/serving/vllm/worker.py b/python/pulsing/serving/vllm/worker.py deleted file mode 100644 index 276d72dfb..000000000 --- a/python/pulsing/serving/vllm/worker.py +++ /dev/null @@ -1,568 +0,0 @@ -"""vLLM Worker - High-performance inference Worker based on vLLM V1 engine (pulsing.remote) - -Referencing Dynamo implementation, supports: -1. Prefill/Decode separation (PD Disaggregation) -2. Multimodal input processing (images) -3. KV Cache management and cleanup -4. LoRA dynamic loading/unloading -5. OpenAI-compatible text input/output mode -6. Engine monitoring and health checks -""" - -import asyncio -import logging -import os -import uuid -from typing import Any - -from pulsing.core import ActorId, StreamMessage, remote - -from .handlers import BaseWorkerHandler, DecodeWorkerHandler, PrefillWorkerHandler -from .utils import _is_macos, _setup_macos_metal_env - -try: - from vllm.engine.arg_utils import AsyncEngineArgs - from vllm.usage.usage_lib import UsageContext - from vllm.v1.engine.async_llm import AsyncLLM - - VLLM_AVAILABLE = True -except ImportError: - VLLM_AVAILABLE = False - -logger = logging.getLogger(__name__) - - -@remote -class VllmWorker: - """vLLM inference Worker,通过 pulsing.remote 暴露方法。 - - 支持 vLLM V1 engine,功能对齐 Dynamo: - 1. PD 分离(Prefill / Decode 角色) - 2. 多模态输入(Image) - 3. KV Cache 管理与清理 - 4. LoRA 动态加载/卸载 - 5. OpenAI 兼容文本输入/输出 - """ - - def __init__( - self, - model: str, - role: str = "aggregated", # Options: aggregated, prefill, decode - engine_args: dict[str, Any] | None = None, - gpu_memory_utilization: float = 0.9, - trust_remote_code: bool = True, - max_new_tokens: int = 512, - enable_multimodal: bool = False, - use_vllm_tokenizer: bool = False, - # Distributed inference parameters (referencing Dynamo implementation) - tensor_parallel_size: int = 1, # TP: Tensor parallelism, split model across multiple GPUs - pipeline_parallel_size: int = 1, # PP: Pipeline parallelism, distribute model layers - data_parallel_size: int = 1, # DP: Data parallelism - data_parallel_rank: int | None = None, # DP rank, for multi-replica deployment - enable_expert_parallel: bool = False, # EP: MoE model expert parallelism - distributed_executor_backend: str | None = None, # "mp" or "ray" - # macOS Metal/MLX support parameters - mlx_device: ( - str | None - ) = None, # 'gpu' or 'cpu', default read from environment variable - metal_memory_fraction: float | None = None, # 0.0-1.0, default 0.8 - **kwargs, - ): - self.model = model - self.role = role.lower() - self.default_max_new_tokens = max_new_tokens - self.enable_multimodal = enable_multimodal - self.use_vllm_tokenizer = use_vllm_tokenizer - - # Distributed configuration - self.tensor_parallel_size = tensor_parallel_size - self.pipeline_parallel_size = pipeline_parallel_size - self.data_parallel_size = data_parallel_size - self.data_parallel_rank = data_parallel_rank or 0 - self.enable_expert_parallel = enable_expert_parallel - self._is_primary_rank = data_parallel_rank is None or data_parallel_rank == 0 - - # macOS Metal/MLX environment - _setup_macos_metal_env(mlx_device, metal_memory_fraction) - - # Build engine arguments - self.engine_args_dict = self._build_engine_args( - engine_args=engine_args, - model=model, - gpu_memory_utilization=gpu_memory_utilization, - trust_remote_code=trust_remote_code, - tensor_parallel_size=tensor_parallel_size, - pipeline_parallel_size=pipeline_parallel_size, - data_parallel_size=data_parallel_size, - data_parallel_rank=data_parallel_rank, - enable_expert_parallel=enable_expert_parallel, - distributed_executor_backend=distributed_executor_backend, - **kwargs, - ) - - self.worker_id = f"vllm-{self.role}-{uuid.uuid4().hex[:8]}" - self._engine: AsyncLLM | None = None - self._handler: BaseWorkerHandler | None = None - self._is_ready = False - self._engine_is_dead = False - self._actor_id: ActorId | None = None - self._init_task: asyncio.Task | None = None - - @staticmethod - def _build_engine_args( - engine_args: dict[str, Any] | None, - model: str, - gpu_memory_utilization: float, - trust_remote_code: bool, - tensor_parallel_size: int, - pipeline_parallel_size: int, - data_parallel_size: int, - data_parallel_rank: int | None, - enable_expert_parallel: bool, - distributed_executor_backend: str | None, - **kwargs, - ) -> dict[str, Any]: - """Build vLLM engine arguments - - Integrates basic parameters and distributed parameters processing logic. - """ - args = engine_args.copy() if engine_args else {} - - # Basic parameters - args.update( - { - "model": model, - "gpu_memory_utilization": gpu_memory_utilization, - "trust_remote_code": trust_remote_code, - "generation_config": "vllm", # Use vllm default config to avoid HF's repetition_penalty - } - ) - - # Distributed parameters (only add when not default values) - if tensor_parallel_size > 1: - args["tensor_parallel_size"] = tensor_parallel_size - if pipeline_parallel_size > 1: - args["pipeline_parallel_size"] = pipeline_parallel_size - if data_parallel_size > 1: - args["data_parallel_size"] = data_parallel_size - if data_parallel_rank is not None: - args["data_parallel_rank"] = data_parallel_rank - if enable_expert_parallel: - args["enable_expert_parallel"] = enable_expert_parallel - - # Distributed executor backend (default to mp when TP=1 to avoid GIL issues) - if distributed_executor_backend: - args["distributed_executor_backend"] = distributed_executor_backend - elif tensor_parallel_size == 1: - args["distributed_executor_backend"] = "mp" - - # Filter out custom parameters, only keep vLLM-supported parameters - excluded_keys = { - "max_new_tokens", - "enable_multimodal", - "use_vllm_tokenizer", - "tensor_parallel_size", - "pipeline_parallel_size", - "data_parallel_size", - "data_parallel_rank", - "enable_expert_parallel", - "distributed_executor_backend", - } - for key, value in kwargs.items(): - if key not in excluded_keys: - args[key] = value - - return args - - async def on_start(self, actor_id: ActorId) -> None: - """Return quickly, initialize engine in background""" - self._actor_id = actor_id - if not VLLM_AVAILABLE: - logger.error("vLLM not installed or version incompatible.") - self._is_ready = False - return - - # Initialize engine in background task - async def init_background(): - try: - logger.info( - f"Starting vLLM engine initialization for model: {self.model}" - ) - await self._init_engine() - if self._is_ready: - logger.info( - f"vLLM engine initialized successfully for {self.worker_id}" - ) - else: - logger.error( - "vLLM engine initialization completed but engine is not ready" - ) - except Exception as e: - logger.exception(f"Failed to initialize vLLM engine: {e}") - self._is_ready = False - - self._init_task = asyncio.create_task(init_background()) - logger.info( - f"vLLM Worker {self.worker_id} started, engine initializing in background..." - ) - - async def _init_engine(self): - if self._is_ready: - return - - logger.info(f"Initializing vLLM ({self.role}) for model: {self.model}") - - # Detect platform and log information - if _is_macos(): - mlx_device = os.environ.get("VLLM_MLX_DEVICE", "not set") - metal_memory = os.environ.get("VLLM_METAL_MEMORY_FRACTION", "not set") - logger.info( - f"Running on macOS with Metal support: " - f"VLLM_MLX_DEVICE={mlx_device}, " - f"VLLM_METAL_MEMORY_FRACTION={metal_memory}" - ) - - os.environ["VLLM_NO_USAGE_STATS"] = "1" - os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" - - # Move entire initialization process to thread pool - def init_sync(): - """Synchronous initialization function, executed in thread pool""" - args = AsyncEngineArgs(**self.engine_args_dict) - usage_context = UsageContext.OPENAI_API_SERVER - engine_config = args.create_engine_config(usage_context=usage_context) - - return AsyncLLM.from_vllm_config( - vllm_config=engine_config, - usage_context=usage_context, - disable_log_requests=True, - ) - - loop = asyncio.get_event_loop() - logger.info("Starting vLLM engine initialization in thread pool...") - self._engine = await loop.run_in_executor(None, init_sync) - - # Create corresponding handler - model_max_len = getattr( - getattr(self._engine.vllm_config, "model_config", None), - "max_model_len", - None, - ) - - # Get default sampling parameters - default_sampling_params = {} - try: - default_sampling_params = ( - AsyncEngineArgs(**self.engine_args_dict) - .create_model_config() - .get_diff_sampling_param() - ) - logger.debug(f"Default sampling params: {default_sampling_params}") - - # If using text mode but penalties are detected, ensure tokenizer is available - # Otherwise clear these penalties to avoid AssertionError - if self.use_vllm_tokenizer: - has_penalties = ( - default_sampling_params.get("repetition_penalty", 1.0) != 1.0 - or default_sampling_params.get("presence_penalty", 0.0) != 0.0 - or default_sampling_params.get("frequency_penalty", 0.0) != 0.0 - ) - if has_penalties: - tokenizer_available = ( - hasattr(self._engine, "tokenizer") - and self._engine.tokenizer is not None - ) - logger.info( - f"Default params have penalties, tokenizer_available={tokenizer_available}" - ) - if not tokenizer_available: - logger.warning( - "Default sampling params contain penalties but tokenizer is not available, " - "resetting penalties to avoid AssertionError" - ) - default_sampling_params["repetition_penalty"] = 1.0 - default_sampling_params["presence_penalty"] = 0.0 - default_sampling_params["frequency_penalty"] = 0.0 - except Exception as e: - logger.warning(f"Could not get default sampling params: {e}") - - if self.role == "prefill": - self._handler = PrefillWorkerHandler( - engine=self._engine, - default_sampling_params=default_sampling_params, - model_max_len=model_max_len, - enable_multimodal=self.enable_multimodal, - use_vllm_tokenizer=self.use_vllm_tokenizer, - on_engine_dead=self._on_engine_dead, - ) - else: - # Both aggregated and decode roles use DecodeWorkerHandler - self._handler = DecodeWorkerHandler( - engine=self._engine, - default_sampling_params=default_sampling_params, - model_max_len=model_max_len, - enable_multimodal=self.enable_multimodal, - use_vllm_tokenizer=self.use_vllm_tokenizer, - on_engine_dead=self._on_engine_dead, - ) - - # Start engine health monitoring (referencing Dynamo engine_monitor.py) - self._handler.engine_monitor.start_monitoring( - on_engine_dead=self._on_engine_dead - ) - logger.info(f"Engine health monitoring started for {self.worker_id}") - - self._is_ready = True - - # Log DP rank conditional registration status (referencing Dynamo main.py) - if self.data_parallel_size > 1: - if self._is_primary_rank: - logger.info( - f"vLLM Worker {self.worker_id} ready (primary rank, will register model)" - ) - else: - logger.info( - f"vLLM Worker {self.worker_id} ready (rank {self.data_parallel_rank}, " - f"will NOT register model - only primary rank registers)" - ) - else: - logger.info(f"vLLM Worker {self.worker_id} ready") - - def _on_engine_dead(self) -> None: - """Engine dead callback function (referencing Dynamo handlers.py) - - Called when vLLM engine detects EngineDeadError. - This usually means the engine has crashed and needs cleanup and possibly restart. - """ - logger.error(f"Engine dead callback triggered for {self.worker_id}") - self._engine_is_dead = True - self._is_ready = False - - # Note: In Actor mode, we don't directly call os._exit(1) - # Instead, set state and let upper-level Actor system handle it - # If forced exit is needed, add logic here - - @property - def engine_is_dead(self) -> bool: - """Return whether the engine is dead""" - return self._engine_is_dead - - def on_stop(self) -> None: - # Stop engine health monitoring - if self._handler and hasattr(self._handler, "engine_monitor"): - self._handler.engine_monitor.stop_monitoring() - - # Cancel initialization task - if ( - hasattr(self, "_init_task") - and self._init_task - and not self._init_task.done() - ): - self._init_task.cancel() - - # Clean up handler resources - if self._handler: - self._handler.cleanup() - - self._engine = None - self._handler = None - self._is_ready = False - - @property - def is_primary_rank(self) -> bool: - """Check if this is the primary rank (for model registration) - - In DP deployment, only rank 0 needs to register model to service discovery. - """ - return self._is_primary_rank - - def metadata(self) -> dict[str, str]: - meta = { - "type": "vllm_worker", - "role": self.role, - "model": self.model, - "worker_id": self.worker_id, - "ready": str(self._is_ready), - "multimodal_enabled": str(self.enable_multimodal), - "text_mode": str(self.use_vllm_tokenizer), - # Distributed configuration - "tp_size": str(self.tensor_parallel_size), - "pp_size": str(self.pipeline_parallel_size), - "dp_size": str(self.data_parallel_size), - "dp_rank": str(self.data_parallel_rank), - "ep_enabled": str(self.enable_expert_parallel), - "is_primary_rank": str(self._is_primary_rank), - # Health status - "engine_healthy": str(not self._engine_is_dead), - } - - if self._is_ready and self._engine: - # Try to get vLLM engine runtime statistics - try: - config = self._engine.vllm_config - meta.update( - { - "total_kv_blocks": str(config.cache_config.num_gpu_blocks), - "max_num_seqs": str(config.scheduler_config.max_num_seqs), - "max_num_batched_tokens": str( - config.scheduler_config.max_num_batched_tokens - ), - "block_size": str(config.cache_config.block_size), - } - ) - # Get actual parallel configuration from vllm_config - parallel_config = getattr(config, "parallel_config", None) - if parallel_config: - meta["actual_tp_size"] = str( - getattr(parallel_config, "tensor_parallel_size", 1) - ) - meta["actual_pp_size"] = str( - getattr(parallel_config, "pipeline_parallel_size", 1) - ) - meta["actual_dp_size"] = str( - getattr(parallel_config, "data_parallel_size", 1) - ) - except Exception: - pass - - return meta - - async def _ensure_ready(self) -> None: - """等待 engine 就绪,超时则抛出异常。""" - if not VLLM_AVAILABLE: - raise RuntimeError("vLLM not installed or version incompatible") - max_wait = 60.0 - wait_interval = 0.5 - waited = 0.0 - while not self._is_ready and waited < max_wait: - await asyncio.sleep(wait_interval) - waited += wait_interval - if not self._is_ready: - raise RuntimeError(f"vLLM engine initialization timeout after {max_wait}s") - - def _build_request( - self, prompt: str = "", max_new_tokens: int | None = None, **kwargs - ) -> dict: - data = kwargs.copy() - data.setdefault("prompt", prompt) - data.setdefault("max_new_tokens", max_new_tokens or self.default_max_new_tokens) - return data - - async def _collect_generate_result(self, data: dict) -> dict: - """从 handler.generate 的迭代结果聚合成单次响应 dict。""" - accumulated_text = "" - finish_reason = None - result_count = 0 - async for result in self._handler.generate(data): - result_count += 1 - if "choices" in result and len(result["choices"]) > 0: - choice = result["choices"][0] - if "delta" in choice and "content" in choice["delta"]: - accumulated_text += choice["delta"]["content"] - elif "message" in choice and "content" in choice["message"]: - accumulated_text = choice["message"]["content"] - elif "text" in choice: - accumulated_text = choice["text"] - if "finish_reason" in choice and choice["finish_reason"]: - finish_reason = choice["finish_reason"] - if accumulated_text or result_count > 0: - return { - "text": accumulated_text, - "finish_reason": finish_reason or "stop", - "completion_tokens": ( - len(accumulated_text.split()) if accumulated_text else 0 - ), - "prompt_tokens": 0, - } - return {"error": "No output"} - - # ------------------------------------------------------------------------- - # 对外方法(替代原 receive 的消息类型分支) - # ------------------------------------------------------------------------- - - async def generate( - self, - prompt: str = "", - max_new_tokens: int | None = None, - **kwargs, - ) -> dict: - """同步生成,返回 {text, finish_reason, prompt_tokens, completion_tokens} 或 {error}。""" - await self._ensure_ready() - try: - data = self._build_request( - prompt=prompt, max_new_tokens=max_new_tokens, **kwargs - ) - return await self._collect_generate_result(data) - except Exception as e: - logger.exception("Error in generate: %s", e) - return {"error": str(e)} - - async def generate_stream( - self, - prompt: str = "", - max_new_tokens: int | None = None, - **kwargs, - ): - """流式生成,async generator 逐条 yield chunk。""" - await self._ensure_ready() - stream_msg, writer = StreamMessage.create("GenerateStream") - data = self._build_request( - prompt=prompt, max_new_tokens=max_new_tokens, **kwargs - ) - - async def produce(): - try: - async for chunk in self._handler.generate(data): - await writer.write(chunk) - if chunk.get("finish_reason"): - break - except Exception as e: - logger.exception("Error in stream generation: %s", e) - await writer.error(str(e)) - finally: - writer.close() - - asyncio.create_task(produce()) - async for chunk in stream_msg.stream_reader(): - yield chunk - - def health_check(self) -> dict: - """健康检查,含 engine 状态。""" - if not self._is_ready or not self._handler: - return { - "role": self.role, - "worker_id": self.worker_id, - "ready": False, - "error": "Engine not ready", - } - status = self._handler.engine_monitor.get_health_status() - status["role"] = self.role - status["worker_id"] = self.worker_id - return status - - async def clear_kv_cache(self) -> dict: - """清理 KV Cache。""" - await self._ensure_ready() - result = await self._handler.clear_kv_cache() - return result if isinstance(result, dict) else {"ok": True} - - async def load_lora(self, lora_name: str, lora_path: str) -> dict: - """加载 LoRA。""" - await self._ensure_ready() - if not lora_name or not lora_path: - return {"error": "Missing required fields: lora_name and lora_path"} - result = await self._handler.load_lora(lora_name, lora_path) - return result if isinstance(result, dict) else {"ok": True} - - async def unload_lora(self, lora_name: str) -> dict: - """卸载 LoRA。""" - await self._ensure_ready() - if not lora_name: - return {"error": "Missing required field: lora_name"} - result = await self._handler.unload_lora(lora_name) - return result if isinstance(result, dict) else {"ok": True} - - async def list_loras(self) -> Any: - """列出已加载的 LoRA。""" - await self._ensure_ready() - return await self._handler.list_loras() diff --git a/python/pulsing/serving/vllm_worker.py b/python/pulsing/serving/vllm_worker.py deleted file mode 100644 index 899a17b66..000000000 --- a/python/pulsing/serving/vllm_worker.py +++ /dev/null @@ -1,417 +0,0 @@ -"""vLLM Worker - High-Performance Inference Worker Based on vLLM V1 Engine (pulsing.remote) - -Referencing Dynamo implementation, supports: -1. Prefill/Decode separation (PD Disaggregation) -2. Multimodal input processing (images) -3. KV Cache management and cleanup -4. LoRA dynamic loading/unloading -5. OpenAI-compatible text input/output mode -6. Engine monitoring and health checks -""" - -import asyncio -import logging -import os -import uuid -from typing import Any - -from pulsing.core import ActorId, StreamMessage, remote - -from .vllm_handlers import BaseWorkerHandler, DecodeWorkerHandler, PrefillWorkerHandler -from .vllm_utils import _is_macos, _setup_macos_metal_env - -try: - from vllm.engine.arg_utils import AsyncEngineArgs - from vllm.usage.usage_lib import UsageContext - from vllm.v1.engine.async_llm import AsyncLLM - - VLLM_AVAILABLE = True -except ImportError: - VLLM_AVAILABLE = False - -logger = logging.getLogger(__name__) - - -@remote -class VllmWorker: - """vLLM Inference Worker,通过 pulsing.remote 暴露方法。 - - 支持 vLLM V1 engine,功能对齐 Dynamo: - 1. PD 分离(Prefill / Decode 角色) - 2. 多模态输入(Image) - 3. KV Cache 管理与清理 - 4. LoRA 动态加载/卸载 - 5. OpenAI 兼容文本输入/输出 - """ - - def __init__( - self, - model: str, - role: str = "aggregated", # Options: aggregated, prefill, decode - engine_args: dict[str, Any] | None = None, - gpu_memory_utilization: float = 0.9, - trust_remote_code: bool = True, - max_new_tokens: int = 512, - enable_multimodal: bool = False, - use_vllm_tokenizer: bool = False, - # macOS Metal/MLX support parameters - mlx_device: ( - str | None - ) = None, # 'gpu' or 'cpu', default read from environment variable - metal_memory_fraction: float | None = None, # 0.0-1.0, default 0.8 - **kwargs, - ): - self.model = model - self.role = role.lower() - self.default_max_new_tokens = max_new_tokens - self.enable_multimodal = enable_multimodal - self.use_vllm_tokenizer = use_vllm_tokenizer - - # Set Metal/MLX environment variables on macOS - _setup_macos_metal_env(mlx_device, metal_memory_fraction) - - self.engine_args_dict = engine_args or {} - self.engine_args_dict.update( - { - "model": model, - "gpu_memory_utilization": gpu_memory_utilization, - "trust_remote_code": trust_remote_code, - # Critical fix: use vllm's generation config instead of loading from HuggingFace - # This avoids AssertionError caused by default repetition_penalty=1.1 - # Reference warning: Default sampling parameters have been overridden by the model's Hugging Face generation config - "generation_config": "vllm", - } - ) - - # Cleanup kwargs for AsyncEngineArgs - kwargs.pop("max_new_tokens", None) - kwargs.pop("enable_multimodal", None) - kwargs.pop("use_vllm_tokenizer", None) - self.engine_args_dict.update(kwargs) - - self.worker_id = f"vllm-{self.role}-{uuid.uuid4().hex[:8]}" - self._engine: AsyncLLM | None = None - self._handler: BaseWorkerHandler | None = None - self._is_ready = False - self._actor_id: ActorId | None = None - self._init_task: asyncio.Task | None = None - - async def on_start(self, actor_id: ActorId) -> None: - """Return quickly, initialize engine in background""" - self._actor_id = actor_id - if not VLLM_AVAILABLE: - logger.error("vLLM not installed or version incompatible.") - self._is_ready = False - return - - # Initialize engine in background task - async def init_background(): - try: - logger.info( - f"Starting vLLM engine initialization for model: {self.model}" - ) - await self._init_engine() - if self._is_ready: - logger.info( - f"vLLM engine initialized successfully for {self.worker_id}" - ) - else: - logger.error( - "vLLM engine initialization completed but engine is not ready" - ) - except Exception as e: - logger.exception(f"Failed to initialize vLLM engine: {e}") - self._is_ready = False - - self._init_task = asyncio.create_task(init_background()) - logger.info( - f"vLLM Worker {self.worker_id} started, engine initializing in background..." - ) - - async def _init_engine(self): - if self._is_ready: - return - - logger.info(f"Initializing vLLM ({self.role}) for model: {self.model}") - - # Detect platform and log information - if _is_macos(): - mlx_device = os.environ.get("VLLM_MLX_DEVICE", "not set") - metal_memory = os.environ.get("VLLM_METAL_MEMORY_FRACTION", "not set") - logger.info( - f"Running on macOS with Metal support: " - f"VLLM_MLX_DEVICE={mlx_device}, " - f"VLLM_METAL_MEMORY_FRACTION={metal_memory}" - ) - - os.environ["VLLM_NO_USAGE_STATS"] = "1" - os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" - - # Move entire initialization process to thread pool - def init_sync(): - """Synchronous initialization function, executed in thread pool""" - args = AsyncEngineArgs(**self.engine_args_dict) - usage_context = UsageContext.OPENAI_API_SERVER - engine_config = args.create_engine_config(usage_context=usage_context) - - return AsyncLLM.from_vllm_config( - vllm_config=engine_config, - usage_context=usage_context, - disable_log_requests=True, - ) - - loop = asyncio.get_event_loop() - logger.info("Starting vLLM engine initialization in thread pool...") - self._engine = await loop.run_in_executor(None, init_sync) - - # Create corresponding handler - model_max_len = getattr( - getattr(self._engine.vllm_config, "model_config", None), - "max_model_len", - None, - ) - - # Get default sampling parameters - default_sampling_params = {} - try: - default_sampling_params = ( - AsyncEngineArgs(**self.engine_args_dict) - .create_model_config() - .get_diff_sampling_param() - ) - logger.debug(f"Default sampling params: {default_sampling_params}") - - # If using text mode but penalties detected, ensure tokenizer is available - # Otherwise clear these penalties to avoid AssertionError - if self.use_vllm_tokenizer: - has_penalties = ( - default_sampling_params.get("repetition_penalty", 1.0) != 1.0 - or default_sampling_params.get("presence_penalty", 0.0) != 0.0 - or default_sampling_params.get("frequency_penalty", 0.0) != 0.0 - ) - if has_penalties: - tokenizer_available = ( - hasattr(self._engine, "tokenizer") - and self._engine.tokenizer is not None - ) - logger.info( - f"Default params have penalties, tokenizer_available={tokenizer_available}" - ) - if not tokenizer_available: - logger.warning( - "Default sampling params contain penalties but tokenizer is not available, " - "resetting penalties to avoid AssertionError" - ) - default_sampling_params["repetition_penalty"] = 1.0 - default_sampling_params["presence_penalty"] = 0.0 - default_sampling_params["frequency_penalty"] = 0.0 - except Exception as e: - logger.warning(f"Could not get default sampling params: {e}") - - if self.role == "prefill": - self._handler = PrefillWorkerHandler( - engine=self._engine, - default_sampling_params=default_sampling_params, - model_max_len=model_max_len, - enable_multimodal=self.enable_multimodal, - use_vllm_tokenizer=self.use_vllm_tokenizer, - ) - else: - # Both aggregated and decode roles use DecodeWorkerHandler - self._handler = DecodeWorkerHandler( - engine=self._engine, - default_sampling_params=default_sampling_params, - model_max_len=model_max_len, - enable_multimodal=self.enable_multimodal, - use_vllm_tokenizer=self.use_vllm_tokenizer, - ) - - self._is_ready = True - logger.info(f"vLLM Worker {self.worker_id} ready") - - def on_stop(self) -> None: - # Cancel initialization task - if ( - hasattr(self, "_init_task") - and self._init_task - and not self._init_task.done() - ): - self._init_task.cancel() - - # Clean up handler resources - if self._handler: - self._handler.cleanup() - - self._engine = None - self._handler = None - self._is_ready = False - - def metadata(self) -> dict[str, str]: - meta = { - "type": "vllm_worker", - "role": self.role, - "model": self.model, - "worker_id": self.worker_id, - "ready": str(self._is_ready), - "multimodal_enabled": str(self.enable_multimodal), - "text_mode": str(self.use_vllm_tokenizer), - } - - if self._is_ready and self._engine: - # Try to get vLLM engine runtime statistics - try: - config = self._engine.vllm_config - meta.update( - { - "total_kv_blocks": str(config.cache_config.num_gpu_blocks), - "max_num_seqs": str(config.scheduler_config.max_num_seqs), - "max_num_batched_tokens": str( - config.scheduler_config.max_num_batched_tokens - ), - "block_size": str(config.cache_config.block_size), - } - ) - except Exception: - pass - - return meta - - async def _ensure_ready(self) -> None: - """等待 engine 就绪,超时则抛出异常。""" - if not VLLM_AVAILABLE: - raise RuntimeError("vLLM not installed or version incompatible") - max_wait = 60.0 - wait_interval = 0.5 - waited = 0.0 - while not self._is_ready and waited < max_wait: - await asyncio.sleep(wait_interval) - waited += wait_interval - if not self._is_ready: - raise RuntimeError(f"vLLM engine initialization timeout after {max_wait}s") - - def _build_request( - self, prompt: str = "", max_new_tokens: int | None = None, **kwargs - ) -> dict: - data = kwargs.copy() - data.setdefault("prompt", prompt) - data.setdefault("max_new_tokens", max_new_tokens or self.default_max_new_tokens) - return data - - async def _collect_generate_result(self, data: dict) -> dict: - """从 handler.generate 的迭代结果聚合成单次响应 dict。""" - accumulated_text = "" - finish_reason = None - result_count = 0 - async for result in self._handler.generate(data): - result_count += 1 - if "choices" in result and len(result["choices"]) > 0: - choice = result["choices"][0] - if "delta" in choice and "content" in choice["delta"]: - accumulated_text += choice["delta"]["content"] - elif "message" in choice and "content" in choice["message"]: - accumulated_text = choice["message"]["content"] - elif "text" in choice: - accumulated_text = choice["text"] - if "finish_reason" in choice and choice["finish_reason"]: - finish_reason = choice["finish_reason"] - if accumulated_text or result_count > 0: - return { - "text": accumulated_text, - "finish_reason": finish_reason or "stop", - "completion_tokens": ( - len(accumulated_text.split()) if accumulated_text else 0 - ), - "prompt_tokens": 0, - } - return {"error": "No output"} - - # ------------------------------------------------------------------------- - # 对外方法(替代原 receive 的消息类型分支) - # ------------------------------------------------------------------------- - - async def generate( - self, - prompt: str = "", - max_new_tokens: int | None = None, - **kwargs, - ) -> dict: - """同步生成,返回 {text, finish_reason, prompt_tokens, completion_tokens} 或 {error}。""" - await self._ensure_ready() - try: - data = self._build_request( - prompt=prompt, max_new_tokens=max_new_tokens, **kwargs - ) - return await self._collect_generate_result(data) - except Exception as e: - logger.exception("Error in generate: %s", e) - return {"error": str(e)} - - async def generate_stream( - self, - prompt: str = "", - max_new_tokens: int | None = None, - **kwargs, - ): - """流式生成,async generator 逐条 yield chunk。""" - await self._ensure_ready() - stream_msg, writer = StreamMessage.create("GenerateStream") - data = self._build_request( - prompt=prompt, max_new_tokens=max_new_tokens, **kwargs - ) - - async def produce(): - try: - async for chunk in self._handler.generate(data): - await writer.write(chunk) - if chunk.get("finish_reason"): - break - except Exception as e: - logger.exception("Error in stream generation: %s", e) - await writer.error(str(e)) - finally: - writer.close() - - asyncio.create_task(produce()) - async for chunk in stream_msg.stream_reader(): - yield chunk - - def health_check(self) -> dict: - """健康检查,含 engine 状态。""" - if not self._is_ready or not self._handler: - return { - "role": self.role, - "worker_id": self.worker_id, - "ready": False, - "error": "Engine not ready", - } - status = self._handler.engine_monitor.get_health_status() - status["role"] = self.role - status["worker_id"] = self.worker_id - return status - - async def clear_kv_cache(self) -> dict: - """清理 KV Cache。""" - await self._ensure_ready() - result = await self._handler.clear_kv_cache() - return result if isinstance(result, dict) else {"ok": True} - - async def load_lora(self, lora_name: str, lora_path: str) -> dict: - """加载 LoRA。""" - await self._ensure_ready() - if not lora_name or not lora_path: - return {"error": "Missing required fields: lora_name and lora_path"} - result = await self._handler.load_lora(lora_name, lora_path) - return result if isinstance(result, dict) else {"ok": True} - - async def unload_lora(self, lora_name: str) -> dict: - """卸载 LoRA。""" - await self._ensure_ready() - if not lora_name: - return {"error": "Missing required field: lora_name"} - result = await self._handler.unload_lora(lora_name) - return result if isinstance(result, dict) else {"ok": True} - - async def list_loras(self) -> Any: - """列出已加载的 LoRA。""" - await self._ensure_ready() - return await self._handler.list_loras() diff --git a/python/pulsing/serving/worker.py b/python/pulsing/serving/worker.py deleted file mode 100644 index b39277069..000000000 --- a/python/pulsing/serving/worker.py +++ /dev/null @@ -1,291 +0,0 @@ -"""Transformers Worker - LLM Inference Worker (pulsing.remote)""" - -import asyncio -import time -import uuid -from dataclasses import dataclass -from threading import Thread - -from pulsing.core import ActorId, StreamMessage, remote - - -@dataclass -class GenerationConfig: - """Generation configuration""" - - max_new_tokens: int = 512 - temperature: float = 1.0 - top_p: float = 1.0 - do_sample: bool = False - - -@remote -class TransformersWorker: - """Transformers LLM Inference Worker,支持同步/流式生成与负载订阅。 - - 通过 pulsing.remote 暴露方法:generate、generate_stream、subscribe_load、health_check、get_load。 - """ - - def __init__( - self, - model_name: str, - device: str = "cuda", - gen_config: GenerationConfig | None = None, - preload: bool = False, - capacity: int = 100, - ): - self.model_name = model_name - self.device = device - self.gen_config = gen_config or GenerationConfig() - self.preload = preload - self.capacity = capacity - self.worker_id = f"worker-{uuid.uuid4().hex[:8]}" - - self._actor_id: ActorId | None = None - self._node_id: str | None = None - self._model = None - self._tokenizer = None - self._is_loaded = False - - self._current_load = 0 - self._request_count = 0 - self._load_subscribers: list = [] - - async def on_start(self, actor_id: ActorId) -> None: - self._actor_id = actor_id - self._node_id = str(actor_id) - print(f"[Worker] {self.worker_id} - {self.model_name}") - if self.preload: - await self.load_model() - - def on_stop(self) -> None: - self._model = None - self._tokenizer = None - for writer in self._load_subscribers: - try: - writer.close() - except Exception: - pass - self._load_subscribers.clear() - - def metadata(self) -> dict[str, str]: - return { - "type": "worker", - "model": self.model_name, - "device": self.device, - "worker_id": self.worker_id, - "load": str(self._current_load), - "processed": str(self._request_count), - "capacity": str(self.capacity), - "is_loaded": str(self._is_loaded).lower(), - } - - @property - def current_load(self) -> int: - return self._current_load - - @property - def load_ratio(self) -> float: - return self._current_load / max(1, self.capacity) - - def _get_load_snapshot(self) -> dict: - return { - "worker_id": self.worker_id, - "node_id": self._node_id or self.worker_id, - "load": self._current_load, - "capacity": self.capacity, - "processed": self._request_count, - "timestamp": time.time(), - } - - async def _push_load_update(self): - if not self._load_subscribers: - return - snapshot = self._get_load_snapshot() - dead = [] - for writer in self._load_subscribers: - try: - await writer.write(snapshot) - except Exception: - dead.append(writer) - for w in dead: - self._load_subscribers.remove(w) - - async def load_model(self): - if self._is_loaded: - return - try: - import torch - from transformers import AutoModelForCausalLM, AutoTokenizer - except ImportError as e: - raise ImportError("Please install transformers and torch") from e - - print(f"[Worker] Loading {self.model_name}...") - self._tokenizer = AutoTokenizer.from_pretrained(self.model_name) - torch_dtype = torch.float16 if self.device in ("cuda", "mps") else torch.float32 - model_kwargs = {"device_map": "auto"} if self.device == "cuda" else {} - self._model = AutoModelForCausalLM.from_pretrained( - self.model_name, torch_dtype=torch_dtype, **model_kwargs - ) - if self.device != "cuda": - self._model.to(self.device) - self._model.eval() - self._is_loaded = True - print(f"[Worker] Model ready on {self.device}") - - # ------------------------------------------------------------------------- - # 对外方法(替代原 receive 的消息类型分支) - # ------------------------------------------------------------------------- - - async def generate( - self, - prompt: str, - max_new_tokens: int | None = None, - ) -> dict: - """同步生成,返回 {text, prompt_tokens, completion_tokens} 或 {error}。""" - if max_new_tokens is None: - max_new_tokens = self.gen_config.max_new_tokens - if not self._is_loaded: - await self.load_model() - - self._current_load += 1 - self._request_count += 1 - asyncio.create_task(self._push_load_update()) - - try: - loop = asyncio.get_running_loop() - - def _run(): - inputs = self._tokenizer(prompt, return_tensors="pt").to( - self._model.device - ) - outputs = self._model.generate( - **inputs, - max_new_tokens=max_new_tokens, - pad_token_id=self._tokenizer.eos_token_id, - do_sample=self.gen_config.do_sample, - ) - input_len = inputs["input_ids"].shape[1] - new_tokens = outputs[0][input_len:] - text = self._tokenizer.decode(new_tokens, skip_special_tokens=True) - return text, input_len, len(new_tokens) - - text, prompt_tokens, completion_tokens = await loop.run_in_executor( - None, _run - ) - return { - "text": text, - "worker_id": self.worker_id, - "prompt_tokens": prompt_tokens, - "completion_tokens": completion_tokens, - } - except Exception as e: - print(f"[Worker] Error: {e}") - return {"error": str(e)} - finally: - self._current_load -= 1 - asyncio.create_task(self._push_load_update()) - - async def generate_stream( - self, - prompt: str, - max_new_tokens: int | None = None, - ): - """流式生成,async generator 逐条 yield {text, worker_id} 或最终 {finish_reason, prompt_tokens, completion_tokens}。""" - if max_new_tokens is None: - max_new_tokens = self.gen_config.max_new_tokens - if not self._is_loaded: - await self.load_model() - - self._current_load += 1 - self._request_count += 1 - asyncio.create_task(self._push_load_update()) - - stream_msg, writer = StreamMessage.create("GenerateStream") - worker = self - - async def produce(): - try: - from transformers import TextIteratorStreamer - - inputs = worker._tokenizer(prompt, return_tensors="pt").to( - worker._model.device - ) - input_len = inputs["input_ids"].shape[1] - streamer = TextIteratorStreamer( - worker._tokenizer, skip_prompt=True, skip_special_tokens=True - ) - gen_kwargs = { - **inputs, - "max_new_tokens": max_new_tokens, - "pad_token_id": worker._tokenizer.eos_token_id, - "do_sample": worker.gen_config.do_sample, - "streamer": streamer, - } - thread = Thread(target=worker._model.generate, kwargs=gen_kwargs) - thread.start() - token_count = 0 - for text in streamer: - if text: - token_count += 1 - await writer.write( - {"text": text, "worker_id": worker.worker_id} - ) - thread.join() - await writer.write( - { - "text": "", - "finish_reason": "stop", - "prompt_tokens": input_len, - "completion_tokens": token_count, - } - ) - except Exception as e: - print(f"[Worker] produce error: {e}") - try: - await writer.error(str(e)) - except Exception: - pass - finally: - worker._current_load -= 1 - asyncio.create_task(worker._push_load_update()) - writer.close() - - asyncio.create_task(produce()) - async for chunk in stream_msg.stream_reader(): - yield chunk - - async def subscribe_load(self): - """订阅负载更新,async generator 每秒 yield 一次负载快照。""" - stream_msg, writer = StreamMessage.create("LoadStream") - self._load_subscribers.append(writer) - worker = self - - async def produce(): - try: - await writer.write(worker._get_load_snapshot()) - while True: - await asyncio.sleep(1.0) - await writer.write(worker._get_load_snapshot()) - except Exception: - pass - finally: - if writer in worker._load_subscribers: - worker._load_subscribers.remove(writer) - writer.close() - - asyncio.create_task(produce()) - async for snapshot in stream_msg.stream_reader(): - yield snapshot - - def health_check(self) -> dict: - """健康检查。""" - return { - "status": "healthy", - "worker_id": self.worker_id, - "is_loaded": self._is_loaded, - } - - def get_load(self) -> dict: - """当前负载快照。""" - return self._get_load_snapshot() diff --git a/python/pulsing/testing/forge_harness.py b/python/pulsing/testing/forge_harness.py deleted file mode 100644 index c42f12211..000000000 --- a/python/pulsing/testing/forge_harness.py +++ /dev/null @@ -1,261 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Shared Forge test harness — minimal args, smoke runners, wire assertions.""" - -from __future__ import annotations - -import json -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Callable, Protocol - -from pulsing.forge.integrated import ( - FORGE_HOST_TOOL_NAMES, - FORGE_ISOLATED_TOOL_NAMES, - FORGE_TOOL_NAMES, -) -from pulsing.forge.result import ToolResult -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.session import LocalToolSession - -# Tools implemented only on the Rust Hybrid path today (no Python handler). -RUST_ONLY_HOST_TOOLS: frozenset[str] = frozenset( - { - "list_mcp_resources", - "list_mcp_resource_templates", - "read_mcp_resource", - "request_permissions", - } -) - -LOCAL_PYTHON_TOOLS: frozenset[str] = FORGE_TOOL_NAMES - RUST_ONLY_HOST_TOOLS - - -def assert_forge_manifest() -> None: - assert len(FORGE_TOOL_NAMES) == 32 - assert FORGE_TOOL_NAMES == FORGE_ISOLATED_TOOL_NAMES | FORGE_HOST_TOOL_NAMES - assert not (FORGE_ISOLATED_TOOL_NAMES & FORGE_HOST_TOOL_NAMES) - - -# Minimal 1x1 PNG (same bytes used across Forge tests). -_MIN_PNG = bytes.fromhex( - "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489" - "0000000a49444154789c630001000005000108d4a7e00000000049454e44ae426082" -) - - -class ForgeRuntime(Protocol): - def call_tool(self, name: str, arguments: dict[str, Any]) -> ToolResult: ... - - -def seed_workspace(tmp_path: Path) -> Path: - """Create common files used by minimal tool args.""" - sample = tmp_path / "sample.txt" - sample.write_text("hello\n", encoding="utf-8") - png = tmp_path / "x.png" - png.write_bytes(_MIN_PNG) - return sample - - -def minimal_tool_args(name: str, tmp_path: Path) -> dict[str, Any]: - """Arguments that exercise each registered tool without Unknown-tool failures.""" - seed_workspace(tmp_path) - p = tmp_path / "sample.txt" - patch = "*** Begin Patch\n*** Add File: added.txt\n+added\n*** End Patch\n" - common: dict[str, dict[str, Any]] = { - "Read": {"file_path": str(p)}, - "Glob": {"pattern": "*.txt", "path": str(tmp_path)}, - "Grep": {"pattern": "hello", "path": str(tmp_path)}, - "Edit": {"file_path": str(p), "old_string": "hello", "new_string": "hi"}, - "Write": {"file_path": str(tmp_path / "out.txt"), "content": "x"}, - "Bash": {"command": "echo ok"}, - "shell_command": { - "command": "echo ok", - "workdir": str(tmp_path), - "timeout_ms": 5000, - }, - "exec_command": {"cmd": "echo ok", "yield_time_ms": 300, "tty": False}, - "write_stdin": {"session_id": 0, "chars": ""}, - "apply_patch": {"patch": patch}, - "view_image": {"path": str(tmp_path / "x.png"), "detail": "low"}, - "update_plan": {"plan": [{"step": "s", "status": "pending"}]}, - "new_context": {}, - "get_context_remaining": {}, - "request_user_input": { - "questions": [{"id": "q", "prompt": "p?", "type": "text"}] - }, - "request_permissions": {"permissions": ["network"], "reason": "test"}, - "tool_search": {"query": "read"}, - "list_available_plugins_to_install": {}, - "request_plugin_install": { - "tool_id": "test", - "tool_name": "test", - "suggest_reason": "test", - }, - "list_mcp_resources": {}, - "list_mcp_resource_templates": {"server": "demo"}, - "read_mcp_resource": {"server": "demo", "uri": "file:///dev/null"}, - "exec": {"source": "print('hi')"}, - "wait": {"cell_id": "missing", "timeout_ms": 1}, - "web.run": {"url": "https://example.com"}, - "skills.list": {}, - "skills.read": {"name": "missing"}, - "memories.list": {}, - "memories.read": {"id": "missing"}, - "memories.search": {"query": "test"}, - "memories.add_ad_hoc_note": {"content": "note"}, - "web_search": {"query": "test"}, - } - return common.get(name, {}) - - -def assert_callable_result(name: str, out: ToolResult) -> None: - if out.content.startswith("Unknown tool:"): - raise AssertionError(f"{name}: {out.content}") - - -@dataclass(frozen=True) -class SmokeResult: - tool: str - ok: bool - detail: str = "" - - -def run_tool_smoke( - rt: ForgeRuntime, - tmp_path: Path, - *, - tools: frozenset[str] | None = None, -) -> list[SmokeResult]: - names = sorted(tools or FORGE_TOOL_NAMES) - results: list[SmokeResult] = [] - for name in names: - try: - out = rt.call_tool(name, minimal_tool_args(name, tmp_path)) - if out.content.startswith("Unknown tool:"): - results.append(SmokeResult(name, False, out.content)) - else: - results.append(SmokeResult(name, True)) - except Exception as exc: # noqa: BLE001 — aggregate smoke failures - results.append(SmokeResult(name, False, str(exc))) - return results - - -def smoke_failures(results: list[SmokeResult]) -> list[str]: - return [f"{r.tool}: {r.detail or 'failed'}" for r in results if not r.ok] - - -def local_runtime( - tmp_path: Path, - *, - session: LocalToolSession | None = None, - sandbox_policy: str = "off", - dangerously_disable_sandbox: bool = False, -) -> LocalToolRuntime: - sess = session or LocalToolSession(token_budget=128_000) - return LocalToolRuntime( - cwd=str(tmp_path), - session=sess, - sandbox_policy=sandbox_policy, - dangerously_disable_sandbox=dangerously_disable_sandbox, - ) - - -def session_from_runtime(rt: ForgeRuntime) -> LocalToolSession | None: - if hasattr(rt, "session"): - sess = rt.session # type: ignore[attr-defined] - return sess if isinstance(sess, LocalToolSession) else None - if hasattr(rt, "python_runtime"): - sess = rt.python_runtime.session # type: ignore[attr-defined] - return sess if isinstance(sess, LocalToolSession) else None - return None - - -# L2 wire checks — return None when skipped, raise AssertionError on mismatch. -WireCheck = Callable[[ForgeRuntime, Path, ToolResult], None] - -_WIRE_CHECKS: dict[str, WireCheck] = {} - - -def register_wire_check(tool: str, fn: WireCheck) -> None: - _WIRE_CHECKS[tool] = fn - - -def wire_check_tools() -> frozenset[str]: - return frozenset(_WIRE_CHECKS) - - -def wire_check_tools_local() -> frozenset[str]: - """L2 wire tools runnable on pure-Python LocalToolRuntime.""" - return wire_check_tools() - RUST_ONLY_HOST_TOOLS - - -def run_wire_check(rt: ForgeRuntime, tmp_path: Path, tool: str) -> None: - fn = _WIRE_CHECKS.get(tool) - if fn is None: - return - out = rt.call_tool(tool, minimal_tool_args(tool, tmp_path)) - assert_callable_result(tool, out) - fn(rt, tmp_path, out) - - -def _check_read(_rt: ForgeRuntime, tmp_path: Path, out: ToolResult) -> None: - assert not out.is_error - assert out.content.strip() == "hello" - - -def _check_apply_patch(_rt: ForgeRuntime, tmp_path: Path, out: ToolResult) -> None: - assert not out.is_error - assert (tmp_path / "added.txt").read_text(encoding="utf-8") == "added\n" - - -def _check_shell_command(_rt: ForgeRuntime, _tmp_path: Path, out: ToolResult) -> None: - assert not out.is_error - assert "ok" in out.content.lower() - - -def _check_update_plan(rt: ForgeRuntime, _tmp_path: Path, out: ToolResult) -> None: - assert not out.is_error - sess = session_from_runtime(rt) - if sess is not None and len(sess.plan) >= 1: - return - assert "plan" in out.content.lower() - - -def _check_get_context_remaining( - _rt: ForgeRuntime, _tmp_path: Path, out: ToolResult -) -> None: - assert not out.is_error - payload = out.structured if out.structured is not None else json.loads(out.content) - assert payload["status"] in ("ok", "unknown") - if payload["status"] == "ok": - assert isinstance(payload["tokens_remaining"], int) - assert payload["tokens_remaining"] >= 0 - else: - assert payload["tokens_remaining"] is None - - -def _check_new_context(rt: ForgeRuntime, _tmp_path: Path, out: ToolResult) -> None: - assert not out.is_error - sess = session_from_runtime(rt) - if sess is not None and sess.new_context_requested: - return - assert "context" in out.content.lower() - - -def _check_list_mcp_resources( - _rt: ForgeRuntime, _tmp_path: Path, out: ToolResult -) -> None: - assert not out.is_error - import json - - parsed = json.loads(out.content) - assert isinstance(parsed, dict) - - -register_wire_check("list_mcp_resources", _check_list_mcp_resources) -register_wire_check("Read", _check_read) -register_wire_check("apply_patch", _check_apply_patch) -register_wire_check("shell_command", _check_shell_command) -register_wire_check("update_plan", _check_update_plan) -register_wire_check("get_context_remaining", _check_get_context_remaining) -register_wire_check("new_context", _check_new_context) diff --git a/python/pulsing/tools/__init__.py b/python/pulsing/tools/__init__.py deleted file mode 100644 index f9c6e7250..000000000 --- a/python/pulsing/tools/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Deprecated: use ``pulsing.forge`` (Pulsing Forge).""" - -from __future__ import annotations - -import warnings - -warnings.warn( - "pulsing.tools is renamed to pulsing.forge; update imports to pulsing.forge", - DeprecationWarning, - stacklevel=2, -) - -from pulsing.forge import * # noqa: F403 diff --git a/python/pulsing/workspace/__init__.py b/python/pulsing/workspace/__init__.py index ddadea72b..96ea3826c 100644 --- a/python/pulsing/workspace/__init__.py +++ b/python/pulsing/workspace/__init__.py @@ -4,7 +4,6 @@ from pulsing.workspace.bootstrap import init_workspace from pulsing.workspace.journal import checkpoint, list_revisions, rollback from pulsing.workspace.layout import find_workspace_root, require_workspace_root -from pulsing.workspace.minimal_demo import run_workspace_minimal_demo __all__ = [ "checkpoint", @@ -13,5 +12,4 @@ "list_revisions", "require_workspace_root", "rollback", - "run_workspace_minimal_demo", ] diff --git a/python/pulsing/workspace/bootstrap.py b/python/pulsing/workspace/bootstrap.py index fce4b582e..268e93237 100644 --- a/python/pulsing/workspace/bootstrap.py +++ b/python/pulsing/workspace/bootstrap.py @@ -13,7 +13,7 @@ from pulsing.workspace.journal import checkpoint from pulsing.workspace.layout import WorkspaceLayout, workspace_cluster_id -Template = Literal["minimal", "agent"] +Template = Literal["minimal"] _ON_INIT_STUB = '''"""Pulsing workspace hook — called after `pulsing init`.""" @@ -60,12 +60,12 @@ def after_checkpoint(ctx: dict[str, Any]) -> None: Code-as-workflow: plain Python, no graph DSL. ```bash -pulsing run # immersive session (default: example.py) +pulsing run # run example.py once pulsing run my_workflow.py # explicit script ``` -After success you stay in the CLI (`›` prompt). Type `exit` to return to the shell. -On failure you return to the shell — then `pulsing rollback` or safe-mode fix. +Each workflow runs once and returns to the shell. +Use `pulsing rollback` to restore a checkpoint. """ _WORKFLOW_EXAMPLE = '''"""Example workflow — extension mode. @@ -100,36 +100,6 @@ def _minimal_cluster(cluster_id: str, name: str) -> dict: return { "cluster_id": cluster_id, "name": name, - "provider": "anthropic", - "model": None, - "auto_approve": False, - "sandbox": "off", - "default_agents": [], - "shared_tool_worker": False, - "puzzles": {}, - } - - -def _agent_cluster(cluster_id: str, name: str) -> dict: - return { - "cluster_id": cluster_id, - "name": name, - "provider": "anthropic", - "model": None, - "auto_approve": False, - "sandbox": "off", - "default_agents": ["guide"], - "shared_tool_worker": False, - "puzzles": { - "unit-tests": { - "title": "Unit test suite", - "kind": "test", - "path": "tests", - "blurb": "Run pytest; keep green.", - "status": "open", - "assign_to": "", - }, - }, } @@ -164,15 +134,13 @@ def _write_workflows_scaffold(layout: WorkspaceLayout) -> None: def init_workspace( root: Path | None = None, *, - template: Template = "agent", + template: Template = "minimal", name: str | None = None, force: bool = False, - seed_npcs: bool = True, - guide: str | None = None, - provider: str | None = None, - model: str | None = None, ) -> InitResult: """Create ``.pulsing/`` layout, hooks, and an initial checkpoint.""" + if template != "minimal": + raise ValueError(f"unknown template {template!r} (expected minimal)") root = (root or Path.cwd()).resolve() layout = WorkspaceLayout(root) cluster_id = workspace_cluster_id(root) @@ -196,16 +164,12 @@ def init_workspace( "cluster_id": cluster_id, "created_at": now, } - if guide: - manifest["init_guide"] = guide layout.workspace_file.write_text( json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) - cluster = _agent_cluster(cluster_id, display_name) - if template == "minimal": - cluster = _minimal_cluster(cluster_id, display_name) + cluster = _minimal_cluster(cluster_id, display_name) layout.cluster_file.write_text( json.dumps(cluster, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", @@ -215,38 +179,13 @@ def init_workspace( _write_scripts_readme(layout) _write_workflows_scaffold(layout) - if seed_npcs and template == "agent": - from pulsing.agent.npc.loader import seed_npc_defs - - seed_npc_defs(root) - checkpoint(layout, message="workspace init", author="pulsing") run_on_init( { "root": str(root), "cluster_id": cluster_id, "template": template, - "guide": guide or "", }, ) - if guide: - _run_init_guide_step(root, guide, layout, provider=provider, model=model) - return InitResult(root=root, created=True, cluster_id=cluster_id) - - -def _run_init_guide_step( - root: Path, - guide: str, - layout: WorkspaceLayout, - *, - provider: str | None, - model: str | None, -) -> None: - from pulsing.workspace.init_guide import run_init_guide_sync - - print("\n# LLM-guided bootstrap…", flush=True) - summary = run_init_guide_sync(root, guide, provider=provider, model=model) - print(f"\n{summary}\n") - checkpoint(layout, message="init guide", author="pulsing") diff --git a/python/pulsing/workspace/init_guide.py b/python/pulsing/workspace/init_guide.py deleted file mode 100644 index 79cbcbd78..000000000 --- a/python/pulsing/workspace/init_guide.py +++ /dev/null @@ -1,88 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""LLM-guided workspace bootstrap after ``pulsing init``.""" - -from __future__ import annotations - -import asyncio -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path - -from pulsing.forge.host.llm import default_model, default_provider - -INIT_TOOL_NAMES: tuple[str, ...] = ( - "update_plan", - "Glob", - "Read", - "Grep", - "Write", - "Edit", - "shell_command", -) - -INIT_SYSTEM = """You are bootstrapping a new Pulsing AI workspace. -The `.pulsing/` scaffold (cluster.json, hooks, journal) already exists. - -Customize the project to match the user's goal: -1. Read `.pulsing/cluster.json` — adjust default_agents and puzzles if needed -2. Create or update project files (README.md, tests/, configs) with Write/Edit -3. Use Glob/Read to inspect before changing; keep changes minimal and practical -4. Do not delete `.pulsing/history/` -5. End with a short summary of what you configured -""" - - -def _resolve_provider_model( - provider: str | None, - model: str | None, -) -> tuple[str, str]: - p = (provider or default_provider()).strip().lower() - m = model or default_model(p) - return p, m - - -async def run_init_guide( - root: Path, - guide: str, - *, - provider: str | None = None, - model: str | None = None, -) -> str: - from pulsing.forge.host import ForgeAgent - - p, m = _resolve_provider_model(provider, model) - agent = ForgeAgent( - cwd=root, - provider=p, - model=m, - tool_names=INIT_TOOL_NAMES, - system_prompt=INIT_SYSTEM, - auto_approve=True, - ) - try: - prompt = ( - f"Workspace bootstrap goal:\n\n{guide}\n\n" - "Start by reading `.pulsing/cluster.json` and the project root, " - "then apply changes." - ) - return await agent.run(prompt) - finally: - agent.close() - - -def run_init_guide_sync( - root: Path, - guide: str, - *, - provider: str | None = None, - model: str | None = None, -) -> str: - try: - asyncio.get_running_loop() - except RuntimeError: - return asyncio.run(run_init_guide(root, guide, provider=provider, model=model)) - - with ThreadPoolExecutor(max_workers=1) as pool: - return pool.submit( - asyncio.run, - run_init_guide(root, guide, provider=provider, model=model), - ).result() diff --git a/python/pulsing/workspace/minimal_demo.py b/python/pulsing/workspace/minimal_demo.py deleted file mode 100644 index 27c295efb..000000000 --- a/python/pulsing/workspace/minimal_demo.py +++ /dev/null @@ -1,78 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Minimal workspace demo: init → wake → say in one process.""" - -from __future__ import annotations - -import asyncio -import os -from pathlib import Path -from typing import Any, Literal - -import pulsing as pul - -from pulsing.agent.cluster.resolve import resolve_agent -from pulsing.agent.workspace.config import load_config, save_config, write_node_record -from pulsing.agent.workspace.session import workspace_session -from pulsing.agent.workspace.world_view import player_name -from pulsing.cli.agent.helpers import spawn_npc -from pulsing.forge.host.llm import llm_runtime_options -from pulsing.workspace.bootstrap import init_workspace - -Template = Literal["agent", "minimal"] - - -async def run_workspace_minimal_demo( - root: Path, - *, - message: str = "list project files with Glob", - provider: str = "demo", - model: str | None = None, - template: Template = "agent", -) -> dict[str, Any]: - """Bootstrap workspace, spawn guide, deliver one message, return agent output.""" - root = root.resolve() - root.mkdir(parents=True, exist_ok=True) - - init_workspace(root, template=template, seed_npcs=(template == "agent")) - cfg = load_config(root) - cfg.provider = provider - cfg.model = model or ("demo" if provider == "demo" else cfg.model) - cfg.auto_approve = True - save_config(cfg) - - llm = llm_runtime_options( - provider=provider, - model=cfg.model, - auto_approve=True, - sandbox=cfg.sandbox, - ) - - async with workspace_session(cfg, bind_addr="127.0.0.1:0") as system: - write_node_record(cfg, addr=str(system.addr), pid=os.getpid()) - await spawn_npc(cfg, "guide", llm, role="guide") - proxy = await _wait_for_agent(cfg, "guide") - out = await proxy.deliver_message( - from_sender=player_name(), - message=message, - channel="say", - ) - if not isinstance(out, dict): - return {"assistant_text": str(out)} - return out - - -async def _wait_for_agent(cfg, name: str, *, timeout: float = 30.0): - deadline = asyncio.get_running_loop().time() + timeout - last_err: Exception | None = None - while asyncio.get_running_loop().time() < deadline: - try: - return await resolve_agent( - pul.get_system(), - name, - workspace_id=cfg.cluster_id, - timeout=5.0, - ) - except Exception as exc: - last_err = exc - await asyncio.sleep(0.2) - raise RuntimeError(f"agent {name!r} not ready") from last_err diff --git a/scripts/build-binary.sh b/scripts/build-binary.sh index bb7985a0d..35c523026 100755 --- a/scripts/build-binary.sh +++ b/scripts/build-binary.sh @@ -9,7 +9,6 @@ source "$ROOT/scripts/lib/platform.sh" RELEASE=0 OUT="dist/bin" PACKAGE=0 -NO_GUI=0 while [[ $# -gt 0 ]]; do case "$1" in @@ -19,7 +18,6 @@ while [[ $# -gt 0 ]]; do shift 2 ;; --package) PACKAGE=1; shift ;; - --no-gui) NO_GUI=1; shift ;; -h | --help) cat <<'EOF' Usage: scripts/build-binary.sh [OPTIONS] @@ -30,7 +28,6 @@ Options: --release Release build (default: debug) --out DIR Directory for the binary (default: dist/bin) --package Also create dist/pulsing-.tar.gz (or .zip on Windows) - --no-gui Build without egui desktop GUI (Linux CI / manylinux) EOF exit 0 ;; @@ -44,16 +41,7 @@ done TAG="$(platform_tag)" mkdir -p "$OUT" -# manylinux / headless Linux: skip egui (no X11 dev headers, smaller binary) -if [[ "$NO_GUI" -eq 0 ]] && [[ "$(uname -s)" == "Linux" ]] && [[ ! -f /usr/include/X11/Xlib.h ]]; then - NO_GUI=1 -fi - -CARGO_ARGS=(-p pulsing-cli) -if [[ "$NO_GUI" -eq 1 ]]; then - CARGO_ARGS+=(--no-default-features) - echo "==> Building pulsing-cli without desktop GUI" -fi +CARGO_ARGS=(--locked -p pulsing-cli) if [[ "$RELEASE" -eq 1 ]]; then cargo build --release "${CARGO_ARGS[@]}" diff --git a/scripts/build-release.sh b/scripts/build-release.sh index be08cb510..ba731eaed 100755 --- a/scripts/build-release.sh +++ b/scripts/build-release.sh @@ -70,7 +70,6 @@ if [[ "$BINARY" -eq 1 ]]; then BIN_ARGS=() [[ "$RELEASE" -eq 1 ]] && BIN_ARGS+=(--release) [[ "$PACKAGE_BIN" -eq 1 ]] && BIN_ARGS+=(--package) - [[ "$MANYLINUX" -eq 1 ]] && BIN_ARGS+=(--no-gui) "$ROOT/scripts/build-binary.sh" "${BIN_ARGS[@]}" fi diff --git a/scripts/build-wheel.sh b/scripts/build-wheel.sh index c4b234337..e6fe62fe2 100755 --- a/scripts/build-wheel.sh +++ b/scripts/build-wheel.sh @@ -43,15 +43,13 @@ if [[ "$MANYLINUX" -eq 1 ]]; then fi if [[ "$RELEASE" -eq 1 ]]; then - MATURIN_ARGS=(build --release --out "$OUT") + MATURIN_ARGS=(build --locked --release --out "$OUT") if [[ "$MANYLINUX" -eq 1 ]]; then MATURIN_ARGS+=(--compatibility manylinux_2_17 -i python3.10) fi maturin "${MATURIN_ARGS[@]}" - maturin build --release --out "$OUT" --manifest-path crates/pulsing-bench-py/Cargo.toml else - maturin develop - maturin develop --manifest-path crates/pulsing-bench-py/Cargo.toml + maturin develop --locked fi echo "==> Wheel path: ${OUT}/*.whl (extension-module)" diff --git a/scripts/sync-codex-forge.sh b/scripts/sync-codex-forge.sh deleted file mode 100755 index 87321409d..000000000 --- a/scripts/sync-codex-forge.sh +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env bash -# Sync Codex tool-related crates into vendor/codex-rs for pulsing-forge development. -# Source: https://github.com/openai/codex (Apache-2.0) -# -# Usage: -# CODEX_ROOT=/path/to/codex/codex-rs ./scripts/sync-codex-forge.sh -# -# After sync, update docs/design/pulsing-forge.md "Synced from Codex" table. - -set -euo pipefail - -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -CODEX_ROOT="${CODEX_ROOT:-$(dirname "$ROOT")/codex/codex-rs}" -DEST="$ROOT/vendor/codex-rs" - -if [[ ! -d "$CODEX_ROOT" ]]; then - echo "error: Codex tree not found at $CODEX_ROOT" >&2 - echo " clone codex or set CODEX_ROOT" >&2 - exit 1 -fi - -CRATES=( - tools - sandboxing - execpolicy - apply-patch - file-system - shell-command - protocol - utils/absolute-path - utils/output-truncation - utils/path-uri - utils/string - network-proxy - bwrap - linux-sandbox -) - -mkdir -p "$DEST" -COMMIT="$(git -C "$(dirname "$CODEX_ROOT")" rev-parse --short HEAD 2>/dev/null || echo unknown)" -echo "Syncing from codex @ $COMMIT" - -for rel in "${CRATES[@]}"; do - src="$CODEX_ROOT/$rel" - if [[ ! -d "$src" ]]; then - echo "skip missing: $rel" >&2 - continue - fi - name="${rel//\//-}" - mkdir -p "$DEST/$name" - rsync -a --delete \ - --exclude 'target' \ - --exclude 'Cargo.lock' \ - "$src/" "$DEST/$name/" - echo " synced $rel -> vendor/codex-rs/$name" -done - -cat > "$DEST/SYNC_INFO" < $DEST (see SYNC_INFO)" diff --git a/tests/fixtures/forge_traces/read_sample.jsonl b/tests/fixtures/forge_traces/read_sample.jsonl deleted file mode 100644 index 2c10f6dfd..000000000 --- a/tests/fixtures/forge_traces/read_sample.jsonl +++ /dev/null @@ -1 +0,0 @@ -{"seq": 1, "kind": "tool_call", "tool": "Read", "arguments": {"file_path": "sample.txt"}, "result": {"content": "forge-repl-fixture", "is_error": false}} diff --git a/tests/python/agent/test_agent.py b/tests/python/agent/test_agent.py deleted file mode 100644 index a6cb3a095..000000000 --- a/tests/python/agent/test_agent.py +++ /dev/null @@ -1,122 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace Agent: spawn, RPC.""" - -from __future__ import annotations - -import inspect -import uuid -from pathlib import Path - -import pytest - -from pulsing.agent.cluster.constants import full_agent_name -from pulsing.agent.npc.config import NpcConfig - - -def _spawn_config( - *, - cwd: str, - ws: str, - name: str, - public: bool = True, -) -> tuple[NpcConfig, str]: - config = NpcConfig( - model="claude-sonnet-4-20250514", - cwd=cwd, - agent_name=name, - workspace_id=ws, - auto_approve=True, - ) - return config, full_agent_name( - name, workspace_id=ws - ) if public else f"craft_agent_{uuid.uuid4().hex[:12]}" - - -def test_imports_without_anthropic_at_module_level() -> None: - from pulsing.agent.actors import Agent - - assert Agent is not None - - -def test_chat_stream_is_async_generator() -> None: - from pulsing.agent.actors import Agent - - assert inspect.isasyncgenfunction(Agent._cls.chat_stream) - - -@pytest.mark.asyncio -async def test_spawn_and_get_session_id() -> None: - import pulsing as pul - from pulsing.agent.actors import Agent - - await pul.init() - try: - config, name = _spawn_config(cwd=".", ws="local", name="a", public=False) - agent = await Agent.spawn(config=config, name=name, public=False) - sid = await agent.get_session_id() - assert len(sid) >= 8 - finally: - await pul.shutdown() - - -@pytest.mark.asyncio -async def test_deliver_message_rejects_empty( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - import asyncio - - import pulsing as pul - from pulsing.agent.actors import Agent - from pulsing.agent.workspace.config import default_config, save_config - - monkeypatch.chdir(tmp_path) - cfg = default_config(tmp_path) - save_config(cfg) - ws = cfg.cluster_id - - await pul.init() - try: - name = f"rx-{uuid.uuid4().hex[:8]}" - config, full = _spawn_config(cwd=str(tmp_path), ws=ws, name=name) - agent = await Agent.spawn(config=config, name=full, public=True) - await asyncio.sleep(0.3) - out = await agent.deliver_message(from_sender="peer", message="") - assert out.get("ok") is False - finally: - await pul.shutdown() - - -@pytest.mark.asyncio -async def test_deliver_message_wait_false_accepted( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - import asyncio - - import pulsing as pul - from pulsing.agent.actors import Agent - from pulsing.agent.workspace.config import default_config, save_config - - monkeypatch.chdir(tmp_path) - cfg = default_config(tmp_path) - save_config(cfg) - ws = cfg.cluster_id - - await pul.init() - try: - name = f"wf-{uuid.uuid4().hex[:8]}" - config, full = _spawn_config(cwd=str(tmp_path), ws=ws, name=name) - agent = await Agent.spawn(config=config, name=full, public=True) - await asyncio.sleep(0.3) - out = await agent.deliver_message( - from_sender="peer", - message="hi", - channel="whisper", - wait=False, - ) - assert out.get("ok") is True - assert out.get("accepted") is True - assert out.get("channel") == "whisper" - finally: - await pul.shutdown() diff --git a/tests/python/agent/test_agent_log.py b/tests/python/agent/test_agent_log.py deleted file mode 100644 index cedb8cc9c..000000000 --- a/tests/python/agent/test_agent_log.py +++ /dev/null @@ -1,24 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Per-agent log ring buffer.""" - -from __future__ import annotations - -from pulsing.agent.actors.log import append_log, get_logs, init_log - - -class _Fake: - pass - - -def test_log_ring_buffer_and_since() -> None: - agent = _Fake() - init_log(agent) - append_log(agent, "hello") - append_log(agent, "world") - chunk = get_logs(agent, since=0) - assert chunk["next"] == 2 - assert len(chunk["lines"]) == 2 - assert "hello" in chunk["lines"][0] - tail = get_logs(agent, since=1) - assert len(tail["lines"]) == 1 - assert "world" in tail["lines"][0] diff --git a/tests/python/agent/test_agent_runtime_lifecycle.py b/tests/python/agent/test_agent_runtime_lifecycle.py index 22dfd6939..da3e11fdc 100644 --- a/tests/python/agent/test_agent_runtime_lifecycle.py +++ b/tests/python/agent/test_agent_runtime_lifecycle.py @@ -2,7 +2,7 @@ Focus areas: 1. Runtime context manager repeatedly entering/exiting -2. Global state cleanup (agent registry, llm, actor system) +2. Global state cleanup (agent registry, actor system) 3. Resource leaks (actor, network connections) 4. Concurrent scenarios """ @@ -20,8 +20,6 @@ clear_agent_registry, get_agent_meta, list_agents, - llm, - reset_llm, runtime, ) @@ -121,37 +119,6 @@ async def test_agent_registry_manual_cleanup_pattern(self): clear_agent_registry() assert len(list_agents()) == 0 - @pytest.mark.asyncio - async def test_llm_singleton_cleanup(self): - """Test if LLM singleton needs cleanup""" - # Skip if OPENAI_API_KEY is not configured - pytest.importorskip("langchain_openai") - - import os - - if not os.getenv("OPENAI_API_KEY"): - pytest.skip("OPENAI_API_KEY required") - - # First round - async with runtime(): - client1 = await llm() - assert client1 is not None - - # Second round - LLM singleton will be retained - async with runtime(): - client2 = await llm() - # In singleton mode, it's the same instance - assert client2 is client1 - - # Manual cleanup - reset_llm() - - # Third round - create new instance - async with runtime(): - client3 = await llm() - # After cleanup, new instance will be created - assert client3 is not client1 - @pytest.mark.asyncio async def test_multiple_actors_cleanup(self): """Test cleanup of multiple actors""" @@ -329,7 +296,6 @@ async def run_with_cleanup(): finally: # Ensure cleanup clear_agent_registry() - reset_llm() # Multiple calls for i in range(5): @@ -373,9 +339,6 @@ async def test_multiple_cleanup_calls(self): clear_agent_registry() clear_agent_registry() - reset_llm() - reset_llm() - assert len(list_agents()) == 0 @pytest.mark.asyncio diff --git a/tests/python/agent/test_cli.py b/tests/python/agent/test_cli.py deleted file mode 100644 index c167cd65e..000000000 --- a/tests/python/agent/test_cli.py +++ /dev/null @@ -1,51 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""``pulsing agent`` CLI parser and world commands.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.cli.agent.commands.world import run_init, run_look -from pulsing.cli.agent.main import DEFAULT_PROG, _parse as parse - - -def test_parse_world_commands() -> None: - assert parse(["init"]).cmd == "init" - assert parse(["look"]).cmd == "look" - assert parse(["demo"]).cmd == "demo" - assert parse(["watch"]).cmd == "watch" - assert parse(["dashboard"]).cmd == "dashboard" - assert parse([]).cmd == "look" - - -def test_parse_agent_and_task() -> None: - assert parse(["list"]).cmd == "list" - assert parse(["say", "guide", "hi"]).cmd == "say" - assert parse(["task", "list"]).task_cmd == "list" - assert parse(["task", "show", "unit-tests"]).id == "unit-tests" - - -def test_parse_group_requires_subcommand() -> None: - with pytest.raises(SystemExit): - parse(["task"]) - - -def test_parse_sleep_and_mark() -> None: - assert parse(["sleep"]).cmd == "sleep" - args = parse(["task", "mark", "unit-tests", "--status", "open"]) - assert args.task_cmd == "mark" - assert args.assign_to is None - - -@pytest.mark.asyncio -async def test_init_and_look(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.chdir(tmp_path) - args = parse(["init"], prog=DEFAULT_PROG) - assert args.cmd == "init" - await run_init(args) - assert (tmp_path / ".pulsing" / "cluster.json").is_file() - assert (tmp_path / ".pulsing" / "npcs" / "artisan.json").is_file() - await run_look(parse(["look"])) - await run_init(parse(["init"])) diff --git a/tests/python/agent/test_cluster.py b/tests/python/agent/test_cluster.py deleted file mode 100644 index 223e3cee1..000000000 --- a/tests/python/agent/test_cluster.py +++ /dev/null @@ -1,136 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Cluster naming and gossip discovery.""" - -from __future__ import annotations - -import uuid -from pathlib import Path - -import pytest - -from pulsing.agent.cluster.constants import full_agent_name, short_agent_name -from pulsing.agent.cluster.discovery import format_agent_table, list_cluster_agents -from pulsing.agent.npc.config import NpcConfig -from pulsing.agent.workspace.config import default_config, save_config - - -def test_agent_name_roundtrip() -> None: - ws = "abc123" - assert full_agent_name("coder", workspace_id=ws) == "craft/ws/abc123/coder" - assert short_agent_name("craft/ws/abc123/coder", workspace_id=ws) == "coder" - assert short_agent_name("coder") == "coder" - - -def test_format_agent_table_empty() -> None: - assert "no cluster agents" in format_agent_table([]).lower() - - -@pytest.mark.asyncio -async def test_cluster_info_and_ping( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - import pulsing as pul - from pulsing.agent.actors import Agent - - monkeypatch.chdir(tmp_path) - cfg = default_config(tmp_path) - save_config(cfg) - ws = cfg.cluster_id - - await pul.init() - try: - name = f"t-{uuid.uuid4().hex[:8]}" - config = NpcConfig( - model="claude-sonnet-4-20250514", - cwd=str(tmp_path), - agent_name=name, - workspace_id=ws, - auto_approve=True, - agent_role="tester", - agent_description="smoke", - ) - agent = await Agent.spawn( - config=config, - name=full_agent_name(name, workspace_id=ws), - public=True, - ) - info = await agent.get_cluster_info() - assert info["name"] == name - assert info["role"] == "tester" - assert info["cluster_enabled"] is True - ping = await agent.ping() - assert ping["ok"] is True - assert ping["name"] == name - finally: - await pul.shutdown() - - -@pytest.mark.asyncio -async def test_get_activity_idle(tmp_path: Path) -> None: - import asyncio - - import pulsing as pul - from pulsing.agent.actors import Agent - from pulsing.agent.workspace.config import default_config, save_config - - cfg = default_config(tmp_path) - save_config(cfg) - ws = cfg.cluster_id - name = f"act-{__import__('uuid').uuid4().hex[:6]}" - - await pul.init() - try: - from pulsing.agent.npc.config import NpcConfig - - config = NpcConfig( - model="claude-sonnet-4-20250514", - cwd=str(tmp_path), - agent_name=name, - workspace_id=ws, - auto_approve=True, - ) - agent = await Agent.spawn( - config=config, - name=f"craft/ws/{ws}/{name}", - public=True, - ) - await asyncio.sleep(0.3) - act = await agent.get_activity() - assert act.get("state") == "idle" - assert act.get("name") == name - finally: - await pul.shutdown() - - -@pytest.mark.asyncio -async def test_list_cluster_agents_finds_spawned( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - import pulsing as pul - from pulsing.agent.actors import Agent - - monkeypatch.chdir(tmp_path) - cfg = default_config(tmp_path) - save_config(cfg) - ws = cfg.cluster_id - - await pul.init() - try: - name = f"disc-{uuid.uuid4().hex[:8]}" - config = NpcConfig( - model="claude-sonnet-4-20250514", - cwd=str(tmp_path), - agent_name=name, - workspace_id=ws, - auto_approve=True, - ) - await Agent.spawn( - config=config, - name=full_agent_name(name, workspace_id=ws), - public=True, - ) - rows = await list_cluster_agents(pul.get_system(), workspace_id=ws) - assert name in {r["name"] for r in rows} - finally: - await pul.shutdown() diff --git a/tests/python/agent/test_dashboard.py b/tests/python/agent/test_dashboard.py deleted file mode 100644 index 5c6bc0559..000000000 --- a/tests/python/agent/test_dashboard.py +++ /dev/null @@ -1,83 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Dashboard layout generation.""" - -from __future__ import annotations - -from pathlib import Path - -from pulsing.cli.agent.commands.dashboard import ( - agent_cli_argv, - find_backend, - write_zellij_layout, -) -from pulsing.agent.workspace.config import default_config - - -def test_agent_cli_argv_includes_subcommand() -> None: - argv = agent_cli_argv("watch", "-f") - assert argv[-2:] == ["-f"] or "watch" in argv - - -def test_write_zellij_layout(tmp_path: Path) -> None: - cfg = default_config(tmp_path) - cfg.default_agents = ["bard", "smith"] - path = write_zellij_layout(cfg, interval=0.8) - text = path.read_text(encoding="utf-8") - assert "layout {" in text - assert str(tmp_path.resolve()) in text - assert 'name="bard"' in text - assert 'name="smith"' in text - assert "logs bard" in text - - -def test_write_zellij_demo_layout(tmp_path: Path) -> None: - from pulsing.cli.agent.commands.dashboard import write_zellij_demo_layout - - cfg = default_config(tmp_path) - path = write_zellij_demo_layout( - cfg, - demo_shell="export PCRaft=1; pulsing-agent demo --no-dashboard", - agent_names=["bard", "smith", "sage"], - ) - text = path.read_text(encoding="utf-8") - assert 'name="demo"' in text - assert 'name="bard"' in text - assert 'name="smith"' in text - assert 'name="sage"' in text - assert "logs" in text - - -def test_zellij_session_line_parser() -> None: - from pulsing.cli.agent.commands.dashboard import _parse_zellij_session_line - - line = "\x1b[32;1mpulsing-agent-demo\x1b[m [Created 1m ago] (\x1b[31;1mEXITED\x1b[m - attach to resurrect)" - assert _parse_zellij_session_line(line, "pulsing-agent-demo") == "exited" - assert _parse_zellij_session_line(line, "other") is None - active = "pulsing-agent-demo [Created 1m ago] (ACTIVE)" - assert _parse_zellij_session_line(active, "pulsing-agent-demo") == "active" - - -def test_zellij_session_constant() -> None: - from pulsing.cli.agent.commands.dashboard import ZELLIJ_SESSION - - assert ZELLIJ_SESSION == "pulsing-agent-dashboard" - - -def test_find_backend_auto_or_skip() -> None: - import shutil - - if shutil.which("zellij"): - assert find_backend("auto") == "zellij" - elif shutil.which("tmux"): - assert find_backend("auto") == "tmux" - - -def test_demo_worker_shell() -> None: - from argparse import Namespace - - from pulsing.cli.agent.commands.demo import demo_worker_shell - from pulsing.cli.agent.commands.dashboard import DEMO_WORKER_ENV - - sh = demo_worker_shell(Namespace(interval=3.0, real_llm=False, addr="127.0.0.1:0")) - assert DEMO_WORKER_ENV in sh - assert "--no-dashboard" in sh diff --git a/tests/python/agent/test_demo.py b/tests/python/agent/test_demo.py deleted file mode 100644 index c869929da..000000000 --- a/tests/python/agent/test_demo.py +++ /dev/null @@ -1,46 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Demo LLM + demo command.""" - -from __future__ import annotations - -from pathlib import Path - -from pulsing.cli.agent.commands.demo import ( - CHATTER_SCRIPT, - DEMO_AGENTS, - prepare_demo_workspace, -) -from pulsing.agent.loop.demo_llm import plan_demo_turn - - -def test_plan_demo_glob_tool() -> None: - plan = plan_demo_turn( - [{"role": "user", "content": "List project files with Glob under ."}], - [{"name": "Glob", "input_schema": {}}], - ) - assert plan["kind"] == "tool" - assert plan["name"] == "Glob" - - -def test_plan_demo_text_fallback() -> None: - plan = plan_demo_turn( - [{"role": "user", "content": "hello world"}], - [], - ) - assert plan["kind"] == "text" - assert "hello" in plan["text"] - - -def test_prepare_demo_workspace(tmp_path: Path) -> None: - cfg = prepare_demo_workspace(tmp_path) - assert cfg.shared_tool_worker is True - assert cfg.default_agents == ["bard", "smith", "sage"] - assert cfg.puzzles["unit-tests"]["assign_to"] == "sage" - assert (tmp_path / ".pulsing" / "cluster.json").is_file() - - -def test_chatter_script_has_three_agents() -> None: - names = {a[0] for a in DEMO_AGENTS} - for a, b, _ in CHATTER_SCRIPT: - assert a in names - assert b in names diff --git a/tests/python/agent/test_follow.py b/tests/python/agent/test_follow.py deleted file mode 100644 index cee90355c..000000000 --- a/tests/python/agent/test_follow.py +++ /dev/null @@ -1,13 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Follow scroll output.""" - -from __future__ import annotations - -from pulsing.cli.agent.commands.follow import should_emit - - -def test_should_emit_delta() -> None: - assert should_emit("", "a", delta=True) is True - assert should_emit("a", "a", delta=True) is False - assert should_emit("a", "b", delta=True) is True - assert should_emit("a", "a", delta=False) is True diff --git a/tests/python/agent/test_forge_events.py b/tests/python/agent/test_forge_events.py deleted file mode 100644 index fcdadc1c6..000000000 --- a/tests/python/agent/test_forge_events.py +++ /dev/null @@ -1,87 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for Craft forge event handler.""" - -from __future__ import annotations - -import asyncio -import uuid - -import pytest - -from pulsing.agent.actors.forge_events import emit_forge_event, handle_forge_event -from pulsing.forge.events import ForgeEvent -from pulsing.forge.p2p_transport import tell_forge_event - - -class _FakeAgent: - def __init__(self) -> None: - self._forge_events: list[dict] = [] - self._forge_stream_sink = None - self._stream_chunks: list[dict] = [] - - async def _sink(self, ev: dict) -> None: - self._stream_chunks.append(ev) - - -@pytest.mark.asyncio -async def test_handle_forge_event_records_and_streams() -> None: - agent = _FakeAgent() - agent._forge_stream_sink = agent._sink - event = ForgeEvent.exec_output_delta(session_id=2, stream="pty", chunk="x") - await handle_forge_event(agent, event.to_dict()) - assert len(agent._forge_events) == 1 - assert agent._stream_chunks[0]["kind"] == "forge_exec_delta" - - -@pytest.mark.asyncio -async def test_tell_forge_event_delivers_to_named_actor() -> None: - import pulsing as pul - - @pul.remote - class _ForgeEventSink: - def __init__(self) -> None: - self._events: list[dict] = [] - - async def on_forge_event(self, event: dict) -> None: - self._events.append(dict(event)) - - def get_forge_events(self) -> list[dict]: - return list(self._events) - - name = f"forge_sink_{uuid.uuid4().hex[:10]}" - await pul.init() - try: - sink = await _ForgeEventSink.spawn(public=True, name=name) - await asyncio.sleep(0.2) - await tell_forge_event(name, ForgeEvent.tool_begin("Read", {"file_path": "x"})) - await asyncio.sleep(0.2) - events = await sink.get_forge_events() - assert len(events) == 1 - assert events[0]["kind"] == "tool_begin" - finally: - await pul.shutdown() - - -@pytest.mark.asyncio -async def test_emit_forge_event_helper_uses_tell() -> None: - agent = _FakeAgent() - agent._event_sink_name = "craft/ws/test/agent" - event = ForgeEvent.tool_begin("Test", {"x": 1}) - - called: list[tuple[str, str]] = [] - - async def _fake_tell(sink: str, ev: ForgeEvent) -> None: - called.append((sink, ev.kind)) - await handle_forge_event(agent, ev.to_dict()) - - import pulsing.agent.actors.forge_events as fe - - orig = fe.tell_forge_event - fe.tell_forge_event = _fake_tell - try: - await emit_forge_event(agent, event) - finally: - fe.tell_forge_event = orig - - assert called == [("craft/ws/test/agent", "tool_begin")] - assert len(agent._forge_events) == 1 diff --git a/tests/python/agent/test_npc.py b/tests/python/agent/test_npc.py deleted file mode 100644 index 70f170946..000000000 --- a/tests/python/agent/test_npc.py +++ /dev/null @@ -1,150 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace NPCs: NpcConfig, spawn_npc.""" - -from __future__ import annotations - -import json -import uuid -from pathlib import Path - -import pytest - -from pulsing.agent.actors.npc import format_incoming -from pulsing.agent.cluster.constants import full_agent_name, is_public_npc_name -from pulsing.agent.cluster.discovery import list_cluster_agents -from pulsing.agent.npc import spawn_npc, get_npc_class, list_npc_classes, seed_npc_defs -from pulsing.agent.npc.config import NpcConfig -from pulsing.agent.workspace.config import default_config, save_config - - -def test_format_incoming_whisper() -> None: - assert format_incoming("alice", "hi", channel="whisper") == "[alice whispers]\nhi" - assert format_incoming("bob", "hey", channel="say") == "[bob]\nhey" - - -def test_npc_config_resolved_profile(tmp_path: Path) -> None: - cfg = NpcConfig( - model="m", - cwd=str(tmp_path), - agent_name="guide", - workspace_id="ws1", - npc_class="scholar", - ) - prompt, allow, forbid, cls_name, _ = cfg.resolved_profile() - assert "guide" in prompt - assert "scholar" == cls_name - assert "Read" in allow - assert "Edit" in forbid - - -def test_npc_class_registry() -> None: - assert "artisan" in list_npc_classes() - quest = get_npc_class("quest_giver") - assert "Summon" in quest.default_tools - assert "MessageClusterAgent" in quest.default_tools - assert "QuestReport" in quest.default_tools - assert "Edit" in get_npc_class("scholar").forbidden_tools - - -def test_seed_and_load_external_npc(tmp_path: Path) -> None: - seed_npc_defs(tmp_path) - nd = tmp_path / ".pulsing" / "npcs" - assert (nd / "artisan.json").is_file() - custom = { - "name": "ranger", - "description": "scout", - "default_tools": ["Read", "Glob"], - "forbidden_tools": ["Bash"], - } - (nd / "ranger.json").write_text(json.dumps(custom), encoding="utf-8") - cls = get_npc_class("ranger", tmp_path) - assert cls.description == "scout" - assert "ranger" in list_npc_classes(tmp_path) - - -def test_is_public_npc_name_filters_internals() -> None: - assert is_public_npc_name("guide") is True - assert is_public_npc_name("_engine") is False - assert is_public_npc_name("guide/_engine") is False - assert is_public_npc_name("guide/tasks/task-1") is False - - -@pytest.mark.asyncio -async def test_spawn_ping_and_cluster_info(tmp_path: Path) -> None: - import pulsing as pul - - cfg = default_config(tmp_path) - save_config(cfg) - ws = cfg.cluster_id - name = f"npc-{uuid.uuid4().hex[:6]}" - - await pul.init() - try: - config = NpcConfig( - model="claude-sonnet-4-20250514", - cwd=str(tmp_path), - agent_name=name, - workspace_id=ws, - auto_approve=True, - agent_role="guide", - ) - npc = await spawn_npc( - config, - name=full_agent_name(name, workspace_id=ws), - public=True, - ) - ping = await npc.ping() - assert ping == {"ok": True, "kind": "npc", "name": name} - - info = await npc.get_cluster_info() - assert info["full_name"] == f"craft/ws/{ws}/{name}" - assert info["kind"] == "npc" - assert await npc.metadata() == { - "agent.kind": "workspace", - "agent.name": name, - "agent.class": "artisan", - "agent.role": "guide", - "agent.workspace_id": ws, - } - - rows = await list_cluster_agents(pul.get_system(), workspace_id=ws) - names = {r["name"] for r in rows} - assert name in names - assert not any("/" in n or n.startswith("_") for n in names) - finally: - await pul.shutdown() - - -@pytest.mark.asyncio -async def test_deliver_message_wait_false_mailbox_handoff(tmp_path: Path) -> None: - import pulsing as pul - - cfg = default_config(tmp_path) - save_config(cfg) - ws = cfg.cluster_id - name = f"q-{uuid.uuid4().hex[:6]}" - - await pul.init() - try: - config = NpcConfig( - model="claude-sonnet-4-20250514", - cwd=str(tmp_path), - agent_name=name, - workspace_id=ws, - auto_approve=True, - ) - npc = await spawn_npc( - config, - name=full_agent_name(name, workspace_id=ws), - public=True, - ) - out = await npc.deliver_message( - from_sender="player", - message="hello", - channel="say", - wait=False, - ) - assert out.get("ok") is True - assert out.get("accepted") is True - finally: - await pul.shutdown() diff --git a/tests/python/agent/test_phase1.py b/tests/python/agent/test_phase1.py deleted file mode 100644 index 407e226b5..000000000 --- a/tests/python/agent/test_phase1.py +++ /dev/null @@ -1,67 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Phase 1: workspace/cluster/npc live in pulsing.agent.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.agent import AgentConfig, find_workspace_root, list_cluster_agents -from pulsing.agent.cluster.constants import full_agent_name, workspace_agent_name -from pulsing.agent.npc import list_npc_classes, seed_npc_defs -from pulsing.agent.workspace.config import default_config, save_config - - -def test_agent_workspace_roundtrip(tmp_path: Path) -> None: - root = tmp_path / "proj" - root.mkdir() - cfg = default_config(root) - save_config(cfg) - found = find_workspace_root(root) - assert found == root.resolve() - assert cfg.cluster_id == default_config(root).cluster_id - - -def test_workspace_load_config(tmp_path: Path) -> None: - root = tmp_path / "proj" - root.mkdir() - cfg = default_config(root) - save_config(cfg) - from pulsing.agent.workspace.config import load_config - - loaded = load_config(root) - assert cfg.cluster_id == loaded.cluster_id - - -def test_agent_config_alias() -> None: - assert AgentConfig is not None - cfg = AgentConfig( - model="x", - cwd="/tmp", - agent_name="guide", - workspace_id="abc123", - ) - assert cfg.short_name == "guide" - - -def test_workspace_agent_naming() -> None: - name = workspace_agent_name("ws1", "coder") - assert name == full_agent_name("coder", workspace_id="ws1") - assert name.startswith("craft/ws/") - - -def test_npc_classes_builtin() -> None: - names = list_npc_classes() - assert "artisan" in names - - -def test_seed_npc_defs(tmp_path: Path) -> None: - seed_npc_defs(tmp_path) - assert (tmp_path / ".pulsing" / "npcs" / "artisan.json").is_file() - - -@pytest.mark.asyncio -async def test_list_cluster_agents_empty_when_no_system() -> None: - """Import path smoke; full cluster tests live in tests/python/agent/.""" - assert callable(list_cluster_agents) diff --git a/tests/python/agent/test_phase2.py b/tests/python/agent/test_phase2.py deleted file mode 100644 index b75710c12..000000000 --- a/tests/python/agent/test_phase2.py +++ /dev/null @@ -1,46 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Phase 2: actors and loop live in pulsing.agent.""" - -from __future__ import annotations - -from pulsing.agent import Agent, LlmChat -from pulsing.agent.actors import AgentActor -from pulsing.agent.actors.forge_events import emit_forge_event -from pulsing.agent.loop.permissions import PermissionChecker -from pulsing.agent.loop.split_tools import build_tools_for_agent -from pulsing.agent.loop.tool_base import ToolResult - - -def test_workspace_agent_exports() -> None: - from pulsing.agent.actors import Agent as WorkspaceAgent, NpcAgent - from pulsing.agent.host import Agent as ExportedAgent - - assert ExportedAgent is WorkspaceAgent - assert NpcAgent is WorkspaceAgent - assert issubclass(WorkspaceAgent._cls, AgentActor) - - -def test_llm_chat_import() -> None: - assert LlmChat is not None - - -def test_tool_result_type() -> None: - r = ToolResult(content="ok") - assert r.content == "ok" - - -def test_emit_forge_event_callable() -> None: - assert callable(emit_forge_event) - - -def test_build_tools_for_agent_smoke() -> None: - checker = PermissionChecker(auto_approve=True) - tools = build_tools_for_agent( - checker, - cluster_enabled=True, - summon_enabled=False, - tool_allowlist={"Read", "ListClusterAgents"}, - ) - names = {t.name for t in tools} - assert "Read" in names - assert "ListClusterAgents" in names diff --git a/tests/python/agent/test_tools.py b/tests/python/agent/test_tools.py deleted file mode 100644 index 774e6d9f6..000000000 --- a/tests/python/agent/test_tools.py +++ /dev/null @@ -1,74 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Craft tools, isolated workers, tool_result helpers.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - - -def test_tool_worker_actor_read(tmp_path: Path) -> None: - from pulsing.forge import ToolWorkerActor, ToolWorkerConfig - - p = tmp_path / "x.txt" - p.write_text("hello", encoding="utf-8") - out = ToolWorkerActor(ToolWorkerConfig(cwd=str(tmp_path))).Read(file_path=str(p)) - assert out["content"] == "hello" - assert out.get("is_error") is False - - -def test_tool_worker_actor_default_config_no_on_start() -> None: - """Constructing without a config (and without on_start) must not crash.""" - from pulsing.forge import ToolWorkerActor - - out = ToolWorkerActor().Glob(pattern="*.md") - assert out.get("is_error") is False - - -def test_tool_result_dataclass() -> None: - pytest.importorskip("anthropic") - from pulsing.agent.loop.tool_base import ToolResult - - r = ToolResult(content="ok") - assert r.content == "ok" - assert r.is_error is False - - -def test_tool_result_from_worker_value() -> None: - from pulsing.agent.loop.tool_base import tool_result_from_worker_value - - r = tool_result_from_worker_value({"content": "x", "is_error": True}) - assert r.content == "x" and r.is_error is True - - -def test_split_tools_builds_core_list() -> None: - from pulsing.agent.loop.forge_tools import assert_forge_tool_coverage - from pulsing.agent.loop.permissions import PermissionChecker - from pulsing.agent.loop.split_tools import build_tools_for_agent - from pulsing.forge.integrated import FORGE_TOOL_NAMES - - assert_forge_tool_coverage() - tools = build_tools_for_agent(PermissionChecker(auto_approve=True)) - names = {t.name for t in tools} - assert FORGE_TOOL_NAMES <= names - assert "FetchUrl" in names - assert "QuestReport" in names - with pytest.raises(RuntimeError): - next(t for t in tools if t.name == "Read").execute(file_path=".") - - -def test_split_tools_includes_cluster_when_enabled() -> None: - from pulsing.agent.loop.permissions import PermissionChecker - from pulsing.agent.loop.split_tools import build_tools_for_agent - - tools = build_tools_for_agent( - PermissionChecker(auto_approve=True), - cluster_enabled=True, - summon_enabled=True, - ) - names = {t.name for t in tools} - assert "ListClusterAgents" in names - assert "MessageClusterAgent" in names - assert "Summon" in names - assert "QuestReport" in names diff --git a/tests/python/agent/test_watch.py b/tests/python/agent/test_watch.py deleted file mode 100644 index c0cc45e52..000000000 --- a/tests/python/agent/test_watch.py +++ /dev/null @@ -1,41 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Cluster activity watch.""" - -from __future__ import annotations - -import time - -from pulsing.agent.cluster.activity import format_activity_table - - -def test_format_activity_table_empty() -> None: - assert "no agents" in format_activity_table([]).lower() - - -def test_format_activity_table_busy_first() -> None: - now = time.time() - text = format_activity_table( - [ - { - "name": "guide", - "npc_class": "artisan", - "state": "tool", - "from": "player", - "tool": "Read", - "detail": "src/a.py", - "since": now - 3, - }, - { - "name": "scout", - "npc_class": "scholar", - "state": "idle", - "from": "", - "detail": "", - "since": now - 120, - }, - ], - ) - assert "guide" in text - assert "Read" in text - assert "scout" in text - assert "idle" in text diff --git a/tests/python/agent/test_workspace.py b/tests/python/agent/test_workspace.py deleted file mode 100644 index 8e047ea23..000000000 --- a/tests/python/agent/test_workspace.py +++ /dev/null @@ -1,82 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace config, naming, scoped discovery.""" - -from __future__ import annotations - -import json -import uuid -from pathlib import Path - -import pytest - -from pulsing.agent.cluster.constants import ( - full_agent_name, - short_agent_name, - workspace_agent_name, -) -from pulsing.agent.cluster.discovery import list_cluster_agents -from pulsing.agent.npc import spawn_npc -from pulsing.agent.npc.config import NpcConfig -from pulsing.agent.workspace.config import ( - default_config, - load_config, - save_config, - write_node_record, -) -from pulsing.agent.workspace.root import find_workspace_root, workspace_cluster_id - - -def test_workspace_agent_naming() -> None: - ws = "abc123" - assert workspace_agent_name(ws, "lead") == "craft/ws/abc123/lead" - assert short_agent_name("craft/ws/abc123/coder", workspace_id=ws) == "coder" - assert full_agent_name("lead", workspace_id=ws) == "craft/ws/abc123/lead" - - -def test_init_and_find_root(tmp_path: Path) -> None: - cfg = default_config(tmp_path) - save_config(cfg) - assert find_workspace_root(tmp_path / "src" / "nested") == tmp_path.resolve() - assert load_config(tmp_path).cluster_id == workspace_cluster_id(tmp_path) - - -def test_node_record_roundtrip(tmp_path: Path) -> None: - cfg = default_config(tmp_path) - save_config(cfg) - write_node_record(cfg, addr="127.0.0.1:9001", pid=42) - data = json.loads(cfg.node_path.read_text()) - assert data["addr"] == "127.0.0.1:9001" - assert cfg.seed_addr() == "127.0.0.1:9001" - - -@pytest.mark.asyncio -async def test_scoped_discovery_isolates_workspace(tmp_path: Path) -> None: - import pulsing as pul - - cfg = default_config(tmp_path) - save_config(cfg) - ws = cfg.cluster_id - name = f"lead-{uuid.uuid4().hex[:6]}" - - await pul.init() - try: - config = NpcConfig( - model="claude-sonnet-4-20250514", - cwd=str(tmp_path), - agent_name=name, - workspace_id=ws, - auto_approve=True, - ) - await spawn_npc( - config, - name=full_agent_name(name, workspace_id=ws), - public=True, - ) - rows = await list_cluster_agents(pul.get_system(), workspace_id=ws) - assert any(r["name"] == name for r in rows) - other = await list_cluster_agents( - pul.get_system(), workspace_id="other-workspace-id" - ) - assert not any(r["name"] == name for r in other) - finally: - await pul.shutdown() diff --git a/tests/python/agent/test_world.py b/tests/python/agent/test_world.py deleted file mode 100644 index f115ba037..000000000 --- a/tests/python/agent/test_world.py +++ /dev/null @@ -1,50 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Workspace world view and puzzles.""" - -from __future__ import annotations - -from pathlib import Path - -from pulsing.agent.workspace.config import default_config, load_config, save_config -from pulsing.agent.workspace.quest import update_quest_status -from pulsing.agent.workspace.world_view import format_puzzles, puzzles_at, render_look - - -def test_default_has_puzzle() -> None: - cfg = default_config(Path("/tmp/demo")) - assert "unit-tests" in cfg.puzzles - assert cfg.puzzles["unit-tests"].get("status") == "open" - - -def test_puzzles_at_tests_dir(tmp_path: Path) -> None: - (tmp_path / "tests").mkdir() - cfg = default_config(tmp_path) - here = puzzles_at(cfg, tmp_path / "tests") - assert any(pid == "unit-tests" for pid, _ in here) - - -def test_render_look(tmp_path: Path) -> None: - (tmp_path / "tests").mkdir() - cfg = default_config(tmp_path) - text = render_look(cfg, cwd=tmp_path / "tests") - assert "unit-tests" in text - assert "player:" in text - - -def test_format_puzzles() -> None: - cfg = default_config(Path("/tmp/demo")) - assert "unit-tests" in format_puzzles(cfg, all_=True) - - -def test_quest_update_and_assign(tmp_path: Path) -> None: - cfg = default_config(tmp_path) - save_config(cfg) - updated = update_quest_status( - tmp_path, "unit-tests", status="in_progress", reporter="guide" - ) - assert updated["status"] == "in_progress" - cfg2 = load_config(tmp_path) - cfg2.puzzles["unit-tests"]["assign_to"] = "guide" - save_config(cfg2) - cfg3 = load_config(tmp_path) - assert cfg3.puzzles["unit-tests"]["assign_to"] == "guide" diff --git a/tests/python/cli/test_agent_phase3.py b/tests/python/cli/test_agent_phase3.py deleted file mode 100644 index f614c9f69..000000000 --- a/tests/python/cli/test_agent_phase3.py +++ /dev/null @@ -1,17 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Phase 3: CLI commands live in pulsing.cli.agent.""" - -from __future__ import annotations - -from pulsing.cli.agent.commands.follow import should_emit -from pulsing.cli.agent.helpers import DEFAULT_PROG as AGENT_DEFAULT_PROG - - -def test_agent_default_prog() -> None: - assert AGENT_DEFAULT_PROG == "pulsing agent" - - -def test_should_emit_delta() -> None: - assert should_emit("a", "a", delta=True) is False - assert should_emit("a", "b", delta=True) is True - assert should_emit("a", "a", delta=False) is True diff --git a/tests/python/cli/test_cli_actor.py b/tests/python/cli/test_cli_actor.py index 570407c7b..5b8f1a54b 100644 --- a/tests/python/cli/test_cli_actor.py +++ b/tests/python/cli/test_cli_actor.py @@ -33,4 +33,4 @@ def test_actor_invalid_class_path_message(self): with pytest.raises(ValueError) as exc_info: actor_cli(actor_type="router") assert "full class path" in str(exc_info.value) - assert "pulsing.serving.worker.TransformersWorker" in str(exc_info.value) + assert "my_app.Counter" in str(exc_info.value) diff --git a/tests/python/forge/conftest.py b/tests/python/forge/conftest.py deleted file mode 100644 index c3406b817..000000000 --- a/tests/python/forge/conftest.py +++ /dev/null @@ -1,33 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Shared pytest fixtures for Forge gate tests.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE -from pulsing.testing.forge_harness import local_runtime - - -@pytest.fixture -def forge_workspace(tmp_path: Path) -> Path: - return tmp_path - - -@pytest.fixture -def local_forge(forge_workspace: Path): - return local_runtime(forge_workspace) - - -@pytest.fixture -def hybrid_forge(forge_workspace: Path): - from pulsing.forge.hybrid_runtime import HybridForgeRuntime - - if not RUST_FORGE_AVAILABLE: - pytest.skip("requires maturin develop") - return HybridForgeRuntime.create( - cwd=str(forge_workspace), - auto_approve=True, - ) diff --git a/tests/python/forge/test_apply_patch_escape.py b/tests/python/forge/test_apply_patch_escape.py deleted file mode 100644 index f24b3e8db..000000000 --- a/tests/python/forge/test_apply_patch_escape.py +++ /dev/null @@ -1,68 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""apply_patch path escape protection.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge.patch_invocation import ParsedPatch, apply_parsed_patch -from pulsing.testing.forge_harness import local_runtime - -pytestmark = pytest.mark.forge - - -def test_apply_patch_rejects_relative_escape_outside_cwd(tmp_path: Path) -> None: - workspace = tmp_path / "workspace" - workspace.mkdir() - patch = "*** Begin Patch\n*** Add File: ../escape.txt\n+pwned\n*** End Patch\n" - rt = local_runtime(workspace) - out = rt.call_tool("apply_patch", {"patch": patch}) - assert out.is_error - assert "outside working directory" in out.content - assert not (tmp_path / "escape.txt").exists() - - -def test_apply_patch_rejects_absolute_path_outside_cwd(tmp_path: Path) -> None: - workspace = tmp_path / "workspace" - workspace.mkdir() - outside = tmp_path / "outside.txt" - patch = f"*** Begin Patch\n*** Add File: {outside}\n+pwned\n*** End Patch\n" - rt = local_runtime(workspace) - out = rt.call_tool("apply_patch", {"patch": patch}) - assert out.is_error - assert "outside working directory" in out.content - assert not outside.exists() - - -def test_apply_patch_allows_absolute_path_inside_cwd(tmp_path: Path) -> None: - target = tmp_path / "abs.txt" - patch = f"*** Begin Patch\n*** Add File: {target}\n+ok\n*** End Patch\n" - rt = local_runtime(tmp_path) - out = rt.call_tool("apply_patch", {"patch": patch}) - assert not out.is_error - assert target.read_text(encoding="utf-8") == "ok\n" - - -def test_apply_patch_rejects_workdir_escape(tmp_path: Path) -> None: - workspace = tmp_path / "workspace" - workspace.mkdir() - patch = "*** Begin Patch\n*** Add File: ok.txt\n+ok\n*** End Patch\n" - with pytest.raises(ValueError, match="outside working directory"): - apply_parsed_patch(ParsedPatch(patch=patch, workdir=".."), workspace) - - -@pytest.mark.skipif(not hasattr(Path, "symlink_to"), reason="symlinks unsupported") -def test_apply_patch_rejects_symlink_escape(tmp_path: Path) -> None: - workspace = tmp_path / "workspace" - workspace.mkdir() - outside = tmp_path / "outside" - outside.mkdir() - (workspace / "link").symlink_to(outside) - patch = "*** Begin Patch\n*** Add File: link/pwned.txt\n+escaped\n*** End Patch\n" - rt = local_runtime(workspace) - out = rt.call_tool("apply_patch", {"patch": patch}) - assert out.is_error - assert "outside working directory" in out.content - assert not (outside / "pwned.txt").exists() diff --git a/tests/python/forge/test_code_mode.py b/tests/python/forge/test_code_mode.py deleted file mode 100644 index 9a073d338..000000000 --- a/tests/python/forge/test_code_mode.py +++ /dev/null @@ -1,156 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""``exec`` / code_mode behavior — sandbox boundary, cell state, error mapping.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.testing.forge_harness import local_runtime - -pytestmark = [pytest.mark.forge] - - -def _exec(rt, source: str, **extra): - return rt.call_tool("exec", {"source": source, **extra}) - - -def test_exec_runs_and_returns_text(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = _exec(rt, "text('hi')") - assert not out.is_error - assert "hi" in out.content - assert out.structured["kind"] == "result" - - -def test_exec_empty_source_is_error(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool("exec", {"source": " "}) - assert out.is_error - assert "empty" in out.content - - -def test_exec_error_message_includes_exception_type(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = _exec(rt, "1 / 0") - assert out.structured["error_text"].startswith("ZeroDivisionError:") - assert "Error:" in out.content - - -def test_exec_syntax_error_is_reported_not_raised(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = _exec(rt, "def broken(:\n pass") - assert out.structured["error_text"].startswith("SyntaxError:") - - -@pytest.mark.parametrize( - "source", - [ - "open('/etc/passwd')", - "__import__('os')", - "eval('1')", - "exec('1')", - ], -) -def test_exec_blocks_raw_io_and_import_builtins( - forge_workspace: Path, source: str -) -> None: - """Defense-in-depth: cells run in-process with no OS sandbox, so the most - obvious escapes (file I/O, module import, eval/exec) must be unavailable - via the restricted builtins — even though this is not a full security - boundary (see code_mode/cell.py comment).""" - rt = local_runtime(forge_workspace) - out = _exec(rt, source) - assert out.structured["error_text"].startswith("NameError:") - - -def test_exec_nested_tool_call_respects_allowlist(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = _exec(rt, "tools.call('exec', {'source': 'text(1)'})") - assert out.structured["error_text"].startswith("PermissionError:") - assert "not available in code mode" in out.structured["error_text"] - - -def test_exec_nested_tool_call_reaches_real_tool(forge_workspace: Path) -> None: - (forge_workspace / "sample.txt").write_text("hello\n", encoding="utf-8") - rt = local_runtime(forge_workspace) - out = _exec(rt, "text(tools.call('shell_command', {'command': 'echo ok'}))") - assert not out.is_error - assert "ok" in out.content.lower() - - -def test_exec_rejects_sandbox_policy_when_isolation_requested( - forge_workspace: Path, -) -> None: - """``exec`` has no OS-level isolation to apply sandbox_policy to; it must - fail closed instead of silently running unsandboxed code when isolation - was explicitly requested (sandbox-boundary bypass otherwise).""" - rt = local_runtime(forge_workspace, sandbox_policy="restricted") - out = _exec(rt, "text('should not run')") - assert out.is_error - assert "sandbox_policy" in out.content - - -def test_exec_rejects_per_call_sandbox_off_when_ctx_restricted( - forge_workspace: Path, -) -> None: - """Per-call sandbox_policy='off' must not downgrade a restricted session.""" - rt = local_runtime(forge_workspace, sandbox_policy="restricted") - out = rt.call_tool( - "exec", {"source": "text('should not run')", "sandbox_policy": "off"} - ) - assert out.is_error - assert "sandbox_policy" in out.content - - -@pytest.mark.parametrize("policy", ["restricted", "bwrap"]) -def test_exec_rejects_non_off_policies(forge_workspace: Path, policy: str) -> None: - rt = local_runtime(forge_workspace, sandbox_policy=policy) - out = _exec(rt, "text('should not run')") - assert out.is_error - assert policy in out.content - - -def test_exec_dangerously_disable_sandbox_overrides_rejection( - forge_workspace: Path, -) -> None: - rt = local_runtime(forge_workspace, sandbox_policy="restricted") - out = _exec(rt, "text('ok')", dangerously_disable_sandbox=True) - assert not out.is_error - assert "ok" in out.content - - -def test_exec_off_policy_is_unaffected(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace, sandbox_policy="off") - out = _exec(rt, "text('ok')") - assert not out.is_error - - -def test_wait_unknown_cell_id_is_error(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool("wait", {"cell_id": "does-not-exist"}) - assert out.is_error - - -def test_exec_then_wait_returns_same_cell(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - first = _exec(rt, "text('hi')") - cell_id = first.structured["cell_id"] - out = rt.call_tool("wait", {"cell_id": cell_id}) - assert not out.is_error - assert out.structured["cell_id"] == cell_id - - -def test_exec_yield_then_wait_resumes(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - source = 'text("part1")\nyield_control()\ntext("part2")\n' - first = _exec(rt, source) - assert first.structured["kind"] == "yielded" - assert "part1" in first.content - assert "part2" not in first.content - - out = rt.call_tool("wait", {"cell_id": first.structured["cell_id"]}) - assert not out.is_error - assert out.structured["kind"] == "result" - assert "part2" in out.content diff --git a/tests/python/forge/test_edit.py b/tests/python/forge/test_edit.py deleted file mode 100644 index db9e7ab62..000000000 --- a/tests/python/forge/test_edit.py +++ /dev/null @@ -1,135 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Edit tool: unique replace, ambiguity, path escape.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.testing.forge_harness import local_runtime - -pytestmark = pytest.mark.forge - - -def test_edit_replaces_unique_occurrence(tmp_path: Path) -> None: - target = tmp_path / "a.txt" - target.write_text("hello world", encoding="utf-8") - rt = local_runtime(tmp_path) - out = rt.call_tool( - "Edit", - {"file_path": "a.txt", "old_string": "world", "new_string": "there"}, - ) - assert not out.is_error - assert target.read_text(encoding="utf-8") == "hello there" - - -def test_edit_rejects_missing_old_string(tmp_path: Path) -> None: - target = tmp_path / "a.txt" - target.write_text("hello world", encoding="utf-8") - rt = local_runtime(tmp_path) - out = rt.call_tool( - "Edit", - {"file_path": "a.txt", "old_string": "nope", "new_string": "x"}, - ) - assert out.is_error - assert "not found" in out.content - assert target.read_text(encoding="utf-8") == "hello world" - - -def test_edit_rejects_ambiguous_old_string_with_count(tmp_path: Path) -> None: - target = tmp_path / "a.txt" - target.write_text("a a a", encoding="utf-8") - rt = local_runtime(tmp_path) - out = rt.call_tool( - "Edit", - {"file_path": "a.txt", "old_string": "a", "new_string": "b"}, - ) - assert out.is_error - assert "3 occurrences" in out.content - assert target.read_text(encoding="utf-8") == "a a a" - - -def test_edit_rejects_relative_escape_outside_cwd(tmp_path: Path) -> None: - workspace = tmp_path / "workspace" - workspace.mkdir() - target = workspace / "a.txt" - target.write_text("hello world", encoding="utf-8") - rt = local_runtime(workspace) - out = rt.call_tool( - "Edit", - {"file_path": "../a.txt", "old_string": "world", "new_string": "there"}, - ) - assert out.is_error - assert "outside working directory" in out.content - assert target.read_text(encoding="utf-8") == "hello world" - - -def test_edit_rejects_absolute_path_outside_cwd(tmp_path: Path) -> None: - workspace = tmp_path / "workspace" - workspace.mkdir() - outside = tmp_path / "outside.txt" - outside.write_text("secret", encoding="utf-8") - rt = local_runtime(workspace) - out = rt.call_tool( - "Edit", - {"file_path": str(outside), "old_string": "secret", "new_string": "leaked"}, - ) - assert out.is_error - assert "outside working directory" in out.content - assert outside.read_text(encoding="utf-8") == "secret" - - -def test_edit_allows_absolute_path_inside_cwd(tmp_path: Path) -> None: - target = tmp_path / "inside.txt" - target.write_text("hello world", encoding="utf-8") - rt = local_runtime(tmp_path) - out = rt.call_tool( - "Edit", - { - "file_path": str(target), - "old_string": "world", - "new_string": "there", - }, - ) - assert not out.is_error - assert target.read_text(encoding="utf-8") == "hello there" - - -def test_edit_rejects_missing_file(tmp_path: Path) -> None: - rt = local_runtime(tmp_path) - out = rt.call_tool( - "Edit", - {"file_path": "missing.txt", "old_string": "a", "new_string": "b"}, - ) - assert out.is_error - assert "file not found" in out.content - - -def test_edit_rejects_directory_path(tmp_path: Path) -> None: - (tmp_path / "sub").mkdir() - rt = local_runtime(tmp_path) - out = rt.call_tool( - "Edit", - {"file_path": "sub", "old_string": "a", "new_string": "b"}, - ) - assert out.is_error - assert "not a file" in out.content - - -def test_edit_rejects_symlink_escape_outside_cwd(tmp_path: Path) -> None: - workspace = tmp_path / "workspace" - workspace.mkdir() - outside = tmp_path / "outside.txt" - outside.write_text("secret", encoding="utf-8") - link = workspace / "link.txt" - link.symlink_to(outside) - rt = local_runtime(workspace) - out = rt.call_tool( - "Edit", - {"file_path": "link.txt", "old_string": "secret", "new_string": "leaked"}, - ) - assert out.is_error - assert "outside working directory" in out.content - assert outside.read_text(encoding="utf-8") == "secret" - assert link.is_symlink() diff --git a/tests/python/forge/test_exec_command.py b/tests/python/forge/test_exec_command.py deleted file mode 100644 index ad2c83703..000000000 --- a/tests/python/forge/test_exec_command.py +++ /dev/null @@ -1,73 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""exec_command sandbox, workdir boundary, and PTY cleanup tests.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.testing.forge_harness import local_runtime - -pytestmark = pytest.mark.forge - - -def test_exec_command_missing_cmd(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool("exec_command", {"yield_time_ms": 300}) - assert out.is_error - assert "missing cmd/command" in out.content - - -def test_exec_command_rejects_workdir_escape(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool( - "exec_command", - {"cmd": "echo hi", "workdir": "..", "yield_time_ms": 300, "tty": False}, - ) - assert out.is_error - assert "outside working directory" in out.content - - -def test_exec_command_rejects_tty_with_restricted_sandbox( - forge_workspace: Path, -) -> None: - rt = local_runtime(forge_workspace, sandbox_policy="restricted") - out = rt.call_tool( - "exec_command", - {"cmd": "echo hi", "yield_time_ms": 300, "tty": True}, - ) - assert out.is_error - assert "cannot use sandbox policy" in out.content - - -def test_exec_command_pipe_mode_runs_under_restricted_sandbox( - forge_workspace: Path, -) -> None: - rt = local_runtime(forge_workspace, sandbox_policy="restricted") - out = rt.call_tool( - "exec_command", - {"cmd": "echo $PATH", "yield_time_ms": 500, "tty": False}, - ) - assert not out.is_error - output = (out.structured or {}).get("output") or "" - assert "/usr/bin:/bin:/usr/local/bin" in output - - -def test_exec_command_close_kills_background_sessions(forge_workspace: Path) -> None: - for tty in (False, True): - rt = local_runtime(forge_workspace) - out = rt.call_tool( - "exec_command", - {"cmd": "sleep 30", "yield_time_ms": 100, "tty": tty}, - ) - session_id = (out.structured or {}).get("session_id") - assert session_id is not None - session = rt.context.exec._sessions[session_id] - proc = session.pty.proc if session.pty is not None else session.proc - assert proc is not None - assert proc.poll() is None - - rt.close() - assert proc.poll() is not None - assert not rt.context.exec._sessions diff --git a/tests/python/forge/test_forge_agent.py b/tests/python/forge/test_forge_agent.py deleted file mode 100644 index 2671da7ed..000000000 --- a/tests/python/forge/test_forge_agent.py +++ /dev/null @@ -1,125 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for pulsing.forge.host (ForgeAgent + CliEventSink).""" - -from __future__ import annotations - -import io -from pathlib import Path - -import pytest - -from pulsing.forge import ForgeClient, LegacyPythonForgeAgent -from pulsing.forge.host import ForgeAgent -from pulsing.forge.host.cli_events import CliEventSink -from pulsing.forge.result import ToolResult - -pytestmark = pytest.mark.forge - - -def test_default_and_legacy_agents_have_explicit_ownership() -> None: - assert ForgeAgent is not LegacyPythonForgeAgent - assert "_runtime" not in ForgeAgent.__dataclass_fields__ - assert "_client" in ForgeAgent.__dataclass_fields__ - assert "_runtime" in LegacyPythonForgeAgent.__dataclass_fields__ - - -def test_native_forge_client_exposes_versioned_events(tmp_path: Path) -> None: - client = ForgeClient() - session_id = client.create_session( - cwd=str(tmp_path), - provider="demo", - model="demo", - ) - receipt = client.start_turn(session_id, "hello") - outcome = client.wait_turn( - session_id, - str(receipt["turn_id"]), - int(receipt["accepted_seq"]), - ) - - events = outcome["events"] - assert outcome["terminal"]["status"] == "completed" - assert events[-1]["protocol"] == "forge.event" - assert events[-1]["version"] == {"major": 1, "minor": 0} - assert events[-1]["kind"] == "turn_completed" - assert events[-1]["payload"]["text"] == "(demo) Noted: hello" - assert client.snapshot(session_id)["spec"]["approval_policy"] == "always" - - -def test_canonical_agent_rejects_python_owned_provider_credentials() -> None: - with pytest.raises(ValueError, match="Rust process configuration"): - ForgeAgent(provider="openai", api_key="python-owned-secret") - - -def test_cli_event_sink_tool_lines() -> None: - out = io.StringIO() - sink = CliEventSink(out=out, err=out) - sink.on_tool_begin("Glob", {"pattern": "*.md"}) - sink.on_tool_end("Glob", ToolResult(content="a.md")) - text = out.getvalue() - assert "→ Glob" in text - assert "← Glob [ok]" in text - - -@pytest.mark.asyncio -async def test_forge_agent_demo_glob(tmp_path: Path) -> None: - (tmp_path / "README.md").write_text("# hi\n", encoding="utf-8") - out = io.StringIO() - agent = ForgeAgent( - cwd=tmp_path, - provider="demo", - events=CliEventSink(out=out, stream_assistant=False), - ) - try: - answer = await agent.run("please glob project files") - assert "Glob" in out.getvalue() or answer - assert len(agent.messages) >= 3 - finally: - agent.close() - - -@pytest.mark.asyncio -async def test_forge_agent_demo_read_then_answer(tmp_path: Path) -> None: - (tmp_path / "README.md").write_text("# demo project\n", encoding="utf-8") - agent = ForgeAgent( - cwd=tmp_path, - provider="demo", - events=CliEventSink(stream_assistant=False), - ) - try: - await agent.run("read readme and summarize") - roles = [m["role"] for m in agent.messages] - assert "assistant" in roles - assert "user" in roles - finally: - agent.close() - - -@pytest.mark.asyncio -async def test_forge_agent_reuses_one_rust_session_across_turns( - tmp_path: Path, -) -> None: - agent = ForgeAgent( - cwd=tmp_path, - provider="demo", - events=CliEventSink(stream_assistant=False), - ) - try: - first = await agent.run("remember alpha") - first_snapshot = agent.session - second = await agent.run("remember beta") - second_snapshot = agent.session - - assert first == "(demo) Noted: remember alpha" - assert second == "(demo) Noted: remember beta" - assert first_snapshot["id"] == second_snapshot["id"] - assert len(first_snapshot["turns"]) == 1 - assert len(second_snapshot["turns"]) == 2 - assert [message["role"] for message in agent.messages] == [ - "user", - "assistant", - "user", - "assistant", - ] - finally: - agent.close() diff --git a/tests/python/forge/test_gates.py b/tests/python/forge/test_gates.py deleted file mode 100644 index 02d3d5587..000000000 --- a/tests/python/forge/test_gates.py +++ /dev/null @@ -1,46 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""L0–L1 Forge gates: registry + callable smoke.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge.codex_parity import format_report_text, parity_report -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE -from pulsing.testing.forge_harness import ( - LOCAL_PYTHON_TOOLS, - assert_forge_manifest, - run_tool_smoke, - smoke_failures, -) - -pytestmark = pytest.mark.forge - - -@pytest.mark.forge_l0 -def test_l0_forge_manifest() -> None: - assert_forge_manifest() - - -@pytest.mark.forge_l1 -def test_l1_local_python_tools_callable(local_forge, forge_workspace: Path) -> None: - failures = smoke_failures( - run_tool_smoke(local_forge, forge_workspace, tools=LOCAL_PYTHON_TOOLS) - ) - assert not failures, failures - - -@pytest.mark.forge_l1 -def test_l1_hybrid_all_tools_callable(hybrid_forge, forge_workspace: Path) -> None: - failures = smoke_failures(run_tool_smoke(hybrid_forge, forge_workspace)) - assert not failures, failures - - -@pytest.mark.forge_l1 -def test_l1_conformance_report(capsys) -> None: - """Print internal conformance scores for CI logs (informational).""" - report = parity_report(rust_available=RUST_FORGE_AVAILABLE) - print(format_report_text(report)) - assert report.gates["registry"].pct >= 96.0 diff --git a/tests/python/forge/test_get_context_remaining.py b/tests/python/forge/test_get_context_remaining.py deleted file mode 100644 index 351c77097..000000000 --- a/tests/python/forge/test_get_context_remaining.py +++ /dev/null @@ -1,118 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Focused checks for the ``get_context_remaining`` Forge tool. - -Handler contract (Rust + Python): ``{"tokens_remaining": , "status": "ok"|"unknown"}``. -Token counts come from ``ToolSession.tokens_remaining()`` — static ``token_budget`` on -``LocalToolSession``, or host-side estimate via ``AgentForgeSession`` / hybrid callback. -""" - -from __future__ import annotations - -import json -from pathlib import Path -from typing import Any -from unittest.mock import MagicMock - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE -from pulsing.forge.session import LocalToolSession, NullToolSession -from pulsing.testing.forge_harness import local_runtime - -pytestmark = [pytest.mark.forge, pytest.mark.forge_l2] - - -def _payload(out) -> dict[str, Any]: - return json.loads(out.content) - - -def test_known_budget_returns_ok(tmp_path: Path) -> None: - ctx = ToolCallContext(cwd=tmp_path, session=LocalToolSession(token_budget=42_000)) - out = dispatch_tool("get_context_remaining", {}, ctx=ctx) - assert not out.is_error - assert _payload(out) == {"tokens_remaining": 42_000, "status": "ok"} - - -def test_null_session_degrades_to_unknown(tmp_path: Path) -> None: - ctx = ToolCallContext(cwd=tmp_path, session=None) - assert isinstance(ctx.session, NullToolSession) - out = dispatch_tool("get_context_remaining", {}, ctx=ctx) - assert not out.is_error - assert _payload(out) == {"tokens_remaining": None, "status": "unknown"} - - -def test_local_session_without_budget_returns_unknown(tmp_path: Path) -> None: - ctx = ToolCallContext(cwd=tmp_path, session=LocalToolSession()) - out = dispatch_tool("get_context_remaining", {}, ctx=ctx) - assert not out.is_error - assert _payload(out) == {"tokens_remaining": None, "status": "unknown"} - - -def test_local_forge_default_session_reports_budget(tmp_path: Path) -> None: - rt = local_runtime(tmp_path) - out = rt.call_tool("get_context_remaining", {}) - assert not out.is_error - payload = _payload(out) - assert payload["status"] == "ok" - assert payload["tokens_remaining"] == 128_000 - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_hybrid_reads_session_token_budget(tmp_path: Path) -> None: - from pulsing.forge.hybrid_runtime import HybridForgeRuntime - - rt = HybridForgeRuntime.create( - cwd=str(tmp_path), - auto_approve=True, - session=LocalToolSession(token_budget=99_000), - ) - out = rt.call_tool("get_context_remaining", {}) - assert not out.is_error - payload = _payload(out) - assert payload["status"] == "ok" - assert payload["tokens_remaining"] == 99_000 - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_hybrid_python_payload_semantics_match(tmp_path: Path) -> None: - from pulsing.forge.hybrid_runtime import HybridForgeRuntime - - session = LocalToolSession(token_budget=55_000) - ctx = ToolCallContext(cwd=tmp_path, session=session) - py_out = dispatch_tool("get_context_remaining", {}, ctx=ctx) - hybrid = HybridForgeRuntime.create( - cwd=str(tmp_path), - auto_approve=True, - session=session, - ) - rust_out = hybrid.call_tool("get_context_remaining", {}) - assert _payload(py_out) == _payload(rust_out) - - -def test_agent_session_estimate_without_static_budget() -> None: - from pulsing.agent.actors.forge_session import AgentForgeSession - - llm = MagicMock() - llm.estimate_tokens_remaining.return_value = 12_345 - agent = MagicMock(_llm=llm) - session = AgentForgeSession(context_window=100_000) - session._agent = agent # noqa: SLF001 — host back-ref - assert session.tokens_remaining() == 12_345 - llm.estimate_tokens_remaining.assert_called_once_with(100_000) - - -def test_llm_estimate_tokens_remaining_from_transcript() -> None: - from pulsing.agent.loop.llm_chat import LlmChat - - llm = LlmChat( - backend=MagicMock(), - tools={}, - permission_checker=MagicMock(), - model="test", - max_tokens=1000, - ) - llm._messages = [{"role": "user", "content": "x" * 400}] - remaining = llm.estimate_tokens_remaining(context_window=10_000) - assert remaining == 10_000 - 100 - 1000 diff --git a/tests/python/forge/test_glob.py b/tests/python/forge/test_glob.py deleted file mode 100644 index fdc21427d..000000000 --- a/tests/python/forge/test_glob.py +++ /dev/null @@ -1,52 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Glob tool unit tests — matching, missing path, pattern safety, truncation.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -pytestmark = pytest.mark.forge - - -def _glob(rt, pattern: str, path: str | None = None): - args: dict[str, str] = {"pattern": pattern} - if path is not None: - args["path"] = path - return rt.call_tool("Glob", args) - - -def test_glob_finds_matching_files(local_forge, forge_workspace: Path) -> None: - (forge_workspace / "a.txt").write_text("x", encoding="utf-8") - (forge_workspace / "b.rs").write_text("x", encoding="utf-8") - out = _glob(local_forge, "*.txt", str(forge_workspace)) - assert not out.is_error - assert out.content.endswith("a.txt") - - -def test_glob_reports_no_matches(local_forge, forge_workspace: Path) -> None: - out = _glob(local_forge, "*.nope", str(forge_workspace)) - assert not out.is_error - assert out.content == "(no matches)" - - -def test_glob_rejects_missing_path(local_forge, forge_workspace: Path) -> None: - out = _glob(local_forge, "*", str(forge_workspace / "does" / "not" / "exist")) - assert out.is_error - assert "does not exist" in out.content - - -def test_glob_rejects_absolute_pattern(local_forge, forge_workspace: Path) -> None: - # An absolute pattern must not be able to escape `path`/cwd. - out = _glob(local_forge, "/etc/*", str(forge_workspace)) - assert out.is_error - assert "absolute" in out.content - - -def test_glob_truncates_with_clear_message(local_forge, forge_workspace: Path) -> None: - for i in range(510): - (forge_workspace / f"f{i}.txt").write_text("x", encoding="utf-8") - out = _glob(local_forge, "*.txt", str(forge_workspace)) - assert not out.is_error - assert "truncated: showing 500 of 510 matches" in out.content diff --git a/tests/python/forge/test_grep.py b/tests/python/forge/test_grep.py deleted file mode 100644 index 47004f700..000000000 --- a/tests/python/forge/test_grep.py +++ /dev/null @@ -1,97 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Grep tool — behavior, safety, and error handling.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.handlers import _grep - -pytestmark = [pytest.mark.forge, pytest.mark.forge_l2] - - -def _ctx(tmp_path: Path) -> ToolCallContext: - return ToolCallContext(cwd=tmp_path) - - -def test_grep_finds_matches(tmp_path: Path) -> None: - (tmp_path / "a.txt").write_text("hello\nworld\nhello again\n", encoding="utf-8") - out = _grep(ctx=_ctx(tmp_path), pattern="hello", path=str(tmp_path)) - assert not out.is_error - assert out.content.count("hello") == 2 - assert "a.txt:1:hello" in out.content - - -def test_grep_invalid_regex(tmp_path: Path) -> None: - out = _grep(ctx=_ctx(tmp_path), pattern="(unclosed", path=str(tmp_path)) - assert out.is_error - assert "Invalid regex" in out.content - - -def test_grep_path_not_found(tmp_path: Path) -> None: - out = _grep(ctx=_ctx(tmp_path), pattern="x", path=str(tmp_path / "missing")) - assert out.is_error - assert "path not found" in out.content - - -def test_grep_path_outside_cwd_is_allowed(tmp_path: Path) -> None: - """Grep (like Glob) does not sandbox path — document current behavior.""" - outside = tmp_path.parent / "outside_grep.txt" - outside.write_text("secret_token\n", encoding="utf-8") - try: - out = _grep(ctx=_ctx(tmp_path), pattern="secret_token", path=str(outside)) - assert not out.is_error - assert "secret_token" in out.content - finally: - outside.unlink(missing_ok=True) - - -def test_grep_redos_pattern_returns_within_timeout(tmp_path: Path) -> None: - """Pathological pattern must not block the tool call indefinitely.""" - evil_line = "a" * 40 + "!" - (tmp_path / "evil.txt").write_text(evil_line, encoding="utf-8") - out = _grep(ctx=_ctx(tmp_path), pattern="(a+)+b", path=str(tmp_path)) - # Either no match or explicit timeout error — must not hang. - assert out.is_error or out.content == "(no matches)" or "timed out" in out.content - - -def test_grep_pattern_too_long(tmp_path: Path) -> None: - out = _grep(ctx=_ctx(tmp_path), pattern="a" * 1001, path=str(tmp_path)) - assert out.is_error - assert "Pattern too long" in out.content - - -def test_grep_truncation_message(tmp_path: Path) -> None: - (tmp_path / "many.txt").write_text("hit\n" * 250, encoding="utf-8") - out = _grep(ctx=_ctx(tmp_path), pattern="hit", path=str(tmp_path)) - assert not out.is_error - assert "truncated: showing 200 of 250 matches" in out.content - - -def test_grep_relative_path_resolves_against_ctx_cwd( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - sub = tmp_path / "sub" - sub.mkdir() - (sub / "a.txt").write_text("needle\n", encoding="utf-8") - other = tmp_path.parent / "other_cwd" - other.mkdir(exist_ok=True) - monkeypatch.chdir(other) - out = _grep(ctx=_ctx(tmp_path), pattern="needle", path="sub") - assert not out.is_error - assert "needle" in out.content - - -def test_grep_skips_symlink_outside_cwd(tmp_path: Path) -> None: - outside = tmp_path.parent / "outside_grep_secret.txt" - outside.write_text("outside_secret\n", encoding="utf-8") - (tmp_path / "link.txt").symlink_to(outside) - try: - out = _grep(ctx=_ctx(tmp_path), pattern="outside_secret", path=str(tmp_path)) - assert not out.is_error - assert out.content == "(no matches)" - finally: - outside.unlink(missing_ok=True) diff --git a/tests/python/forge/test_integration.py b/tests/python/forge/test_integration.py deleted file mode 100644 index 713bfb055..000000000 --- a/tests/python/forge/test_integration.py +++ /dev/null @@ -1,45 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""L3 Forge integration — trace replay and end-to-end tool flows.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge.repl.session import ForgeReplSession -from pulsing.forge.repl.trace import TraceLog, TraceRecord, load_trace, save_trace - -pytestmark = [pytest.mark.forge, pytest.mark.forge_l3] - -_FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "forge_traces" - - -@pytest.mark.forge_l4 -def test_l4_trace_fixture_replay_verify(tmp_path: Path) -> None: - src = tmp_path / "sample.txt" - src.write_text("forge-repl-fixture", encoding="utf-8") - log = TraceLog() - log.append( - TraceRecord( - seq=1, - kind="tool_call", - tool="Read", - arguments={"file_path": "sample.txt"}, - result={"content": "forge-repl-fixture", "is_error": False}, - ) - ) - trace_path = tmp_path / "t.jsonl" - save_trace(trace_path, log) - session = ForgeReplSession(cwd=tmp_path) - session.load_replay_trace(trace_path) - msg = session.replay_step(verify=True) - assert "[ok]" in msg - - -def test_l3_shipped_trace_fixture() -> None: - path = _FIXTURES / "read_sample.jsonl" - assert path.is_file() - loaded = load_trace(path) - assert len(loaded.tool_calls()) == 1 - assert loaded.tool_calls()[0].tool == "Read" diff --git a/tests/python/forge/test_mcp_dynamic_tools.py b/tests/python/forge/test_mcp_dynamic_tools.py deleted file mode 100644 index 412a739d2..000000000 --- a/tests/python/forge/test_mcp_dynamic_tools.py +++ /dev/null @@ -1,68 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""MCP dynamic function tools — routing, wire schema, hybrid integration.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge.hybrid_runtime import HybridForgeRuntime -from pulsing.forge.mcp.manager import McpManager -from pulsing.forge.mcp.naming import MCP_TOOL_NAME_PREFIX, is_mcp_dynamic_tool -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE - -pytestmark = pytest.mark.forge - - -def test_is_mcp_dynamic_tool() -> None: - assert is_mcp_dynamic_tool("mcp__github__search") - assert not is_mcp_dynamic_tool("list_mcp_resources") - assert not is_mcp_dynamic_tool("Read") - - -def test_mcp_manager_sync_live_tools_from_rust() -> None: - class _Rust: - def mcp_tool_specs(self) -> list[dict]: - return [ - { - "name": "mcp__demo__echo", - "description": "Echo", - "input_schema": { - "type": "object", - "properties": {"msg": {"type": "string"}}, - }, - "server_name": "demo", - "tool_name": "echo", - } - ] - - mgr = McpManager() - mgr.sync_live_tools_from_rust(_Rust()) - stubs = mgr.deferred_tool_stubs() - assert len(stubs) == 1 - assert stubs[0].model_name == "mcp__demo__echo" - assert stubs[0].input_schema["properties"]["msg"]["type"] == "string" - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_hybrid_mcp_dynamic_tool_routes_to_rust(tmp_path: Path) -> None: - rt = HybridForgeRuntime.create(cwd=str(tmp_path), auto_approve=True) - name = f"{MCP_TOOL_NAME_PREFIX}missing__tool" - out = rt.call_tool(name, {}) - assert not out.content.startswith("Unknown tool:") - assert "unknown MCP tool" in out.content.lower() or "MCP tool" in out.content - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_hybrid_mcp_tool_specs_wire_schema(tmp_path: Path) -> None: - rt = HybridForgeRuntime.create(cwd=str(tmp_path), auto_approve=True) - rust = rt.rust_runtime - assert rust is not None - specs = rust.mcp_tool_specs() - assert isinstance(specs, list) - for spec in specs: - assert spec["name"].startswith(MCP_TOOL_NAME_PREFIX) - schema = spec.get("input_schema") or {} - assert schema.get("type") == "object" - assert isinstance(schema.get("properties"), dict) diff --git a/tests/python/forge/test_mcp_resources.py b/tests/python/forge/test_mcp_resources.py deleted file mode 100644 index 32e940660..000000000 --- a/tests/python/forge/test_mcp_resources.py +++ /dev/null @@ -1,54 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Hybrid MCP resource listing — list_mcp_resources behavior.""" - -from __future__ import annotations - -import json - -import pytest - -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE - -pytestmark = [ - pytest.mark.forge, - pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop"), -] - - -@pytest.mark.forge_l1 -def test_list_mcp_resources_returns_json_object(hybrid_forge) -> None: - out = hybrid_forge.call_tool("list_mcp_resources", {}) - assert not out.is_error - assert "MCP runtime is not initialized" not in out.content - assert "MCP runtime is not started" not in out.content - parsed = json.loads(out.content) - assert isinstance(parsed, dict) - - -@pytest.mark.forge_l1 -def test_list_mcp_resources_cursor_requires_server(hybrid_forge) -> None: - out = hybrid_forge.call_tool("list_mcp_resources", {"cursor": "next"}) - assert out.is_error - assert "server" in out.content.lower() - - -@pytest.mark.forge_l1 -def test_list_mcp_resources_unknown_server(hybrid_forge) -> None: - out = hybrid_forge.call_tool("list_mcp_resources", {"server": "missing-forge-test"}) - assert out.is_error - assert "not connected" in out.content.lower() - - -@pytest.mark.forge_l1 -def test_list_mcp_resources_rejects_blank_server(hybrid_forge) -> None: - out = hybrid_forge.call_tool("list_mcp_resources", {"server": " "}) - assert out.is_error - assert "non-empty" in out.content.lower() - - -@pytest.mark.forge_l1 -def test_refresh_mcp_keeps_list_resources_callable(hybrid_forge) -> None: - hybrid_forge.refresh_mcp() - out = hybrid_forge.call_tool("list_mcp_resources", {}) - assert not out.is_error - assert json.loads(out.content) == {} diff --git a/tests/python/forge/test_new_context.py b/tests/python/forge/test_new_context.py deleted file mode 100644 index b74f86b93..000000000 --- a/tests/python/forge/test_new_context.py +++ /dev/null @@ -1,63 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Focused checks for the ``new_context`` tool (Python fallback path).""" - -from __future__ import annotations - -import re -from pathlib import Path - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.handlers import NEW_CONTEXT_MESSAGE, dispatch_tool -from pulsing.forge.runtime import LocalToolRuntime -from pulsing.forge.session import LocalToolSession - -pytestmark = [pytest.mark.forge, pytest.mark.forge_l2] - -_RUST_SESSION_RS = ( - Path(__file__).resolve().parents[3] / "crates/pulsing-forge/src/handlers/session.rs" -) - - -def test_new_context_message_matches_rust_constant() -> None: - text = _RUST_SESSION_RS.read_text(encoding="utf-8") - match = re.search(r'pub const NEW_CONTEXT_MESSAGE: &str =\s*\n?\s*"([^"]+)";', text) - assert match is not None, "NEW_CONTEXT_MESSAGE not found in session.rs" - assert match.group(1) == NEW_CONTEXT_MESSAGE - - -def test_new_context_returns_message_and_flags_session(tmp_path: Path) -> None: - session = LocalToolSession() - rt = LocalToolRuntime(cwd=str(tmp_path), session=session) - - out = rt.call_tool("new_context", {}) - - assert not out.is_error - assert out.content == NEW_CONTEXT_MESSAGE - assert session.new_context_requested is True - - -def test_new_context_without_session_does_not_raise(tmp_path: Path) -> None: - """Missing session falls back to NullToolSession — call must still succeed.""" - ctx = ToolCallContext(cwd=tmp_path, session=None) - - out = dispatch_tool("new_context", {}, ctx=ctx) - - assert not out.is_error - assert out.content == NEW_CONTEXT_MESSAGE - - -def test_new_context_propagates_session_error(tmp_path: Path) -> None: - session = LocalToolSession() - - def fail() -> None: - raise RuntimeError("session unavailable") - - session.request_new_context = fail # type: ignore[method-assign] - ctx = ToolCallContext(cwd=tmp_path, session=session) - - out = dispatch_tool("new_context", {}, ctx=ctx) - - assert out.is_error - assert out.content == "session unavailable" diff --git a/tests/python/forge/test_plan.py b/tests/python/forge/test_plan.py deleted file mode 100644 index 569aac619..000000000 --- a/tests/python/forge/test_plan.py +++ /dev/null @@ -1,114 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the ``update_plan`` Forge tool (Codex plan/todo parity). - -Reference: vendor/codex-rs/protocol/src/plan_tool.rs (``UpdatePlanArgs``, -``PlanItemArg``, ``StepStatus``) - the closest Codex protocol type, since the -`update_plan` tool handler itself (codex-rs/core/src/tools/handlers/plan.rs) -does no validation beyond parsing. -""" - -from __future__ import annotations - -import pytest - -from pulsing.forge.session import PlanItem, StepStatus, UpdatePlanArgs - -pytestmark = pytest.mark.forge - - -def test_update_plan_valid_call_updates_session(local_forge) -> None: - out = local_forge.call_tool( - "update_plan", - { - "plan": [ - {"step": "one", "status": "pending"}, - {"step": "two", "status": "in_progress"}, - ] - }, - ) - - assert not out.is_error - assert local_forge.context.session.plan == [ - PlanItem(step="one", status=StepStatus.PENDING), - PlanItem(step="two", status=StepStatus.IN_PROGRESS), - ] - - -def test_update_plan_accepts_empty_plan(local_forge) -> None: - out = local_forge.call_tool("update_plan", {"plan": []}) - - assert not out.is_error - assert local_forge.context.session.plan == [] - - -def test_update_plan_missing_plan_is_rejected(local_forge) -> None: - out = local_forge.call_tool("update_plan", {}) - - assert out.is_error - assert "plan" in out.content - - -def test_update_plan_invalid_status_is_a_clear_error(local_forge) -> None: - out = local_forge.call_tool( - "update_plan", - {"plan": [{"step": "one", "status": "doing"}]}, - ) - - assert out.is_error - assert "status" in out.content - assert "doing" in out.content - - -def test_update_plan_missing_step_is_a_clear_error(local_forge) -> None: - out = local_forge.call_tool( - "update_plan", - {"plan": [{"status": "pending"}]}, - ) - - assert out.is_error - assert "step" in out.content - - -def test_update_plan_multiple_in_progress_is_rejected(local_forge) -> None: - out = local_forge.call_tool( - "update_plan", - { - "plan": [ - {"step": "one", "status": "in_progress"}, - {"step": "two", "status": "in_progress"}, - ] - }, - ) - - assert out.is_error - assert "in_progress" in out.content - - -def test_update_plan_args_from_dict_rejects_multiple_in_progress() -> None: - with pytest.raises(ValueError, match="in_progress"): - UpdatePlanArgs.from_dict( - { - "plan": [ - {"step": "one", "status": "in_progress"}, - {"step": "two", "status": "in_progress"}, - ] - } - ) - - -def test_update_plan_args_from_dict_rejects_unknown_fields() -> None: - with pytest.raises(ValueError, match="unknown field"): - UpdatePlanArgs.from_dict({"plan": [], "extra": 1}) - - -def test_update_plan_args_from_dict_rejects_non_list_plan() -> None: - with pytest.raises(ValueError): - UpdatePlanArgs.from_dict({"plan": "not-a-list"}) - - -def test_update_plan_args_from_dict_preserves_explanation() -> None: - args = UpdatePlanArgs.from_dict( - {"plan": [{"step": "one", "status": "completed"}], "explanation": "why"} - ) - assert args.explanation == "why" - assert args.plan == [PlanItem(step="one", status=StepStatus.COMPLETED)] diff --git a/tests/python/forge/test_plugin_install.py b/tests/python/forge/test_plugin_install.py deleted file mode 100644 index 68963e292..000000000 --- a/tests/python/forge/test_plugin_install.py +++ /dev/null @@ -1,229 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""`request_plugin_install` authorization and validation.""" - -from __future__ import annotations - -import json -from pathlib import Path - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.discovery.plugin_id import PluginId -from pulsing.forge.discovery.plugin_store import PluginStore -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.session import LocalToolSession - -pytestmark = pytest.mark.forge - - -@pytest.fixture -def codex_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - home = tmp_path / "codex" - home.mkdir() - monkeypatch.setenv("CODEX_HOME", str(home)) - monkeypatch.setenv("FORGE_PLUGIN_DISCOVER_ALL", "1") - return home - - -def _scaffold_marketplace(codex_home: Path) -> str: - agents = codex_home / ".agents" / "plugins" - agents.mkdir(parents=True) - plugin_src = agents / "demo" - manifest_dir = plugin_src / ".codex-plugin" - manifest_dir.mkdir(parents=True) - (manifest_dir / "plugin.json").write_text( - json.dumps( - { - "name": "demo", - "version": "1.0.0", - "description": "Demo plugin", - "mcpServers": ".mcp.json", - } - ), - encoding="utf-8", - ) - (plugin_src / ".mcp.json").write_text( - json.dumps({"mcpServers": {"demo-mcp": {"command": "echo"}}}), - encoding="utf-8", - ) - marketplace_path = agents / "marketplace.json" - marketplace_path.write_text( - json.dumps( - { - "name": "local-dev", - "plugins": [ - { - "name": "demo", - "source": {"source": "local", "path": "./demo"}, - "policy": {"installation": "AVAILABLE"}, - } - ], - } - ), - encoding="utf-8", - ) - return "demo@local-dev" - - -def _ctx(*, approve: bool) -> ToolCallContext: - session = LocalToolSession(plugin_install=lambda _args: approve) - return ToolCallContext(cwd=".", session=session) - - -def test_plugin_install_confirmed_success(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - ctx = _ctx(approve=True) - ctx.tool_catalog.refresh_from_codex() - - out = dispatch_tool( - "request_plugin_install", - { - "tool_type": "plugin", - "action_type": "install", - "tool_id": plugin_id, - "suggest_reason": "Need demo MCP tools", - }, - ctx=ctx, - ) - assert not out.is_error - payload = json.loads(out.content) - assert payload["completed"] is True - assert payload["user_confirmed"] is True - assert payload["tool_id"] == plugin_id - assert payload["tools_registered"] >= 0 - assert PluginStore().is_installed(PluginId.parse(plugin_id)) - - -def test_plugin_install_denied_skips_install(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - ctx = _ctx(approve=False) - ctx.tool_catalog.refresh_from_codex() - - out = dispatch_tool( - "request_plugin_install", - { - "tool_type": "plugin", - "action_type": "install", - "tool_id": plugin_id, - "suggest_reason": "Need demo MCP tools", - }, - ctx=ctx, - ) - assert not out.is_error - payload = json.loads(out.content) - assert payload["user_confirmed"] is False - assert payload["completed"] is True - assert payload["tools_registered"] == 0 - assert not PluginStore().is_installed(PluginId.parse(plugin_id)) - - -def test_plugin_install_unknown_tool_id(codex_home: Path) -> None: - _scaffold_marketplace(codex_home) - ctx = _ctx(approve=True) - ctx.tool_catalog.refresh_from_codex() - - out = dispatch_tool( - "request_plugin_install", - { - "tool_type": "plugin", - "action_type": "install", - "tool_id": "missing@local-dev", - "suggest_reason": "Need it", - }, - ctx=ctx, - ) - assert out.is_error - assert "unknown plugin" in out.content - - -def test_plugin_install_rejects_enable_action(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - ctx = _ctx(approve=True) - ctx.tool_catalog.refresh_from_codex() - - out = dispatch_tool( - "request_plugin_install", - { - "tool_type": "plugin", - "action_type": "enable", - "tool_id": plugin_id, - "suggest_reason": "Need it", - }, - ctx=ctx, - ) - assert out.is_error - assert 'action_type="install"' in out.content - - -def test_plugin_install_requires_suggest_reason(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - ctx = _ctx(approve=True) - ctx.tool_catalog.refresh_from_codex() - - out = dispatch_tool( - "request_plugin_install", - { - "tool_type": "plugin", - "action_type": "install", - "tool_id": plugin_id, - "suggest_reason": " ", - }, - ctx=ctx, - ) - assert out.is_error - assert "non-empty suggest_reason" in out.content - - -def test_plugin_install_accepts_reason_alias(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - ctx = _ctx(approve=True) - ctx.tool_catalog.refresh_from_codex() - - out = dispatch_tool( - "request_plugin_install", - { - "plugin_id": plugin_id, - "reason": "Need demo MCP tools", - }, - ctx=ctx, - ) - assert not out.is_error - payload = json.loads(out.content) - assert payload["user_confirmed"] is True - - -def test_list_available_plugins_returns_marketplace_entry(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - ctx = _ctx(approve=True) - ctx.tool_catalog.refresh_from_codex() - - out = dispatch_tool("list_available_plugins_to_install", {}, ctx=ctx) - assert not out.is_error - payload = json.loads(out.content) - entry = payload["tools"][0] - assert entry["id"] == plugin_id - assert entry["tool_type"] == "plugin" - assert entry["description"] == "Demo plugin" - assert entry["mcp_server_names"] == ["demo-mcp"] - - -def test_list_available_plugins_hides_installed(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - ctx = _ctx(approve=True) - ctx.tool_catalog.refresh_from_codex() - dispatch_tool( - "request_plugin_install", - { - "tool_type": "plugin", - "action_type": "install", - "tool_id": plugin_id, - "suggest_reason": "Need demo MCP tools", - }, - ctx=ctx, - ) - - out = dispatch_tool("list_available_plugins_to_install", {}, ctx=ctx) - assert not out.is_error - payload = json.loads(out.content) - assert payload["tools"] == [] diff --git a/tests/python/forge/test_read.py b/tests/python/forge/test_read.py deleted file mode 100644 index f5783ad26..000000000 --- a/tests/python/forge/test_read.py +++ /dev/null @@ -1,77 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the Forge `Read` tool (Python fallback, `_read` in handlers.py).""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -pytestmark = pytest.mark.forge - - -def test_read_whole_file(local_forge, forge_workspace: Path) -> None: - (forge_workspace / "a.txt").write_text("hello", encoding="utf-8") - out = local_forge.call_tool("Read", {"file_path": "a.txt"}) - assert not out.is_error - assert out.content == "hello" - - -def test_read_missing_file_reports_path(local_forge, forge_workspace: Path) -> None: - out = local_forge.call_tool("Read", {"file_path": "missing.txt"}) - assert out.is_error - assert "missing.txt" in out.content - - -def test_read_rejects_directory(local_forge, forge_workspace: Path) -> None: - (forge_workspace / "sub").mkdir() - out = local_forge.call_tool("Read", {"file_path": "sub"}) - assert out.is_error - assert "directory" in out.content - - -def test_read_rejects_oversized_file(local_forge, forge_workspace: Path) -> None: - (forge_workspace / "big.txt").write_bytes(b"x" * (2 * 1024 * 1024 + 1)) - out = local_forge.call_tool("Read", {"file_path": "big.txt"}) - assert out.is_error - assert "too large" in out.content - assert "offset" in out.content - - -def test_read_rejects_non_utf8(local_forge, forge_workspace: Path) -> None: - (forge_workspace / "bin.dat").write_bytes(bytes([0xFF, 0xFE, 0x00, 0xFF])) - out = local_forge.call_tool("Read", {"file_path": "bin.dat"}) - assert out.is_error - assert "UTF-8" in out.content - - -def test_read_absolute_path_outside_cwd_is_allowed( - local_forge, forge_workspace: Path -) -> None: - """Read has no cwd boundary (unlike Write); it is a general-purpose reader.""" - outside = forge_workspace.parent / "outside.txt" - outside.write_text("elsewhere", encoding="utf-8") - try: - out = local_forge.call_tool("Read", {"file_path": str(outside)}) - assert not out.is_error - assert out.content == "elsewhere" - finally: - outside.unlink(missing_ok=True) - - -def test_read_offset_and_limit_page_through_lines( - local_forge, forge_workspace: Path -) -> None: - (forge_workspace / "lines.txt").write_text("l1\nl2\nl3\nl4\nl5\n", encoding="utf-8") - out = local_forge.call_tool( - "Read", {"file_path": "lines.txt", "offset": 2, "limit": 2} - ) - assert not out.is_error - assert out.content == "l2\nl3\n" - - -def test_read_offset_only_reads_to_end(local_forge, forge_workspace: Path) -> None: - (forge_workspace / "lines.txt").write_text("l1\nl2\nl3\n", encoding="utf-8") - out = local_forge.call_tool("Read", {"file_path": "lines.txt", "offset": 2}) - assert not out.is_error - assert out.content == "l2\nl3\n" diff --git a/tests/python/forge/test_request_user_input.py b/tests/python/forge/test_request_user_input.py deleted file mode 100644 index 90a94bd5a..000000000 --- a/tests/python/forge/test_request_user_input.py +++ /dev/null @@ -1,211 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""`request_user_input` validation, timeout-defaults, and dispatch behavior.""" - -from __future__ import annotations - -import json - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.session import LocalToolSession -from pulsing.forge.session_input import ( - RequestUserInputArgs, - RequestUserInputQuestion, - default_auto_answers, - resolve_user_input, - validate_request_user_input, -) - -pytestmark = pytest.mark.forge - - -def _payload(**overrides): - base = { - "questions": [ - { - "id": "q1", - "header": "Pick", - "question": "Which one?", - "options": [{"label": "A", "description": "first"}, {"label": "B"}], - } - ] - } - base.update(overrides) - return base - - -def test_validate_accepts_minimal_question(): - args = validate_request_user_input({"questions": [{"id": "q1", "question": "Go?"}]}) - assert args.questions[0].id == "q1" - assert args.questions[0].options is None - assert args.auto_resolution_ms is None - - -def test_validate_accepts_full_payload_and_clamps_timeout(): - args = validate_request_user_input(_payload(autoResolutionMs=90_000)) - assert args.questions[0].options[0].label == "A" - assert args.auto_resolution_ms == 90_000 - - -@pytest.mark.parametrize( - "raw", - [ - {"questions": []}, - {"questions": "not-a-list"}, - {"questions": [{"question": "Go?"}]}, - {"questions": [{"id": " ", "question": "Go?"}]}, - {"questions": [{"id": "q1", "question": ""}]}, - { - "questions": [ - {"id": "q1", "question": "Go?"}, - {"id": "q1", "question": "Again?"}, - ] - }, - {"questions": [{"id": "q1", "question": "Go?", "options": []}]}, - {"questions": [{"id": "q1", "question": "Go?", "options": [{"label": " "}]}]}, - {"questions": [{"id": "q1", "question": "Go?"}], "autoResolutionMs": "soon"}, - {"questions": [{"id": "q1", "question": "Go?"}], "autoResolutionMs": [1, 2]}, - ], - ids=[ - "empty-questions", - "questions-not-list", - "missing-id", - "blank-id", - "blank-question-text", - "duplicate-id", - "empty-options-array", - "blank-option-label", - "auto_resolution_ms-not-numeric", - "auto_resolution_ms-wrong-type", - ], -) -def test_validate_rejects_invalid_payloads(raw): - with pytest.raises(ValueError): - validate_request_user_input(raw) - - -def test_validate_clamps_auto_resolution_ms_to_bounds(): - import pulsing.forge.session_input as session_input - - lo = validate_request_user_input(_payload(autoResolutionMs=1)).auto_resolution_ms - hi = validate_request_user_input( - _payload(autoResolutionMs=999_999_999) - ).auto_resolution_ms - assert lo == session_input.MIN_AUTO_RESOLUTION_MS - assert hi == session_input.MAX_AUTO_RESOLUTION_MS - - -def test_default_auto_answers_picks_first_option(): - args = validate_request_user_input(_payload()) - answers = default_auto_answers(args) - assert answers["answers"]["q1"]["answers"] == ["A"] - - -def test_default_auto_answers_empty_string_without_options(): - args = validate_request_user_input({"questions": [{"id": "q1", "question": "Go?"}]}) - answers = default_auto_answers(args) - assert answers["answers"]["q1"]["answers"] == [""] - - -def test_resolve_user_input_prefers_callback_over_timeout(): - args = RequestUserInputArgs( - questions=[RequestUserInputQuestion(id="q1", header="H", question="Go?")] - ) - seen = {} - - def callback(payload): - seen["payload"] = payload - return {"answers": {"q1": {"answers": ["yes"]}}} - - out = resolve_user_input(args, user_input_callback=callback) - assert out["answers"]["q1"]["answers"] == ["yes"] - assert seen["payload"]["questions"][0]["id"] == "q1" - - -def test_resolve_user_input_falls_back_to_defaults_on_timeout( - monkeypatch: pytest.MonkeyPatch, -): - """When autoResolutionMs elapses, resolution must degrade to the first option per question.""" - import pulsing.forge.session_input as session_input - - monkeypatch.setattr(session_input, "MIN_AUTO_RESOLUTION_MS", 1) - args = session_input.validate_request_user_input(_payload(autoResolutionMs=5)) - out = session_input.resolve_user_input( - args, auto_approve=False, user_input_callback=None, prompt_callback=None - ) - assert out["answers"]["q1"]["answers"] == ["A"] - - -def test_resolve_user_input_callback_timeout_falls_back_to_defaults( - monkeypatch: pytest.MonkeyPatch, -): - import time - - import pulsing.forge.session_input as session_input - - monkeypatch.setattr(session_input, "MIN_AUTO_RESOLUTION_MS", 1) - args = session_input.validate_request_user_input(_payload(autoResolutionMs=5)) - - def slow_callback(_payload): - time.sleep(0.05) - return {"answers": {"q1": {"answers": ["late"]}}} - - out = session_input.resolve_user_input(args, user_input_callback=slow_callback) - assert out["answers"]["q1"]["answers"] == ["A"] - - -def test_resolve_user_input_auto_approve_skips_callback(): - args = RequestUserInputArgs( - questions=[RequestUserInputQuestion(id="q1", header="H", question="Go?")] - ) - out = resolve_user_input( - args, - auto_approve=True, - user_input_callback=lambda _: pytest.fail("must not be called"), - ) - assert out["answers"]["q1"]["answers"] == [""] - - -def test_resolve_user_input_raises_without_any_configured_channel(): - args = RequestUserInputArgs( - questions=[RequestUserInputQuestion(id="q1", header="H", question="Go?")] - ) - with pytest.raises(RuntimeError): - resolve_user_input(args) - - -def test_dispatch_reports_invalid_arguments_as_tool_error(tmp_path): - ctx = ToolCallContext(cwd=str(tmp_path), session=LocalToolSession()) - out = dispatch_tool("request_user_input", {"questions": []}, ctx=ctx) - assert out.is_error - assert "question" in out.content.lower() - - -def test_dispatch_reports_malformed_auto_resolution_ms(tmp_path): - ctx = ToolCallContext(cwd=str(tmp_path), session=LocalToolSession()) - out = dispatch_tool( - "request_user_input", - _payload(autoResolutionMs={"bad": True}), - ctx=ctx, - ) - assert out.is_error - assert "autoresolutionms" in out.content.lower() - - -def test_dispatch_without_configured_session_reports_runtime_error(tmp_path): - ctx = ToolCallContext(cwd=str(tmp_path), session=LocalToolSession()) - out = dispatch_tool("request_user_input", _payload(), ctx=ctx) - assert out.is_error - assert "not configured" in out.content.lower() - - -def test_dispatch_returns_session_answers_on_success(tmp_path): - session = LocalToolSession( - user_input=lambda _args: {"answers": {"q1": {"answers": ["A"]}}} - ) - ctx = ToolCallContext(cwd=str(tmp_path), session=session) - out = dispatch_tool("request_user_input", _payload(), ctx=ctx) - assert not out.is_error - assert json.loads(out.content)["answers"]["q1"]["answers"] == ["A"] diff --git a/tests/python/forge/test_scenarios_apply_patch.py b/tests/python/forge/test_scenarios_apply_patch.py deleted file mode 100644 index 7389df757..000000000 --- a/tests/python/forge/test_scenarios_apply_patch.py +++ /dev/null @@ -1,105 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""L3 apply_patch scenario fixtures (codex-apply-patch portable layout).""" - -from __future__ import annotations - -import shutil -import tempfile -from pathlib import Path - -import pytest - -from pulsing.testing.forge_harness import local_runtime - -pytestmark = [pytest.mark.forge, pytest.mark.forge_l3] - -_SCENARIOS = ( - Path(__file__).resolve().parents[3] - / "vendor" - / "codex-rs" - / "apply-patch" - / "tests" - / "fixtures" - / "scenarios" -) - -# Tracked gaps vs codex-apply-patch reference (see testing.zh.md). -KNOWN_GAP_SCENARIOS = frozenset( - { - "011_add_overwrites_existing_file", - "015_failure_after_partial_success_leaves_changes", - } -) - - -def _snapshot_dir(root: Path) -> dict[str, bytes | str]: - out: dict[str, bytes | str] = {} - if not root.is_dir(): - return out - for path in sorted(root.rglob("*")): - if path.name == ".gitattributes": - continue - rel = str(path.relative_to(root)) - if path.is_dir(): - out[rel + "/"] = "dir" - elif path.is_file(): - out[rel] = path.read_bytes() - return out - - -def _run_scenario(scenario: Path, tmp: Path) -> bool: - inp = scenario / "input" - if inp.is_dir(): - for src in inp.rglob("*"): - if src.is_file(): - dst = tmp / src.relative_to(inp) - dst.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(src, dst) - patch = (scenario / "patch.txt").read_text(encoding="utf-8") - rt = local_runtime(tmp) - rt.call_tool("apply_patch", {"patch": patch}) - return _snapshot_dir(scenario / "expected") == _snapshot_dir(tmp) - - -@pytest.fixture(scope="module") -def scenario_dirs() -> list[Path]: - if not _SCENARIOS.is_dir(): - pytest.skip(f"missing scenarios dir: {_SCENARIOS}") - return sorted(p for p in _SCENARIOS.iterdir() if p.is_dir()) - - -def test_l3_apply_patch_scenarios_coverage(scenario_dirs: list[Path]) -> None: - assert len(scenario_dirs) >= 20 - - -@pytest.mark.parametrize( - "scenario", - [ - pytest.param(p, id=p.name) - for p in (sorted(_SCENARIOS.iterdir()) if _SCENARIOS.is_dir() else []) - if p.is_dir() and p.name not in KNOWN_GAP_SCENARIOS - ], -) -def test_l3_apply_patch_scenario(scenario: Path) -> None: - if not _SCENARIOS.is_dir(): - pytest.skip(f"missing scenarios dir: {_SCENARIOS}") - tmp = Path(tempfile.mkdtemp()) - try: - assert _run_scenario(scenario, tmp), scenario.name - finally: - shutil.rmtree(tmp) - - -@pytest.mark.parametrize("name", sorted(KNOWN_GAP_SCENARIOS)) -def test_l3_apply_patch_known_gaps(name: str) -> None: - """Documented gaps — xfail until patch engine catches up.""" - scenario = _SCENARIOS / name - if not scenario.is_dir(): - pytest.skip(f"missing gap scenario {name}") - tmp = Path(tempfile.mkdtemp()) - try: - ok = _run_scenario(scenario, tmp) - finally: - shutil.rmtree(tmp) - if ok: - pytest.fail(f"scenario {name} now passes — remove from KNOWN_GAP_SCENARIOS") diff --git a/tests/python/forge/test_shell_command.py b/tests/python/forge/test_shell_command.py deleted file mode 100644 index 4251d3f2a..000000000 --- a/tests/python/forge/test_shell_command.py +++ /dev/null @@ -1,54 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""shell_command / exec_command sandbox + path boundary tests.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.testing.forge_harness import local_runtime - -pytestmark = pytest.mark.forge - -_RESTRICTED_PATH = "/usr/bin:/bin:/usr/local/bin" - - -def test_shell_command_missing_cmd(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool("shell_command", {}) - assert out.is_error - assert "missing cmd/command" in out.content - - -def test_shell_command_workdir_escape_rejected(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool( - "shell_command", - {"command": "echo hi", "workdir": "../escape"}, - ) - assert out.is_error - assert "outside working directory" in out.content - - -def test_shell_command_restricted_sandbox_limits_path(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace, sandbox_policy="restricted") - out = rt.call_tool( - "shell_command", - {"command": "echo $PATH", "timeout_ms": 5000}, - ) - assert not out.is_error - assert _RESTRICTED_PATH in out.content - assert "restricted env" in out.content - - -def test_shell_command_login_restricted_still_sandboxed(forge_workspace: Path) -> None: - """Login shells may source profile and widen PATH; assert wrapper label, not PATH.""" - rt = local_runtime(forge_workspace, sandbox_policy="restricted") - out = rt.call_tool( - "shell_command", - {"command": "echo ok", "login": True, "timeout_ms": 5000}, - ) - assert not out.is_error - assert "restricted env (env -i + bash -l)" in out.content - assert "sandbox=off" not in out.content diff --git a/tests/python/forge/test_skills.py b/tests/python/forge/test_skills.py deleted file mode 100644 index b326741ec..000000000 --- a/tests/python/forge/test_skills.py +++ /dev/null @@ -1,206 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Security-focused tests for the ``skills.read`` Forge tool. - -Covers path-traversal and symlink-escape attempts against the skills -catalog, in addition to basic read/size-cap behaviour. -""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.extension.skills.catalog import ( - _SKILL_READ_CAP, - list_skills, - read_skill, -) -from pulsing.forge.handlers import dispatch_tool - - -def _ctx(cwd: Path) -> ToolCallContext: - return ToolCallContext(cwd=cwd) - - -def _write_skill(root: Path, skill_name: str, *, name: str, description: str) -> Path: - skill_dir = root / ".agents" / "skills" / skill_name - skill_dir.mkdir(parents=True, exist_ok=True) - skill_md = skill_dir / "SKILL.md" - skill_md.write_text( - f"---\nname: {name}\ndescription: {description}\n---\n# {name}\nbody\n", - encoding="utf-8", - ) - return skill_md - - -def _isolate_skills_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - monkeypatch.setenv("HOME", str(tmp_path)) - monkeypatch.delenv("FORGE_SKILLS_DIRS", raising=False) - - -def test_skills_list_empty_when_skills_dir_missing( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - _isolate_skills_home(monkeypatch, tmp_path) - assert list_skills(tmp_path) == [] - listed = dispatch_tool("skills.list", {}, ctx=_ctx(tmp_path)) - assert not listed.is_error - assert listed.structured == {"skills": []} - - -def test_skills_list_excludes_symlinked_skill_md(tmp_path: Path) -> None: - secret = tmp_path / "secret.txt" - secret.write_text("TOP SECRET CONTENT", encoding="utf-8") - skill_dir = tmp_path / ".agents" / "skills" / "evil-skill" - skill_dir.mkdir(parents=True) - (skill_dir / "SKILL.md").symlink_to(secret) - - listed = dispatch_tool("skills.list", {}, ctx=_ctx(tmp_path)) - assert not listed.is_error - assert "evil-skill" not in listed.content - assert "TOP SECRET" not in listed.content - - -def test_skills_list_excludes_symlinked_skill_directory(tmp_path: Path) -> None: - outside = tmp_path / "outside" - outside.mkdir() - (outside / "SKILL.md").write_text( - "---\nname: outside-skill\ndescription: should not be listed\n---\n", - encoding="utf-8", - ) - skills_root = tmp_path / ".agents" / "skills" - skills_root.mkdir(parents=True) - (skills_root / "linked-skill").symlink_to(outside) - - listed = dispatch_tool("skills.list", {}, ctx=_ctx(tmp_path)) - assert not listed.is_error - assert "outside-skill" not in listed.content - assert "should not be listed" not in listed.content - - -def test_skills_list_skips_invalid_utf8( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - _isolate_skills_home(monkeypatch, tmp_path) - bad = tmp_path / ".agents" / "skills" / "bad-utf8" - bad.mkdir(parents=True) - (bad / "SKILL.md").write_bytes(b"\xff\xfe not utf-8") - good = tmp_path / ".agents" / "skills" / "good-skill" - good.mkdir() - (good / "SKILL.md").write_text( - "---\nname: good-skill\ndescription: valid skill\n---\n", - encoding="utf-8", - ) - - listed = dispatch_tool("skills.list", {}, ctx=_ctx(tmp_path)) - assert not listed.is_error - assert "good-skill" in listed.content - assert "bad-utf8" not in listed.content - - -def test_skills_read_by_name_and_path(tmp_path: Path) -> None: - _write_skill( - tmp_path, "demo-skill", name="demo-skill", description="Demo skill for tests" - ) - ctx = _ctx(tmp_path) - - read = dispatch_tool("skills.read", {"name": "demo-skill"}, ctx=ctx) - assert not read.is_error - assert "Demo skill for tests" in read.content - - read_by_path = dispatch_tool( - "skills.read", {"path": "demo-skill/SKILL.md"}, ctx=ctx - ) - assert not read_by_path.is_error - assert "Demo skill for tests" in read_by_path.content - - -def test_skills_read_missing_name_or_path_errors(tmp_path: Path) -> None: - out = dispatch_tool("skills.read", {}, ctx=_ctx(tmp_path)) - assert out.is_error - - -def test_skills_read_unknown_skill_errors_without_leaking_paths(tmp_path: Path) -> None: - out = dispatch_tool("skills.read", {"name": "does-not-exist"}, ctx=_ctx(tmp_path)) - assert out.is_error - assert str(tmp_path) not in out.content - - -@pytest.mark.parametrize( - "traversal_path", - [ - "../../../etc/passwd", - "demo-skill/../../../etc/passwd", - "/etc/passwd", - ], -) -def test_skills_read_rejects_path_traversal( - tmp_path: Path, traversal_path: str -) -> None: - _write_skill(tmp_path, "demo-skill", name="demo-skill", description="Demo skill") - ctx = _ctx(tmp_path) - - out = dispatch_tool("skills.read", {"path": traversal_path}, ctx=ctx) - assert out.is_error - assert "root:" not in out.content - assert str(tmp_path) not in out.content - - -def test_skills_read_rejects_symlinked_skill_file(tmp_path: Path) -> None: - secret = tmp_path / "secret.txt" - secret.write_text("TOP SECRET CONTENT", encoding="utf-8") - - skill_dir = tmp_path / ".agents" / "skills" / "evil-skill" - skill_dir.mkdir(parents=True) - (skill_dir / "SKILL.md").symlink_to(secret) - - ctx = _ctx(tmp_path) - out = dispatch_tool("skills.read", {"name": "evil-skill"}, ctx=ctx) - assert out.is_error - assert "TOP SECRET" not in out.content - - out_by_path = dispatch_tool("skills.read", {"path": "evil-skill/SKILL.md"}, ctx=ctx) - assert out_by_path.is_error - assert "TOP SECRET" not in out_by_path.content - - -def test_skills_read_rejects_symlinked_skill_directory(tmp_path: Path) -> None: - outside = tmp_path / "outside" - outside.mkdir() - (outside / "SKILL.md").write_text( - "---\nname: outside-skill\ndescription: should not be reachable\n---\n", - encoding="utf-8", - ) - - skills_root = tmp_path / ".agents" / "skills" - skills_root.mkdir(parents=True) - (skills_root / "linked-skill").symlink_to(outside) - - ctx = _ctx(tmp_path) - out = dispatch_tool("skills.read", {"name": "outside-skill"}, ctx=ctx) - assert out.is_error - assert "should not be reachable" not in out.content - - -def test_read_skill_direct_call_rejects_escape(tmp_path: Path) -> None: - secret = tmp_path / "secret.txt" - secret.write_text("TOP SECRET CONTENT", encoding="utf-8") - skill_dir = tmp_path / ".agents" / "skills" / "evil-skill" - skill_dir.mkdir(parents=True) - (skill_dir / "SKILL.md").symlink_to(secret) - - with pytest.raises(FileNotFoundError): - read_skill(cwd=tmp_path, name="evil-skill") - - -def test_skills_read_enforces_size_cap(tmp_path: Path) -> None: - skill_md = _write_skill( - tmp_path, "big-skill", name="big-skill", description="Big skill" - ) - skill_md.write_text("x" * (_SKILL_READ_CAP + 1), encoding="utf-8") - - out = dispatch_tool("skills.read", {"name": "big-skill"}, ctx=_ctx(tmp_path)) - assert out.is_error - assert "too large" in out.content diff --git a/tests/python/forge/test_tool_calls.py b/tests/python/forge/test_tool_calls.py deleted file mode 100644 index 4952faaab..000000000 --- a/tests/python/forge/test_tool_calls.py +++ /dev/null @@ -1,129 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for pulsing.forge.tool_calls.""" - -from __future__ import annotations - -import pytest - -from pulsing.forge.result import ToolResult -from pulsing.forge.tool_calls import ( - OpenAIToolCallAccumulator, - anthropic_tool_result_block, - extract_tool_calls, - forge_tool_definitions, - openai_tool_message, - parse_tool_arguments, - to_anthropic_tools, - to_openai_tools, -) - -pytestmark = pytest.mark.forge - - -def test_parse_tool_arguments_json_string() -> None: - assert parse_tool_arguments('{"a": 1}') == {"a": 1} - - -def test_parse_tool_arguments_invalid_json() -> None: - assert parse_tool_arguments("{bad") == {} - - -def test_extract_openai_tool_calls() -> None: - msg = { - "role": "assistant", - "tool_calls": [ - { - "id": "call_1", - "type": "function", - "function": { - "name": "Glob", - "arguments": '{"pattern": "*.md"}', - }, - } - ], - } - calls = extract_tool_calls(msg, provider="openai") - assert len(calls) == 1 - assert calls[0].id == "call_1" - assert calls[0].name == "Glob" - assert calls[0].arguments == {"pattern": "*.md"} - - -def test_extract_anthropic_tool_calls() -> None: - msg = { - "role": "assistant", - "content": [ - {"type": "text", "text": "checking"}, - { - "type": "tool_use", - "id": "tu_1", - "name": "Read", - "input": {"file_path": "a.txt"}, - }, - ], - } - calls = extract_tool_calls(msg, provider="anthropic") - assert len(calls) == 1 - assert calls[0].name == "Read" - assert calls[0].arguments["file_path"] == "a.txt" - - -def test_openai_tool_message_and_anthropic_block() -> None: - result = ToolResult(content="ok", is_error=False) - om = openai_tool_message("id1", result) - assert om["role"] == "tool" - assert om["tool_call_id"] == "id1" - - block = anthropic_tool_result_block("id1", ToolResult(content="err", is_error=True)) - assert block["type"] == "tool_result" - assert block["is_error"] is True - - -def test_schema_conversion_roundtrip() -> None: - anthropic = forge_tool_definitions(["Glob", "Read"]) - openai = to_openai_tools(anthropic) - names = {t["function"]["name"] for t in openai} - assert names == {"Glob", "Read"} - back = to_anthropic_tools(openai) - assert {t["name"] for t in back} == {"Glob", "Read"} - assert "input_schema" in back[0] - - -def test_openai_stream_accumulator() -> None: - acc = OpenAIToolCallAccumulator() - acc.feed_chunk( - { - "choices": [ - { - "delta": { - "tool_calls": [ - { - "index": 0, - "id": "c1", - "function": {"name": "Glob", "arguments": '{"pat'}, - } - ] - } - } - ] - } - ) - acc.feed_chunk( - { - "choices": [ - { - "delta": { - "tool_calls": [ - { - "index": 0, - "function": {"arguments": 'tern": "*.py"}'}, - } - ] - } - } - ] - } - ) - calls = acc.finish() - assert calls[0].name == "Glob" - assert calls[0].arguments == {"pattern": "*.py"} diff --git a/tests/python/forge/test_tool_search.py b/tests/python/forge/test_tool_search.py deleted file mode 100644 index fd3772b80..000000000 --- a/tests/python/forge/test_tool_search.py +++ /dev/null @@ -1,122 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Dedicated tests for tool_search (BM25, limits, handler parity with Rust).""" - -from __future__ import annotations - -import json - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.discovery.bm25 import bm25_scores -from pulsing.forge.discovery.catalog import ToolCatalog -from pulsing.forge.discovery.entries import ( - TOOL_SEARCH_DEFAULT_LIMIT, - TOOL_SEARCH_MAX_LIMIT, - TOOL_SEARCH_MAX_QUERY_CHARS, - DeferredToolEntry, - normalize_tool_search_limit, -) -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.session import LocalToolSession - - -def _catalog(*names: tuple[str, str]) -> ToolCatalog: - catalog = ToolCatalog() - for name, desc in names: - catalog.register_deferred(DeferredToolEntry.from_function(name, desc)) - return catalog - - -def test_bm25_ranks_github_higher() -> None: - docs = ["filesystem read write grep", "github pull request mcp server"] - scores = bm25_scores("github mcp", docs) - assert scores[1] > scores[0] - - -def test_bm25_empty_query_scores_zero() -> None: - docs = ["github mcp server", "filesystem tools"] - assert bm25_scores("", docs) == [0.0, 0.0] - assert bm25_scores(" ", docs) == [0.0, 0.0] - - -def test_bm25_punctuation_only_query() -> None: - docs = ["github mcp server"] - assert bm25_scores("!!! ??? ---", docs) == [0.0] - - -def test_bm25_no_documents() -> None: - assert bm25_scores("github", []) == [] - - -def test_normalize_tool_search_limit() -> None: - assert normalize_tool_search_limit(None) == TOOL_SEARCH_DEFAULT_LIMIT - assert normalize_tool_search_limit(0) == TOOL_SEARCH_DEFAULT_LIMIT - assert normalize_tool_search_limit(-5) == TOOL_SEARCH_DEFAULT_LIMIT - assert normalize_tool_search_limit("bad") == TOOL_SEARCH_DEFAULT_LIMIT - assert normalize_tool_search_limit(3) == 3 - assert normalize_tool_search_limit(999_999) == TOOL_SEARCH_MAX_LIMIT - - -def test_catalog_search_respects_limit() -> None: - catalog = _catalog( - ("alpha", "alpha tool"), - ("beta", "beta tool"), - ("gamma", "gamma tool"), - ) - hits = catalog.search("tool", limit=2) - assert len(hits) == 2 - - -def test_handler_rejects_empty_query() -> None: - ctx = ToolCallContext( - cwd=".", session=LocalToolSession(), tool_catalog=ToolCatalog() - ) - for args in [{"query": ""}, {"query": " "}, {}]: - out = dispatch_tool("tool_search", args, ctx=ctx) - assert out.is_error - assert out.content == "tool_search requires non-empty query" - - -def test_handler_returns_loadable_json() -> None: - catalog = _catalog(("github_mcp", "GitHub MCP integration")) - ctx = ToolCallContext(cwd=".", session=LocalToolSession(), tool_catalog=catalog) - out = dispatch_tool("tool_search", {"query": "github mcp"}, ctx=ctx) - assert not out.is_error - payload = json.loads(out.content) - tool = payload["tools"][0] - assert tool["type"] == "function" - assert tool["name"] == "github_mcp" - assert tool["defer_loading"] is True - - -@pytest.mark.parametrize("limit", [0, -5]) -def test_handler_limit_non_positive_uses_default(limit: int) -> None: - catalog = _catalog( - ("github_mcp", "GitHub integration"), - ("github_issues", "GitHub integration"), - ("github_actions", "GitHub integration"), - ) - ctx = ToolCallContext(cwd=".", session=LocalToolSession(), tool_catalog=catalog) - out = dispatch_tool("tool_search", {"query": "github", "limit": limit}, ctx=ctx) - assert not out.is_error - assert len(json.loads(out.content)["tools"]) == 3 - - -def test_handler_huge_limit_clamped() -> None: - catalog = _catalog(("github_mcp", "GitHub MCP integration")) - ctx = ToolCallContext(cwd=".", session=LocalToolSession(), tool_catalog=catalog) - out = dispatch_tool( - "tool_search", {"query": "github", "limit": 999_999_999}, ctx=ctx - ) - assert not out.is_error - assert len(json.loads(out.content)["tools"]) == 1 - - -def test_handler_truncates_overlong_query() -> None: - catalog = _catalog(("github_mcp", "GitHub MCP integration")) - ctx = ToolCallContext(cwd=".", session=LocalToolSession(), tool_catalog=catalog) - query = "github " + "x" * TOOL_SEARCH_MAX_QUERY_CHARS - out = dispatch_tool("tool_search", {"query": query}, ctx=ctx) - assert not out.is_error - assert len(json.loads(out.content)["tools"]) == 1 diff --git a/tests/python/forge/test_view_image.py b/tests/python/forge/test_view_image.py deleted file mode 100644 index 98028996b..000000000 --- a/tests/python/forge/test_view_image.py +++ /dev/null @@ -1,144 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""view_image: attach images, path escape, format/size limits.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE -from pulsing.testing.forge_harness import _MIN_PNG, local_runtime - -pytestmark = pytest.mark.forge - -_VIEW_IMAGE_CAP = 8 * 1024 * 1024 - - -def _png(workspace: Path, name: str = "x.png") -> Path: - path = workspace / name - path.write_bytes(_MIN_PNG) - return path - - -def test_view_image_attaches_structured_output(forge_workspace: Path) -> None: - p = _png(forge_workspace) - rt = local_runtime(forge_workspace) - out = rt.call_tool("view_image", {"path": str(p), "detail": "high"}) - assert not out.is_error - assert out.structured is not None - items = out.structured.get("content_items") or [] - assert items and items[0]["type"] == "input_image" - assert str(items[0]["image_url"]).startswith("data:image/png;base64,") - assert items[0]["detail"] == "high" - - -def test_view_image_original_skips_resize(forge_workspace: Path) -> None: - p = _png(forge_workspace) - rt = local_runtime(forge_workspace) - out = rt.call_tool("view_image", {"path": str(p), "detail": "original"}) - assert not out.is_error - assert out.structured is not None - assert out.structured["bytes"] == len(_MIN_PNG) - - -def test_view_image_rejects_relative_escape(forge_workspace: Path) -> None: - workspace = forge_workspace / "inner" - workspace.mkdir() - outside = forge_workspace / "escape.png" - outside.write_bytes(_MIN_PNG) - rt = local_runtime(workspace) - out = rt.call_tool("view_image", {"path": "../escape.png"}) - assert out.is_error - assert "outside working directory" in out.content - - -def test_view_image_rejects_absolute_path_outside_cwd(forge_workspace: Path) -> None: - workspace = forge_workspace / "inner" - workspace.mkdir() - outside = forge_workspace / "outside.png" - outside.write_bytes(_MIN_PNG) - rt = local_runtime(workspace) - out = rt.call_tool("view_image", {"path": str(outside)}) - assert out.is_error - assert "outside working directory" in out.content - - -def test_view_image_allows_absolute_path_inside_cwd(forge_workspace: Path) -> None: - p = _png(forge_workspace) - rt = local_runtime(forge_workspace) - out = rt.call_tool("view_image", {"path": str(p)}) - assert not out.is_error - - -def test_view_image_rejects_invalid_detail(forge_workspace: Path) -> None: - _png(forge_workspace) - rt = local_runtime(forge_workspace) - out = rt.call_tool("view_image", {"path": "x.png", "detail": "low"}) - assert out.is_error - assert "view_image.detail only supports" in out.content - - -def test_view_image_rejects_directory(forge_workspace: Path) -> None: - (forge_workspace / "subdir").mkdir() - rt = local_runtime(forge_workspace) - out = rt.call_tool("view_image", {"path": "subdir"}) - assert out.is_error - assert "is not a file" in out.content - - -def test_view_image_rejects_oversized_file(forge_workspace: Path) -> None: - big = forge_workspace / "big.png" - big.write_bytes(_MIN_PNG + b"\x00" * (_VIEW_IMAGE_CAP - len(_MIN_PNG) + 1)) - rt = local_runtime(forge_workspace) - out = rt.call_tool("view_image", {"path": str(big)}) - assert out.is_error - assert "Image too large for view_image" in out.content - assert str(_VIEW_IMAGE_CAP) in out.content - - -def test_view_image_rejects_unrecognized_format(forge_workspace: Path) -> None: - (forge_workspace / "x.bin").write_bytes(b"not an image") - rt = local_runtime(forge_workspace) - out = rt.call_tool("view_image", {"path": "x.bin"}) - assert out.is_error - assert "not a recognized image format" in out.content - - -def test_view_image_sniffs_mime_not_extension(forge_workspace: Path) -> None: - """JPEG bytes with a .png name must still attach as image/jpeg.""" - jpeg = bytes.fromhex( - "ffd8ffe000104a46494600010100000100010000ffdb004300080606070605080707" - "070909080a0c140d0c0b0b0c1912130f141d1a1f1e1d1a1c1c20242e2720222c" - "231c1c2837292c30313434341f27393d38323c2e333432ffdb0043010909090c0b" - "0c180d0d1832211c213232323232323232323232323232323232323232323232" - "323232323232323232323232323232323232ffc000110800010001030111000211" - "00031101ffc4001500010100000000000000000000000000000008ffc400141001" - "00000000000000000000000000000000ffda000c03010002110311003f00aa" - "ffd9" - ) - path = forge_workspace / "fake.png" - path.write_bytes(jpeg) - rt = local_runtime(forge_workspace) - out = rt.call_tool("view_image", {"path": str(path), "detail": "original"}) - assert not out.is_error - items = out.structured["content_items"] - assert str(items[0]["image_url"]).startswith("data:image/jpeg;base64,") - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_view_image_rust_rejects_escape(forge_workspace: Path) -> None: - from pulsing.forge.hybrid_runtime import HybridForgeRuntime - - workspace = forge_workspace / "inner" - workspace.mkdir() - outside = forge_workspace / "escape.png" - outside.write_bytes(_MIN_PNG) - rt = HybridForgeRuntime.create(cwd=str(workspace), auto_approve=True) - out = rt.call_tool("view_image", {"path": "../escape.png"}) - assert out.is_error - if "outside working directory" not in out.content: - pytest.skip( - "installed pulsing-forge lacks view_image cwd guard; run maturin develop" - ) - assert "outside working directory" in out.content diff --git a/tests/python/forge/test_wait.py b/tests/python/forge/test_wait.py deleted file mode 100644 index 758aed1c9..000000000 --- a/tests/python/forge/test_wait.py +++ /dev/null @@ -1,103 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the ``wait`` Forge tool (Codex code_mode exec/wait pairing).""" - -from __future__ import annotations - -import pytest - -from pulsing.forge.code_mode.protocol import WaitArgs - -pytestmark = pytest.mark.forge - - -def test_wait_returns_result_for_completed_cell(local_forge) -> None: - exec_out = local_forge.call_tool("exec", {"source": "text('hi')"}) - cell_id = exec_out.structured["cell_id"] - - out = local_forge.call_tool("wait", {"cell_id": cell_id}) - - assert not out.is_error - assert out.structured["kind"] == "result" - assert out.structured["content_items"][0]["text"] == "hi" - - -def test_wait_unknown_cell_id_is_a_clear_error(local_forge) -> None: - out = local_forge.call_tool("wait", {"cell_id": "cell-does-not-exist"}) - - assert out.is_error - assert "cell-does-not-exist" in out.content - - -def test_wait_missing_cell_id_is_rejected(local_forge) -> None: - out = local_forge.call_tool("wait", {}) - - assert out.is_error - assert "cell_id" in out.content - - -def test_wait_terminate_on_finished_cell_does_not_clobber_result(local_forge) -> None: - exec_out = local_forge.call_tool("exec", {"source": "text('done')"}) - cell_id = exec_out.structured["cell_id"] - - out = local_forge.call_tool("wait", {"cell_id": cell_id, "terminate": True}) - - assert not out.is_error - assert out.structured["kind"] == "result" - assert out.structured["content_items"][0]["text"] == "done" - - -def test_wait_terminate_on_yielded_cell_marks_terminated(local_forge) -> None: - exec_out = local_forge.call_tool("exec", {"source": "yield_control()"}) - cell_id = exec_out.structured["cell_id"] - assert exec_out.structured["kind"] == "yielded" - - out = local_forge.call_tool("wait", {"cell_id": cell_id, "terminate": True}) - - assert not out.is_error - assert out.structured["kind"] == "terminated" - - -def test_wait_max_tokens_trims_content(local_forge) -> None: - exec_out = local_forge.call_tool("exec", {"source": "text('hello world')"}) - cell_id = exec_out.structured["cell_id"] - - out = local_forge.call_tool("wait", {"cell_id": cell_id, "max_tokens": 5}) - - assert not out.is_error - assert out.structured["content_items"][0]["text"] == "hello" - - -def test_wait_args_rejects_negative_yield_time_ms() -> None: - with pytest.raises(ValueError): - WaitArgs.from_dict({"cell_id": "x", "yield_time_ms": -1}) - - -def test_wait_args_rejects_non_positive_max_tokens() -> None: - with pytest.raises(ValueError): - WaitArgs.from_dict({"cell_id": "x", "max_tokens": 0}) - - -def test_wait_args_preserves_explicit_zero_yield_time_ms() -> None: - args = WaitArgs.from_dict({"cell_id": "x", "yield_time_ms": 0}) - assert args.yield_time_ms == 0 - - -def test_wait_invalid_max_tokens_type_is_a_clean_tool_error(local_forge) -> None: - out = local_forge.call_tool("wait", {"cell_id": "x", "max_tokens": "not-a-number"}) - - assert out.is_error - assert "max_tokens" in out.content or "invalid literal" in out.content - - -def test_wait_on_exec_error_without_output_is_structured_not_tool_error( - local_forge, -) -> None: - exec_out = local_forge.call_tool("exec", {"source": "1 / 0"}) - cell_id = exec_out.structured["cell_id"] - - out = local_forge.call_tool("wait", {"cell_id": cell_id}) - - assert not out.is_error - assert out.structured["kind"] == "result" - assert out.structured["error_text"].startswith("ZeroDivisionError:") - assert "Error:" in out.content diff --git a/tests/python/forge/test_web_run.py b/tests/python/forge/test_web_run.py deleted file mode 100644 index f9e428b00..000000000 --- a/tests/python/forge/test_web_run.py +++ /dev/null @@ -1,315 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the ``web.run`` Forge tool (open/find/search + SSRF guards). - -Codex ships no open-source implementation of ``web.run`` to compare against -(it's a hosted ChatGPT product feature); these tests instead pin down Forge's -own contract: allowlisted ``open`` fetches, and no request is ever made to a -non-public address regardless of configuration. -""" - -from __future__ import annotations - -from typing import Any - -import ipaddress - -import pytest - -from pulsing.forge.extension.web_run import handlers as web_run - -pytestmark = pytest.mark.forge - -_PUBLIC_IP = ipaddress.ip_address( - "93.184.216.34" -) # example.com A record (IANA reserved doc range) - - -@pytest.fixture -def mock_public_dns(monkeypatch: pytest.MonkeyPatch) -> None: - """Stub DNS so fetch tests never hit the network or local resolver quirks.""" - - def _public_ips(host: str) -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]: - try: - ip = ipaddress.ip_address(host) - except ValueError: - return [_PUBLIC_IP] - return [ip] - - monkeypatch.setattr(web_run, "_resolve_ips", _public_ips) - - -class _FakeResponse: - def __init__(self, body: bytes, url: str = "") -> None: - self._body = body - self.url = url - - def read(self, n: int) -> bytes: - return self._body[:n] - - def __enter__(self) -> "_FakeResponse": - return self - - def __exit__(self, *exc_info: object) -> bool: - return False - - -class _FakeOpener: - def __init__(self, body: bytes = b"", exc: Exception | None = None) -> None: - self._body = body - self._exc = exc - - def open(self, req: Any, timeout: float | None = None) -> _FakeResponse: - if self._exc is not None: - raise self._exc - return _FakeResponse(self._body) - - -@pytest.fixture(autouse=True) -def _clean_web_env(monkeypatch: pytest.MonkeyPatch) -> None: - for var in ("FORGE_WEB_ALLOW", "PULSING_CRAFT_FETCH_ALLOW", "FORGE_WEB_SEARCH"): - monkeypatch.delenv(var, raising=False) - - -def test_open_fetches_allowlisted_host( - monkeypatch: pytest.MonkeyPatch, local_forge, mock_public_dns -) -> None: - monkeypatch.setenv("FORGE_WEB_ALLOW", "example.com") - monkeypatch.setattr( - web_run, "build_opener", lambda *_: _FakeOpener(body=b"hello world") - ) - - out = local_forge.call_tool( - "web.run", {"open": [{"url": "https://example.com/page"}]} - ) - - assert not out.is_error - assert out.content == "hello world" - - -def test_open_without_allowlist_is_disabled_by_default(local_forge) -> None: - out = local_forge.call_tool( - "web.run", {"open": [{"url": "https://example.com/page"}]} - ) - - assert out.is_error - assert "FORGE_WEB_ALLOW" in out.content - - -def test_open_rejects_host_not_in_allowlist( - monkeypatch: pytest.MonkeyPatch, local_forge -) -> None: - monkeypatch.setenv("FORGE_WEB_ALLOW", "example.com") - - out = local_forge.call_tool( - "web.run", {"open": [{"url": "https://evil.example.org/x"}]} - ) - - assert out.is_error - assert "evil.example.org" in out.content - assert "is not in FORGE_WEB_ALLOW" in out.content - - -def test_allowlist_wildcard_subdomain(monkeypatch: pytest.MonkeyPatch) -> None: - allowed = {"*.example.com"} - assert web_run._host_matches_allowlist("api.example.com", allowed) - assert not web_run._host_matches_allowlist("example.com", allowed) - assert not web_run._host_matches_allowlist("evil.example.org", allowed) - - -def test_allowlist_wildcard_apex_and_subdomains( - monkeypatch: pytest.MonkeyPatch, -) -> None: - allowed = {"**.example.com"} - assert web_run._host_matches_allowlist("example.com", allowed) - assert web_run._host_matches_allowlist("api.example.com", allowed) - - -def test_open_blocks_cgnat_ip_even_if_allowlisted() -> None: - error = web_run._check_url_allowed("http://100.64.0.1/", {"100.64.0.1"}) - assert error is not None - assert "non-public" in error or "SSRF" in error - - -def test_open_accepts_flat_url_arg( - monkeypatch: pytest.MonkeyPatch, local_forge, mock_public_dns -) -> None: - monkeypatch.setenv("FORGE_WEB_ALLOW", "example.com") - monkeypatch.setattr( - web_run, "build_opener", lambda *_: _FakeOpener(body=b"flat ok") - ) - - out = local_forge.call_tool("web.run", {"url": "https://example.com/flat"}) - - assert not out.is_error - assert out.content == "flat ok" - - -def test_redirect_blocked_reports_clearly( - monkeypatch: pytest.MonkeyPatch, local_forge, mock_public_dns -) -> None: - from urllib.error import HTTPError - - monkeypatch.setenv("FORGE_WEB_ALLOW", "example.com") - err = HTTPError( - "http://169.254.169.254/", - 302, - "redirect blocked: host '169.254.169.254' is a non-public address", - {}, - None, - ) - monkeypatch.setattr(web_run, "build_opener", lambda *_: _FakeOpener(exc=err)) - - out = local_forge.call_tool( - "web.run", {"open": [{"url": "https://example.com/redirect"}]} - ) - - assert out.is_error - assert "redirect blocked" in out.content - assert "non-public" in out.content - - -def test_open_rejects_non_http_scheme(local_forge) -> None: - out = local_forge.call_tool("web.run", {"open": [{"url": "file:///etc/passwd"}]}) - - assert out.is_error - assert "only http/https" in out.content - - -@pytest.mark.parametrize( - "url", - [ - "http://169.254.169.254/latest/meta-data/", # cloud metadata endpoint - "http://127.0.0.1:8080/", - "http://0.0.0.0/", - "http://[::1]/", - ], -) -def test_open_blocks_ssrf_to_non_public_ip_even_if_allowlisted( - monkeypatch: pytest.MonkeyPatch, url: str -) -> None: - host = web_run.urlparse(url).hostname or "" - monkeypatch.setenv("FORGE_WEB_ALLOW", host) - - error = web_run._check_url_allowed(url, {host}) - - assert error is not None - assert "non-public" in error or "SSRF" in error - - -def test_check_url_allowed_accepts_public_looking_ip( - monkeypatch: pytest.MonkeyPatch, -) -> None: - # 8.8.8.8 is a real public IP (Google DNS); used only to exercise the - # "not blocked" branch of the IP classifier without a real network call. - error = web_run._check_url_allowed("http://8.8.8.8/", {"8.8.8.8"}) - assert error is None - - -def test_redirect_to_disallowed_host_is_blocked( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setattr(web_run, "_resolve_ips", lambda host: []) - handler = web_run._AllowlistRedirectHandler({"example.com"}) - - with pytest.raises(web_run.HTTPError): - handler.redirect_request( - None, None, 302, "Found", {}, "http://169.254.169.254/latest/meta-data/" - ) - - -def test_open_reports_timeout_clearly( - monkeypatch: pytest.MonkeyPatch, local_forge, mock_public_dns -) -> None: - monkeypatch.setenv("FORGE_WEB_ALLOW", "example.com") - monkeypatch.setattr( - web_run, "build_opener", lambda *_: _FakeOpener(exc=TimeoutError()) - ) - - out = local_forge.call_tool( - "web.run", {"open": [{"url": "https://example.com/slow"}]} - ) - - assert out.is_error - assert "timed out" in out.content - - -def test_open_reports_http_error_clearly( - monkeypatch: pytest.MonkeyPatch, local_forge, mock_public_dns -) -> None: - from urllib.error import HTTPError - - monkeypatch.setenv("FORGE_WEB_ALLOW", "example.com") - err = HTTPError("https://example.com/404", 404, "Not Found", {}, None) - monkeypatch.setattr(web_run, "build_opener", lambda *_: _FakeOpener(exc=err)) - - out = local_forge.call_tool( - "web.run", {"open": [{"url": "https://example.com/404"}]} - ) - - assert out.is_error - assert "404" in out.content - - -def test_open_response_over_cap_is_rejected( - monkeypatch: pytest.MonkeyPatch, local_forge, mock_public_dns -) -> None: - monkeypatch.setenv("FORGE_WEB_ALLOW", "example.com") - monkeypatch.setattr(web_run, "_FETCH_CAP", 4) - monkeypatch.setattr( - web_run, "build_opener", lambda *_: _FakeOpener(body=b"way too long") - ) - - out = local_forge.call_tool( - "web.run", {"open": [{"url": "https://example.com/big"}]} - ) - - assert out.is_error - assert "cap" in out.content - - -def test_search_query_disabled_by_default(local_forge) -> None: - out = local_forge.call_tool("web.run", {"search_query": "pulsing forge"}) - - assert out.is_error - assert "FORGE_WEB_SEARCH" in out.content - - -def test_find_op_reports_unsupported(local_forge) -> None: - out = local_forge.call_tool( - "web.run", {"find": [{"ref_id": "turn0", "pattern": "x"}]} - ) - - assert out.is_error - assert "unsupported_in_mvp" in out.content - - -def test_open_op_must_be_object(local_forge) -> None: - out = local_forge.call_tool("web.run", {"open": ["not-an-object"]}) - - assert out.is_error - assert "object" in out.content - - -def test_open_rejects_localhost_hostname() -> None: - error = web_run._check_url_allowed("http://localhost/", {"localhost"}) - assert error is not None - assert "SSRF" in error - - -def test_open_rejects_url_with_credentials() -> None: - error = web_run._check_url_allowed("http://user:pass@example.com/", {"example.com"}) - assert error is not None - assert "credentials" in error - - -def test_open_rejects_empty_url(monkeypatch: pytest.MonkeyPatch, local_forge) -> None: - monkeypatch.setenv("FORGE_WEB_ALLOW", "example.com") - out = local_forge.call_tool("web.run", {"open": [{"url": " "}]}) - assert out.is_error - assert "missing" in out.content - - -def test_empty_command_is_rejected(local_forge) -> None: - out = local_forge.call_tool("web.run", {}) - - assert out.is_error diff --git a/tests/python/forge/test_web_search.py b/tests/python/forge/test_web_search.py deleted file mode 100644 index 067286b43..000000000 --- a/tests/python/forge/test_web_search.py +++ /dev/null @@ -1,142 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the hosted ``web_search`` Forge tool. - -Codex registers web_search as a Responses API provider tool (type=web_search), -not a sandbox function. These tests pin Forge's contract: argument validation, -hosted deferral without a provider hook, and clear auth failures when Craft -wires a hook but credentials are missing. -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Any - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.extension.web_search import handlers as web_search -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.session import LocalToolSession - -pytestmark = pytest.mark.forge - - -def _ctx(tmp_path, *, session: Any = None) -> ToolCallContext: - return ToolCallContext(cwd=tmp_path, session=session) - - -@dataclass -class _HookSession(LocalToolSession): - hook: Any = None - calls: list[dict[str, Any]] = field(default_factory=list) - - def hosted_web_search(self, arguments: dict[str, Any]) -> Any: - self.calls.append(dict(arguments)) - if self.hook is None: - return None - return self.hook(arguments) - - -def test_empty_query_rejected(tmp_path) -> None: - out = dispatch_tool("web_search", {}, ctx=_ctx(tmp_path)) - assert out.is_error - assert "query" in out.content - assert "queries" in out.content - - -def test_whitespace_only_query_rejected(tmp_path) -> None: - out = dispatch_tool("web_search", {"query": " "}, ctx=_ctx(tmp_path)) - assert out.is_error - - -def test_hosted_deferred_without_hook(tmp_path) -> None: - out = dispatch_tool("web_search", {"query": "pulsing actor"}, ctx=_ctx(tmp_path)) - assert not out.is_error - assert out.structured is not None - assert out.structured["kind"] == "hosted_web_search" - assert out.structured["status"] == "deferred" - assert out.structured["reason"] == "provider_not_configured" - assert out.structured["arguments"] == {"query": "pulsing actor"} - assert "Responses API" in out.content - assert "web.run" in out.content - - -def test_hosted_deferred_accepts_queries_list(tmp_path) -> None: - out = dispatch_tool( - "web_search", - {"queries": ["alpha", " beta "]}, - ctx=_ctx(tmp_path), - ) - assert not out.is_error - assert out.structured is not None - assert out.structured["arguments"] == {"queries": ["alpha", "beta"]} - - -def test_hook_success_returns_structured(tmp_path) -> None: - session = _HookSession( - hook=lambda args: { - "status": "ok", - "results": [{"title": "hit", "url": "https://x"}], - }, - ) - out = dispatch_tool( - "web_search", {"query": "test"}, ctx=_ctx(tmp_path, session=session) - ) - assert not out.is_error - assert out.structured is not None - assert out.structured["status"] == "ok" - assert session.calls == [{"query": "test"}] - - -def test_hook_none_falls_back_to_deferred(tmp_path) -> None: - session = _HookSession(hook=lambda _args: None) - out = dispatch_tool( - "web_search", {"query": "test"}, ctx=_ctx(tmp_path, session=session) - ) - assert not out.is_error - assert out.structured is not None - assert out.structured["status"] == "deferred" - - -def test_hook_auth_exception_clear_message(tmp_path) -> None: - session = _HookSession( - hook=lambda _args: (_ for _ in ()).throw(RuntimeError("missing API key")), - ) - out = dispatch_tool( - "web_search", {"query": "test"}, ctx=_ctx(tmp_path, session=session) - ) - assert out.is_error - assert "provider auth missing" in out.content - assert "OPENAI_API_KEY" in out.content - - -def test_hook_auth_error_dict_clear_message(tmp_path) -> None: - session = _HookSession( - hook=lambda _args: {"status": "error", "error": "401 unauthorized"}, - ) - out = dispatch_tool( - "web_search", {"query": "test"}, ctx=_ctx(tmp_path, session=session) - ) - assert out.is_error - assert "provider auth missing" in out.content - assert out.structured is not None - assert out.structured["status"] == "error" - - -def test_hook_generic_exception_message(tmp_path) -> None: - session = _HookSession( - hook=lambda _args: (_ for _ in ()).throw(RuntimeError("upstream timeout")), - ) - out = dispatch_tool( - "web_search", {"query": "test"}, ctx=_ctx(tmp_path, session=session) - ) - assert out.is_error - assert "provider hook failed" in out.content - assert "auth missing" not in out.content - - -def test_auth_hint_detects_common_patterns() -> None: - assert web_search._AUTH_ERROR_HINT.search("missing API key") - assert web_search._AUTH_ERROR_HINT.search("401 Unauthorized") - assert not web_search._AUTH_ERROR_HINT.search("connection reset") diff --git a/tests/python/forge/test_wire.py b/tests/python/forge/test_wire.py deleted file mode 100644 index c7fbc070f..000000000 --- a/tests/python/forge/test_wire.py +++ /dev/null @@ -1,37 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""L2 Forge wire checks — structured output and side effects.""" - -from __future__ import annotations - -import json - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.handlers import dispatch_tool -from pulsing.testing.forge_harness import ( - run_wire_check, - wire_check_tools, - wire_check_tools_local, -) - -pytestmark = [pytest.mark.forge, pytest.mark.forge_l2] - - -@pytest.mark.parametrize("tool", sorted(wire_check_tools_local())) -def test_l2_wire_local(local_forge, forge_workspace, tool: str) -> None: - run_wire_check(local_forge, forge_workspace, tool) - - -@pytest.mark.parametrize("tool", sorted(wire_check_tools())) -def test_l2_wire_hybrid(hybrid_forge, forge_workspace, tool: str) -> None: - run_wire_check(hybrid_forge, forge_workspace, tool) - - -def test_get_context_remaining_unknown_without_session_budget(forge_workspace) -> None: - """No ToolSession (defaults to NullToolSession) → degrade to status="unknown".""" - ctx = ToolCallContext(cwd=str(forge_workspace)) - out = dispatch_tool("get_context_remaining", {}, ctx=ctx) - assert not out.is_error - payload = json.loads(out.content) - assert payload == {"tokens_remaining": None, "status": "unknown"} diff --git a/tests/python/forge/test_write.py b/tests/python/forge/test_write.py deleted file mode 100644 index c68e664fc..000000000 --- a/tests/python/forge/test_write.py +++ /dev/null @@ -1,81 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Write tool: new file, overwrite, path escape, deep parent dirs.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.testing.forge_harness import local_runtime - -pytestmark = pytest.mark.forge - - -def test_write_creates_new_file(tmp_path: Path) -> None: - rt = local_runtime(tmp_path) - out = rt.call_tool("Write", {"file_path": "new.txt", "content": "hello"}) - assert not out.is_error - assert out.content == "created" - assert (tmp_path / "new.txt").read_text(encoding="utf-8") == "hello" - - -def test_write_overwrites_existing_file(tmp_path: Path) -> None: - target = tmp_path / "existing.txt" - target.write_text("old", encoding="utf-8") - rt = local_runtime(tmp_path) - out = rt.call_tool("Write", {"file_path": "existing.txt", "content": "new"}) - assert not out.is_error - assert out.content == "overwritten" - assert target.read_text(encoding="utf-8") == "new" - - -def test_write_creates_deep_parent_dirs(tmp_path: Path) -> None: - rt = local_runtime(tmp_path) - out = rt.call_tool("Write", {"file_path": "a/b/c/deep.txt", "content": "deep"}) - assert not out.is_error - assert (tmp_path / "a" / "b" / "c" / "deep.txt").read_text( - encoding="utf-8" - ) == "deep" - - -def test_write_rejects_relative_escape_outside_cwd(tmp_path: Path) -> None: - workspace = tmp_path / "workspace" - workspace.mkdir() - rt = local_runtime(workspace) - out = rt.call_tool("Write", {"file_path": "../escape.txt", "content": "x"}) - assert out.is_error - assert "outside working directory" in out.content - assert not (tmp_path / "escape.txt").exists() - - -def test_write_rejects_absolute_path_outside_cwd(tmp_path: Path) -> None: - workspace = tmp_path / "workspace" - workspace.mkdir() - outside = tmp_path / "outside.txt" - rt = local_runtime(workspace) - out = rt.call_tool("Write", {"file_path": str(outside), "content": "x"}) - assert out.is_error - assert "outside working directory" in out.content - assert not outside.exists() - - -def test_write_allows_absolute_path_inside_cwd(tmp_path: Path) -> None: - rt = local_runtime(tmp_path) - target = tmp_path / "abs.txt" - out = rt.call_tool("Write", {"file_path": str(target), "content": "ok"}) - assert not out.is_error - assert target.read_text(encoding="utf-8") == "ok" - - -def test_write_rejects_symlink_escape_outside_cwd(tmp_path: Path) -> None: - outside = tmp_path / "outside" - outside.mkdir() - workspace = tmp_path / "workspace" - workspace.mkdir() - (workspace / "link").symlink_to(outside) - rt = local_runtime(workspace) - out = rt.call_tool("Write", {"file_path": "link/escape.txt", "content": "x"}) - assert out.is_error - assert "outside working directory" in out.content - assert not (outside / "escape.txt").exists() diff --git a/tests/python/forge/test_write_stdin.py b/tests/python/forge/test_write_stdin.py deleted file mode 100644 index 744c5d5f0..000000000 --- a/tests/python/forge/test_write_stdin.py +++ /dev/null @@ -1,153 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""write_stdin boundary tests — unknown session, empty/oversized input, concurrency.""" - -from __future__ import annotations - -import threading -from pathlib import Path - -import pytest - -from pulsing.forge.exec_output import MAX_STDIN_BYTES -from pulsing.testing.forge_harness import local_runtime - -pytestmark = pytest.mark.forge - - -def test_write_stdin_unknown_session_returns_clear_error(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool("write_stdin", {"session_id": 999, "chars": "hi"}) - assert out.is_error - assert "999" in out.content - - -def test_write_stdin_missing_session_id(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool("write_stdin", {"chars": "hi"}) - assert out.is_error - - -def test_write_stdin_invalid_session_id_type(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool("write_stdin", {"session_id": "not-a-number", "chars": "hi"}) - assert out.is_error - - -def test_write_stdin_empty_input_on_live_session(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - started = rt.call_tool( - "exec_command", {"cmd": "cat", "yield_time_ms": 300, "tty": True} - ) - session_id = (started.structured or {}).get("session_id") - assert session_id is not None - try: - out = rt.call_tool( - "write_stdin", {"session_id": session_id, "chars": "", "yield_time_ms": 300} - ) - assert not out.is_error - finally: - rt.call_tool("write_stdin", {"session_id": session_id, "chars": "\x03"}) - - -def test_write_stdin_oversized_input_rejected(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - started = rt.call_tool( - "exec_command", {"cmd": "cat", "yield_time_ms": 300, "tty": True} - ) - session_id = (started.structured or {}).get("session_id") - assert session_id is not None - try: - huge = "a" * (MAX_STDIN_BYTES + 1) - out = rt.call_tool("write_stdin", {"session_id": session_id, "chars": huge}) - assert out.is_error - assert "too large" in out.content - finally: - rt.call_tool("write_stdin", {"session_id": session_id, "chars": "\x03"}) - - -def test_write_stdin_concurrent_writes_do_not_crash(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - started = rt.call_tool( - "exec_command", {"cmd": "cat", "yield_time_ms": 300, "tty": True} - ) - session_id = (started.structured or {}).get("session_id") - assert session_id is not None - - errors: list[Exception] = [] - - def _write(i: int) -> None: - try: - rt.call_tool( - "write_stdin", - {"session_id": session_id, "chars": f"{i}\n", "yield_time_ms": 250}, - ) - except Exception as exc: # noqa: BLE001 — assert no exception escapes - errors.append(exc) - - threads = [threading.Thread(target=_write, args=(i,)) for i in range(8)] - for t in threads: - t.start() - for t in threads: - t.join(timeout=10) - - rt.call_tool("write_stdin", {"session_id": session_id, "chars": "\x03"}) - assert not errors - - -def test_write_stdin_rejects_non_tty_session(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - started = rt.call_tool( - "exec_command", {"cmd": "sleep 5", "yield_time_ms": 300, "tty": False} - ) - session_id = (started.structured or {}).get("session_id") - assert session_id is not None - out = rt.call_tool("write_stdin", {"session_id": session_id, "chars": "hi"}) - assert out.is_error - assert "tty=true" in out.content - rt.call_tool("write_stdin", {"session_id": session_id, "chars": "\x03"}) - - -def test_write_stdin_rejects_utf8_oversized_by_bytes_not_chars( - forge_workspace: Path, -) -> None: - rt = local_runtime(forge_workspace) - started = rt.call_tool( - "exec_command", {"cmd": "cat", "yield_time_ms": 300, "tty": True} - ) - session_id = (started.structured or {}).get("session_id") - assert session_id is not None - try: - huge = "é" * (MAX_STDIN_BYTES // 2 + 1) - assert len(huge) < MAX_STDIN_BYTES - assert len(huge.encode("utf-8")) > MAX_STDIN_BYTES - out = rt.call_tool("write_stdin", {"session_id": session_id, "chars": huge}) - assert out.is_error - assert "too large" in out.content - finally: - rt.call_tool("write_stdin", {"session_id": session_id, "chars": "\x03"}) - - -def test_write_stdin_rejects_unknown_session_after_exit(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - started = rt.call_tool( - "exec_command", {"cmd": "cat", "yield_time_ms": 300, "tty": True} - ) - session_id = (started.structured or {}).get("session_id") - assert session_id is not None - ended = rt.call_tool( - "write_stdin", {"session_id": session_id, "chars": "\x03", "yield_time_ms": 500} - ) - assert (ended.structured or {}).get("exit_code") is not None - out = rt.call_tool("write_stdin", {"session_id": session_id, "chars": "hi"}) - assert out.is_error - assert "unknown session_id" in out.content or "already exited" in out.content - - -def test_exec_command_rejects_workdir_escape(forge_workspace: Path) -> None: - rt = local_runtime(forge_workspace) - out = rt.call_tool( - "exec_command", - {"cmd": "echo hi", "workdir": "..", "yield_time_ms": 300, "tty": True}, - ) - assert out.is_error - assert "outside working directory" in out.content diff --git a/tests/python/test_actor_only_distribution.py b/tests/python/test_actor_only_distribution.py new file mode 100644 index 000000000..7ec7120e9 --- /dev/null +++ b/tests/python/test_actor_only_distribution.py @@ -0,0 +1,67 @@ +"""Guard the actor distribution against removed application dependencies.""" + +from __future__ import annotations + +import importlib +import json +import subprocess +import sys +from pathlib import Path + +import pytest + + +@pytest.mark.parametrize( + "module", + [ + "pulsing.serving.router", + "pulsing.forge.runtime", + "pulsing.agent.llm", + "pulsing.cli.bench", + ], +) +def test_removed_application_modules(module): + with pytest.raises(ModuleNotFoundError): + importlib.import_module(module) + + +def test_native_module_has_no_application_exports(): + from pulsing import _core + + for name in ("ForgeRuntime", "CacheAwarePolicy", "CacheAwareConfig"): + assert not hasattr(_core, name) + + +def test_actor_cli_help(): + result = subprocess.run( + [sys.executable, "-m", "pulsing.cli", "--help"], + capture_output=True, + text=True, + check=True, + timeout=30, + ) + assert "actor" in result.stdout + assert "inspect" in result.stdout + assert "checkpoint" in result.stdout + for name in ("forge", "bench", "agent", "gui"): + assert name not in result.stdout.lower() + + +def test_workspace_defaults_do_not_require_an_agent(tmp_path: Path): + from pulsing.workspace import init_workspace + + result = init_workspace(tmp_path) + assert result.created + manifest = json.loads((tmp_path / ".pulsing/workspace.json").read_text()) + cluster = json.loads((tmp_path / ".pulsing/cluster.json").read_text()) + assert manifest["template"] == "minimal" + assert set(cluster) == {"cluster_id", "name"} + assert (tmp_path / ".pulsing/history/HEAD").is_file() + + +def test_workspace_rejects_removed_agent_template(tmp_path: Path): + from pulsing.workspace import init_workspace + + with pytest.raises(ValueError, match="expected minimal"): + init_workspace(tmp_path, template="agent") + assert not (tmp_path / ".pulsing").exists() diff --git a/tests/python/test_codex_parity.py b/tests/python/test_codex_parity.py deleted file mode 100644 index 11a6cb7f1..000000000 --- a/tests/python/test_codex_parity.py +++ /dev/null @@ -1,46 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Internal conformance gates (legacy entry — see tests/python/forge/).""" - -from __future__ import annotations - -import pytest - -from pulsing.forge.codex_parity import ( - assert_registry_gate, - format_report_text, - parity_report, -) -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE - -pytestmark = pytest.mark.forge - - -def test_ccrp_registry_gate() -> None: - """Every in-scope Codex tool must be registered in Forge.""" - assert_registry_gate() - - -def test_ccrp_parity_report_snapshot() -> None: - """Print parity summary; callable gate reflects maturin build.""" - report = parity_report(rust_available=RUST_FORGE_AVAILABLE) - text = format_report_text(report) - # Keep visible in pytest -v / CI logs for release notes. - print(text) - assert report.gates["registry"].pct == 100.0 - if RUST_FORGE_AVAILABLE: - assert report.gates["callable"].pct == 100.0, format_report_text(report) - assert report.certification in ("Bronze+", "Silver", "Gold", "Platinum") - assert report.certification in ( - "Incomplete", - "Bronze", - "Bronze+", - "Silver", - "Gold", - "Platinum", - ) - - -@pytest.mark.xfail(reason="L3 behavior parity not yet at Gold threshold") -def test_ccrp_behavior_gate_gold() -> None: - report = parity_report(rust_available=RUST_FORGE_AVAILABLE) - assert report.gates["behavior"].pct >= 90.0 diff --git a/tests/python/test_codex_plugin_compat.py b/tests/python/test_codex_plugin_compat.py deleted file mode 100644 index c72b8b5dd..000000000 --- a/tests/python/test_codex_plugin_compat.py +++ /dev/null @@ -1,186 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Codex plugin marketplace + cache install tests.""" - -from __future__ import annotations - -import json -import os -from pathlib import Path - -import pytest - -from pulsing.forge.discovery.catalog import ToolCatalog -from pulsing.forge.discovery.codex_paths import plugins_cache_root -from pulsing.forge.discovery.discoverable import ( - DiscoverableToolAction, - DiscoverableToolType, -) -from pulsing.forge.discovery.install import install_plugin_from_marketplace -from pulsing.forge.discovery.plugin_id import PluginId -from pulsing.forge.discovery.plugin_store import PluginStore -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.context import ToolCallContext -from pulsing.forge.session import LocalToolSession - - -@pytest.fixture -def codex_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - home = tmp_path / "codex" - home.mkdir() - monkeypatch.setenv("CODEX_HOME", str(home)) - monkeypatch.setenv("FORGE_PLUGIN_DISCOVER_ALL", "1") - return home - - -def _scaffold_marketplace(codex_home: Path) -> str: - agents = codex_home / ".agents" / "plugins" - agents.mkdir(parents=True) - plugin_src = agents / "demo" - manifest_dir = plugin_src / ".codex-plugin" - manifest_dir.mkdir(parents=True) - (manifest_dir / "plugin.json").write_text( - json.dumps( - { - "name": "demo", - "version": "1.0.0", - "description": "Demo plugin", - "mcpServers": ".mcp.json", - } - ), - encoding="utf-8", - ) - (plugin_src / ".mcp.json").write_text( - json.dumps({"mcpServers": {"demo-mcp": {"command": "echo"}}}), - encoding="utf-8", - ) - - marketplace_path = agents / "marketplace.json" - marketplace_path.write_text( - json.dumps( - { - "name": "local-dev", - "plugins": [ - { - "name": "demo", - "source": {"source": "local", "path": "./demo"}, - "policy": {"installation": "AVAILABLE"}, - } - ], - } - ), - encoding="utf-8", - ) - return "demo@local-dev" - - -def test_marketplace_discover_and_install(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - catalog = ToolCatalog() - catalog.refresh_from_codex() - assert any(t.id == plugin_id for t in catalog.discoverable) - - result = install_plugin_from_marketplace(plugin_id) - assert result.installed_path.is_dir() - assert PluginStore().is_installed(result.plugin_id) - - cache_root = plugins_cache_root() - assert ( - cache_root / "local-dev" / "demo" / "1.0.0" / ".codex-plugin" / "plugin.json" - ).is_file() - - -def test_plugin_store_sorts_mixed_numeric_and_text_versions( - codex_home: Path, -) -> None: - plugin_id = PluginId(plugin_name="demo", marketplace_name="local-dev") - base = PluginStore().plugin_base_root(plugin_id) - for version in ["1.0.9", "1.0.dev", "1.0.10"]: - (base / version).mkdir(parents=True) - - assert PluginStore().active_plugin_version(plugin_id) == "1.0.dev" - - -def test_request_plugin_install_codex_wire(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - session = LocalToolSession( - plugin_install=lambda args: True, - ) - ctx = ToolCallContext(cwd=".", session=session) - ctx.tool_catalog.refresh_from_codex() - - out = dispatch_tool( - "request_plugin_install", - { - "tool_type": "plugin", - "action_type": "install", - "tool_id": plugin_id, - "suggest_reason": "Need demo MCP tools", - }, - ctx=ctx, - ) - assert not out.is_error - payload = json.loads(out.content) - assert payload["completed"] is True - assert payload["user_confirmed"] is True - assert payload["tool_type"] == "plugin" - assert payload["tool_id"] == plugin_id - - -def test_list_available_plugins_codex_wire(codex_home: Path) -> None: - plugin_id = _scaffold_marketplace(codex_home) - ctx = ToolCallContext(cwd=".", session=LocalToolSession()) - out = dispatch_tool("list_available_plugins_to_install", {}, ctx=ctx) - payload = json.loads(out.content) - entry = payload["tools"][0] - assert entry["tool_type"] == "plugin" - assert entry["id"] == plugin_id - assert set(entry) == { - "id", - "name", - "description", - "tool_type", - "has_skills", - "mcp_server_names", - "app_connector_ids", - } - - -def test_list_available_plugins_refresh_failure_returns_tool_error( - codex_home: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A broken plugin cache must surface as a ToolResult error, not an uncaught exception.""" - - ctx = ToolCallContext( - cwd=".", session=LocalToolSession() - ) # initial refresh succeeds - - def _boom(self: PluginStore) -> list[PluginId]: - raise OSError("permission denied") - - monkeypatch.setattr(PluginStore, "list_installed_plugin_ids", _boom) - out = dispatch_tool("list_available_plugins_to_install", {}, ctx=ctx) - assert out.is_error - assert "permission denied" in out.content - - -def test_list_available_plugins_skips_corrupt_installed_plugin( - codex_home: Path, -) -> None: - """One plugin with a broken manifest must not block listing the rest of the catalog.""" - plugin_id = _scaffold_marketplace(codex_home) - install_plugin_from_marketplace(plugin_id) - manifest_path = ( - plugins_cache_root() - / "local-dev" - / "demo" - / "1.0.0" - / ".codex-plugin" - / "plugin.json" - ) - manifest_path.write_text("{not valid json", encoding="utf-8") - - ctx = ToolCallContext(cwd=".", session=LocalToolSession()) - out = dispatch_tool("list_available_plugins_to_install", {}, ctx=ctx) - assert not out.is_error - payload = json.loads(out.content) - assert payload["tools"] == [] diff --git a/tests/python/test_core_api_surface.py b/tests/python/test_core_api_surface.py index 0e940de7a..b929a266f 100644 --- a/tests/python/test_core_api_surface.py +++ b/tests/python/test_core_api_surface.py @@ -23,11 +23,8 @@ "ActorId", "ActorRef", "ActorSystem", - "CacheAwareConfig", - "CacheAwarePolicy", "ConnectActorRef", "ConsistentHashPolicy", - "ForgeRuntime", "Message", "NodeId", "PowerOfTwoPolicy", diff --git a/tests/python/test_forge_backend.py b/tests/python/test_forge_backend.py deleted file mode 100644 index 70f1df212..000000000 --- a/tests/python/test_forge_backend.py +++ /dev/null @@ -1,93 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for ForgeBackend and Pulsing Actor integration helpers.""" - -from __future__ import annotations - -import asyncio - -import pytest - -from pulsing.forge.tool_coverage import assert_forge_tool_coverage -from pulsing.forge.backend import ( - ForgeBackend, - ForgeBackendMode, - ForgeHostConfig, - create_host_runtime, -) -from pulsing.forge.integrated import FORGE_HOST_TOOL_NAMES, FORGE_ISOLATED_TOOL_NAMES -from pulsing.forge.naming import shared_tool_worker_name - - -def test_shared_tool_worker_name() -> None: - assert shared_tool_worker_name("abc123") == "craft/ws/abc123/_tools" - - -def test_forge_backend_modes_disjoint_tool_sets() -> None: - assert not (FORGE_ISOLATED_TOOL_NAMES & FORGE_HOST_TOOL_NAMES) - assert len(FORGE_ISOLATED_TOOL_NAMES) + len(FORGE_HOST_TOOL_NAMES) == 32 - - -def test_create_host_runtime_local() -> None: - rt = create_host_runtime(ForgeHostConfig(cwd=".", auto_approve=True)) - out = rt.call_tool("get_context_remaining", {}) - assert not out.is_error - - -def test_forge_tool_schema_coverage() -> None: - assert_forge_tool_coverage() - - -def test_forge_backend_mode_enum() -> None: - assert ForgeBackendMode.DEDICATED.value == "dedicated" - assert ForgeBackendMode.SHARED.value == "shared" - - -class _FlakyWorker: - """Minimal ForgeIsolatedWorker stand-in: fails once, then succeeds.""" - - def __init__(self, mode: ForgeBackendMode) -> None: - self.mode = mode - self._lock = asyncio.Lock() - self.calls = 0 - self.respawns = 0 - - async def call_tool(self, name, arguments=None, *, event_sink=None): - self.calls += 1 - if self.calls == 1: - raise RuntimeError("worker died") - return {"content": "ok", "is_error": False} - - async def respawn(self, *, reason: str) -> None: - self.respawns += 1 - - -@pytest.mark.asyncio -async def test_forge_backend_call_tool_retries_dedicated_worker() -> None: - """A failed isolated call must respawn (not crash with AttributeError/deadlock).""" - worker = _FlakyWorker(ForgeBackendMode.DEDICATED) - backend = ForgeBackend( - host=create_host_runtime(ForgeHostConfig(cwd=".")), worker=worker - ) - - name = next(iter(FORGE_ISOLATED_TOOL_NAMES)) - result = await asyncio.wait_for(backend.call_tool(name, {}), timeout=5.0) - - assert not result.is_error - assert worker.calls == 2 - assert worker.respawns == 1 - - -@pytest.mark.asyncio -async def test_forge_backend_call_tool_retries_shared_worker() -> None: - """Shared-mode recovery must only clear the local proxy (no respawn).""" - worker = _FlakyWorker(ForgeBackendMode.SHARED) - backend = ForgeBackend( - host=create_host_runtime(ForgeHostConfig(cwd=".")), worker=worker - ) - - name = next(iter(FORGE_ISOLATED_TOOL_NAMES)) - result = await asyncio.wait_for(backend.call_tool(name, {}), timeout=5.0) - - assert not result.is_error - assert worker.calls == 2 - assert worker.respawns == 0 diff --git a/tests/python/test_forge_code_mode.py b/tests/python/test_forge_code_mode.py deleted file mode 100644 index 80f38e568..000000000 --- a/tests/python/test_forge_code_mode.py +++ /dev/null @@ -1,70 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Smoke tests for Forge Code Mode (Python cell exec/wait).""" - -from __future__ import annotations - -from pathlib import Path - -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.context import ToolCallContext - - -def _ctx(tmp_path: Path) -> ToolCallContext: - return ToolCallContext(cwd=tmp_path) - - -def test_exec_completes_with_text(tmp_path: Path) -> None: - ctx = _ctx(tmp_path) - out = dispatch_tool("exec", {"source": 'text("hello from cell")\n'}, ctx=ctx) - assert not out.is_error - assert "hello from cell" in out.content - assert out.structured is not None - assert out.structured["kind"] == "result" - assert out.structured["cell_id"].startswith("cell-") - - -def test_exec_yield_control(tmp_path: Path) -> None: - ctx = _ctx(tmp_path) - source = 'text("part1")\nyield_control()\ntext("part2")\n' - out = dispatch_tool("exec", {"source": source}, ctx=ctx) - assert not out.is_error - assert out.structured is not None - assert out.structured["kind"] == "yielded" - assert "part1" in out.content - assert "part2" not in out.content - - cell_id = out.structured["cell_id"] - wait_out = dispatch_tool( - "wait", - {"cell_id": cell_id, "terminate": False}, - ctx=ctx, - ) - assert not wait_out.is_error - assert wait_out.structured is not None - assert wait_out.structured["kind"] == "result" - assert "part2" in wait_out.content - - -def test_exec_nested_read(tmp_path: Path) -> None: - sample = tmp_path / "sample.txt" - sample.write_text("forge code mode", encoding="utf-8") - ctx = _ctx(tmp_path) - source = f'text(tools.call("Read", {{"file_path": "{sample}"}}))\n' - out = dispatch_tool("exec", {"source": source}, ctx=ctx) - assert not out.is_error - assert "forge code mode" in out.content - - -def test_exec_pragma_parsed(tmp_path: Path) -> None: - ctx = _ctx(tmp_path) - source = '# @exec: {"yield_time_ms": 5000}\ntext("ok")\n' - out = dispatch_tool("exec", {"source": source}, ctx=ctx) - assert not out.is_error - assert "ok" in out.content - - -def test_wait_unknown_cell(tmp_path: Path) -> None: - ctx = _ctx(tmp_path) - out = dispatch_tool("wait", {"cell_id": "cell-missing"}, ctx=ctx) - assert out.is_error - assert "unknown cell_id" in out.content diff --git a/tests/python/test_forge_discovery.py b/tests/python/test_forge_discovery.py deleted file mode 100644 index 4a470feb9..000000000 --- a/tests/python/test_forge_discovery.py +++ /dev/null @@ -1,74 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge session + discovery tests.""" - -from __future__ import annotations - -import json - -import pytest - -from pulsing.forge.discovery.catalog import DeferredToolEntry, ToolCatalog -from pulsing.forge.handlers import dispatch_tool -from pulsing.forge.context import ToolCallContext -from pulsing.forge.session import LocalToolSession -from pulsing.forge.session_input import validate_request_user_input - - -def test_validate_request_user_input_rejects_empty(): - with pytest.raises(ValueError): - validate_request_user_input({"questions": []}) - - -def test_tool_search_bm25(): - catalog = ToolCatalog() - catalog.register_deferred( - DeferredToolEntry.from_function("github_pr", "Open GitHub pull requests") - ) - catalog.register_deferred( - DeferredToolEntry.from_function("read_file", "Read workspace files") - ) - hits = catalog.search("github pull request") - assert hits[0].name == "github_pr" - - -def test_get_context_remaining_structured(): - session = LocalToolSession(token_budget=42_000) - ctx = ToolCallContext(cwd=".", session=session) - out = dispatch_tool("get_context_remaining", {}, ctx=ctx) - payload = json.loads(out.content) - assert payload["tokens_remaining"] == 42_000 - assert payload["status"] == "ok" - - -def test_list_plugins_empty_catalog(): - ctx = ToolCallContext(cwd=".", session=LocalToolSession()) - out = dispatch_tool("list_available_plugins_to_install", {}, ctx=ctx) - payload = json.loads(out.content) - assert "tools" in payload - - -def test_auto_resolution_timeout_defaults(monkeypatch: pytest.MonkeyPatch) -> None: - import pulsing.forge.session_input as session_input - - monkeypatch.setattr(session_input, "MIN_AUTO_RESOLUTION_MS", 1) - - args = session_input.validate_request_user_input( - { - "questions": [ - { - "id": "pick", - "header": "Go", - "question": "Which?", - "options": [ - {"label": "A (Recommended)", "description": "first"}, - {"label": "B", "description": "second"}, - ], - } - ], - "autoResolutionMs": 50, - } - ) - out = session_input.resolve_user_input( - args, auto_approve=False, user_input_callback=None, prompt_callback=None - ) - assert out["answers"]["pick"]["answers"] == ["A (Recommended)"] diff --git a/tests/python/test_forge_extension.py b/tests/python/test_forge_extension.py deleted file mode 100644 index a97fc6356..000000000 --- a/tests/python/test_forge_extension.py +++ /dev/null @@ -1,76 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Smoke tests for Forge Extension tools (web.run, skills, memories, web_search).""" - -from __future__ import annotations - -from pathlib import Path - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.handlers import dispatch_tool - - -def _ctx(tmp_path: Path) -> ToolCallContext: - return ToolCallContext(cwd=tmp_path) - - -def test_skills_list_and_read(tmp_path: Path, monkeypatch) -> None: - skills_root = tmp_path / ".agents" / "skills" / "demo-skill" - skills_root.mkdir(parents=True) - (skills_root / "SKILL.md").write_text( - "---\nname: demo-skill\ndescription: Demo skill for tests\n---\n# Demo\nbody\n", - encoding="utf-8", - ) - ctx = _ctx(tmp_path) - listed = dispatch_tool("skills.list", {}, ctx=ctx) - assert not listed.is_error - assert "demo-skill" in listed.content - - read = dispatch_tool("skills.read", {"name": "demo-skill"}, ctx=ctx) - assert not read.is_error - assert "Demo skill for tests" in read.content - - -def test_memories_crud(tmp_path: Path, monkeypatch) -> None: - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(tmp_path / "memories")) - ctx = _ctx(tmp_path) - add = dispatch_tool( - "memories.add_ad_hoc_note", - { - "filename": "2026-05-23T12-00-00-remember-this.md", - "note": "remember this detail", - }, - ctx=ctx, - ) - assert not add.is_error - - listed = dispatch_tool("memories.list", {}, ctx=ctx) - assert not listed.is_error - assert listed.structured is not None - assert listed.structured.get("entries") - - search = dispatch_tool("memories.search", {"queries": ["remember"]}, ctx=ctx) - assert not search.is_error - assert search.structured is not None - assert search.structured.get("matches") - - -def test_web_run_open_allowlist(tmp_path: Path, monkeypatch) -> None: - monkeypatch.setenv("FORGE_WEB_ALLOW", "example.com") - ctx = _ctx(tmp_path) - out = dispatch_tool( - "web.run", - {"open": [{"ref_id": "https://example.com/"}]}, - ctx=ctx, - ) - # Network may fail in CI; accept success or HTTP error, not allowlist error. - assert "is not in FORGE_WEB_ALLOW" not in out.content - - -def test_web_search_hosted_stub(tmp_path: Path) -> None: - ctx = _ctx(tmp_path) - out = dispatch_tool("web_search", {"query": "pulsing actor"}, ctx=ctx) - assert not out.is_error - assert out.structured is not None - assert out.structured.get("kind") == "hosted_web_search" - assert out.structured.get("status") == "deferred" - assert out.structured.get("reason") == "provider_not_configured" diff --git a/tests/python/test_forge_integrated.py b/tests/python/test_forge_integrated.py deleted file mode 100644 index 4c29e97da..000000000 --- a/tests/python/test_forge_integrated.py +++ /dev/null @@ -1,15 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Forge integrated runtime tests.""" - -from __future__ import annotations - -from pulsing.forge.tool_coverage import assert_forge_tool_coverage -from pulsing.forge.integrated import FORGE_HOST_TOOL_NAMES, FORGE_ISOLATED_TOOL_NAMES - - -def test_forge_tool_coverage() -> None: - assert_forge_tool_coverage() - - -def test_forge_tool_partitions() -> None: - assert not (FORGE_ISOLATED_TOOL_NAMES & FORGE_HOST_TOOL_NAMES) diff --git a/tests/python/test_forge_mcp.py b/tests/python/test_forge_mcp.py deleted file mode 100644 index 8fbde9c38..000000000 --- a/tests/python/test_forge_mcp.py +++ /dev/null @@ -1,63 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for Forge MCP catalog loading.""" - -from __future__ import annotations - -import json -from pathlib import Path - -from pulsing.forge.discovery.plugin_id import PluginId -from pulsing.forge.discovery.plugin_store import PluginStore -from pulsing.forge.mcp.catalog import load_mcp_catalog, parse_plugin_mcp_file - - -def test_parse_plugin_mcp_file_shapes(tmp_path: Path) -> None: - wrapped = tmp_path / "wrapped.json" - wrapped.write_text( - json.dumps({"mcpServers": {"demo": {"command": "echo", "args": ["hi"]}}}), - encoding="utf-8", - ) - out = parse_plugin_mcp_file(tmp_path, wrapped) - assert "demo" in out - assert out["demo"]["command"] == "echo" - - flat = tmp_path / "flat.json" - flat.write_text( - json.dumps({"github": {"command": "npx", "args": ["pkg"]}}), encoding="utf-8" - ) - out2 = parse_plugin_mcp_file(tmp_path, flat) - assert "github" in out2 - - -def test_load_mcp_catalog_empty(monkeypatch) -> None: - monkeypatch.setenv("CODEX_HOME", "/tmp/nonexistent-codex-home-forge-test") - snap = load_mcp_catalog() - assert isinstance(snap.servers, dict) - - -def test_load_mcp_catalog_uses_active_plugin_version( - tmp_path: Path, monkeypatch -) -> None: - monkeypatch.setenv("CODEX_HOME", str(tmp_path)) - plugin_id = PluginId(plugin_name="demo", marketplace_name="local-dev") - root = PluginStore().plugin_version_root(plugin_id, "1.2.3") - manifest_dir = root / ".codex-plugin" - manifest_dir.mkdir(parents=True) - (manifest_dir / "plugin.json").write_text( - json.dumps( - { - "name": "demo", - "version": "1.2.3", - "mcpServers": ".mcp.json", - } - ), - encoding="utf-8", - ) - (root / ".mcp.json").write_text( - json.dumps({"mcpServers": {"demo-server": {"command": "echo"}}}), - encoding="utf-8", - ) - - snapshot = load_mcp_catalog() - - assert snapshot.servers["demo-server"].plugin_id == plugin_id.id diff --git a/tests/python/test_forge_memories.py b/tests/python/test_forge_memories.py deleted file mode 100644 index d2fe0d088..000000000 --- a/tests/python/test_forge_memories.py +++ /dev/null @@ -1,719 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for Forge memories backend (Codex ext/memories alignment).""" - -from __future__ import annotations - -import threading -from pathlib import Path - -import pytest - -from pulsing.forge.context import ToolCallContext -from pulsing.forge.extension.memories.backend import ( - AD_HOC_NOTE_MAX_BYTES, - MAX_LIST_RESULTS, - MAX_SEARCH_CONTEXT_LINES, - MAX_SEARCH_MATCH_WINDOW_LINES, - MAX_SEARCH_QUERIES, - MemoriesBackendError, - SearchMatchMode, - SearchMatchModeKind, -) -from pulsing.forge.extension.memories.local_backend import ( - LocalMemoriesStore, - clamp_max_results, - default_ad_hoc_filename, -) -from pulsing.forge.extension.memories.path_utils import ( - MAX_READ_FILE_BYTES, - validate_read_path, -) -from pulsing.forge.handlers import dispatch_tool - - -def _store(tmp_path: Path) -> LocalMemoriesStore: - root = tmp_path / "memories" - root.mkdir() - return LocalMemoriesStore(root) - - -def test_list_immediate_children_and_cursor(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "a.md").write_text("a", encoding="utf-8") - sub = store.root / "nested" - sub.mkdir() - (sub / "b.md").write_text("b", encoding="utf-8") - - page1 = store.list_memories(max_results=1) - assert len(page1.entries) == 1 - assert page1.truncated - assert page1.next_cursor == "1" - - page2 = store.list_memories(cursor=page1.next_cursor, max_results=1) - assert len(page2.entries) == 1 - assert page2.entries[0].entry_type.value == "directory" - - -def test_list_nested_path(tmp_path: Path) -> None: - store = _store(tmp_path) - nested = store.root / "nested" - nested.mkdir() - (nested / "note.md").write_text("hello", encoding="utf-8") - - out = store.list_memories(path="nested") - assert len(out.entries) == 1 - assert out.entries[0].path == "nested/note.md" - - -def test_list_skips_hidden_entries(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / ".hidden.md").write_text("x", encoding="utf-8") - (store.root / "visible.md").write_text("y", encoding="utf-8") - - out = store.list_memories() - paths = [e.path for e in out.entries] - assert paths == ["visible.md"] - - -def test_list_rejects_path_traversal(tmp_path: Path) -> None: - store = _store(tmp_path) - with pytest.raises(MemoriesBackendError, match="must stay within"): - store.list_memories(path="../outside") - - -def test_list_rejects_hidden_path_component(tmp_path: Path) -> None: - store = _store(tmp_path) - hidden = store.root / ".secret" - hidden.mkdir() - (hidden / "note.md").write_text("x", encoding="utf-8") - - with pytest.raises(MemoriesBackendError, match="not found"): - store.list_memories(path=".secret") - - -def test_list_rejects_symlink_path(tmp_path: Path) -> None: - store = _store(tmp_path) - outside = tmp_path / "outside" - outside.mkdir() - (outside / "note.md").write_text("x", encoding="utf-8") - (store.root / "link").symlink_to(outside) - - with pytest.raises(MemoriesBackendError, match="symlink|must stay within"): - store.list_memories(path="link") - - -def test_list_not_found(tmp_path: Path) -> None: - store = _store(tmp_path) - with pytest.raises(MemoriesBackendError, match="not found"): - store.list_memories(path="missing-dir") - - -def test_list_single_file(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "solo.md").write_text("solo", encoding="utf-8") - - out = store.list_memories(path="solo.md") - assert len(out.entries) == 1 - assert out.entries[0].path == "solo.md" - assert out.entries[0].entry_type.value == "file" - assert out.next_cursor is None - assert not out.truncated - - -def test_list_invalid_cursor(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "a.md").write_text("a", encoding="utf-8") - - with pytest.raises(MemoriesBackendError, match="must be a non-negative integer"): - store.list_memories(cursor="bad") - - with pytest.raises(MemoriesBackendError, match="exceeds result count"): - store.list_memories(cursor="99") - - -def test_dispatch_list_path_traversal(tmp_path: Path, monkeypatch) -> None: - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(tmp_path / "memories")) - outside = tmp_path / "outside.txt" - outside.write_text("secret", encoding="utf-8") - ctx = ToolCallContext(cwd=tmp_path) - - result = dispatch_tool("memories.list", {"path": "../outside.txt"}, ctx=ctx) - assert result.is_error - assert "must stay within" in result.content - - result = dispatch_tool("memories.list", {"path": str(outside)}, ctx=ctx) - assert result.is_error - assert "must stay within" in result.content - - -def test_dispatch_list_rejects_null_byte(tmp_path: Path, monkeypatch) -> None: - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(tmp_path / "memories")) - ctx = ToolCallContext(cwd=tmp_path) - - result = dispatch_tool("memories.list", {"path": "foo\x00bar"}, ctx=ctx) - assert result.is_error - assert "must stay within" in result.content - - -def test_list_max_results_capped(tmp_path: Path) -> None: - store = _store(tmp_path) - for i in range(5): - (store.root / f"{i:02d}.md").write_text("x", encoding="utf-8") - - page = store.list_memories(max_results=2) - assert len(page.entries) == 2 - assert page.truncated - assert page.next_cursor == "2" - - assert ( - clamp_max_results(MAX_LIST_RESULTS + 500, 2000, MAX_LIST_RESULTS) - == MAX_LIST_RESULTS - ) - - -def test_memories_root_falls_back_to_codex_home(tmp_path: Path, monkeypatch) -> None: - codex = tmp_path / "codex" - monkeypatch.delenv("FORGE_MEMORIES_ROOT", raising=False) - monkeypatch.setenv("CODEX_HOME", str(codex)) - - store = LocalMemoriesStore() - assert store.root == (codex / "memories").resolve() - assert store.root.is_dir() - - -def test_read_one_indexed_and_max_lines(tmp_path: Path) -> None: - store = _store(tmp_path) - rel = "doc.md" - (store.root / rel).write_text("line1\nline2\nline3\n", encoding="utf-8") - - out = store.read_memory(path=rel, line_offset=2, max_lines=1) - assert out.start_line_number == 2 - assert out.content == "line2\n" - assert out.truncated # more lines remain in file - - with pytest.raises(MemoriesBackendError): - store.read_memory(path=rel, line_offset=0) - - -def test_read_rejects_invalid_line_offset(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "doc.md").write_text("line1\n", encoding="utf-8") - - for bad in [-1, 0]: - with pytest.raises(MemoriesBackendError, match="1-indexed line number"): - store.read_memory(path="doc.md", line_offset=bad) - - -def test_read_rejects_invalid_max_lines(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "doc.md").write_text("line1\n", encoding="utf-8") - - for bad in [-1, 0]: - with pytest.raises(MemoriesBackendError, match="positive integer"): - store.read_memory(path="doc.md", max_lines=bad) - - -def test_read_not_found_and_not_file(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "dir").mkdir() - - with pytest.raises(MemoriesBackendError, match="was not found"): - store.read_memory(path="missing.md") - - with pytest.raises(MemoriesBackendError, match="is not a file"): - store.read_memory(path="dir") - - -def test_read_rejects_hidden_path(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / ".secret.md").write_text("hidden", encoding="utf-8") - - with pytest.raises(MemoriesBackendError, match="not found"): - store.read_memory(path=".secret.md") - - -def test_read_rejects_binary_file(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "bin.md").write_bytes(b"\xff\xfe") - - with pytest.raises(MemoriesBackendError, match="not valid UTF-8 text"): - store.read_memory(path="bin.md") - - -def test_read_line_offset_exceeds_length(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "doc.md").write_text("only\n", encoding="utf-8") - - with pytest.raises(MemoriesBackendError, match="exceeds file length"): - store.read_memory(path="doc.md", line_offset=99) - - -def test_validate_read_path_rejects_null_byte() -> None: - with pytest.raises(MemoriesBackendError, match="must stay within"): - validate_read_path("notes\x00.md") - - -def test_dispatch_read_empty_path(tmp_path: Path, monkeypatch) -> None: - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(tmp_path / "memories")) - ctx = ToolCallContext(cwd=tmp_path) - - result = dispatch_tool("memories.read", {"path": " "}, ctx=ctx) - assert result.is_error - assert result.content == "path is required" - - -def test_dispatch_read_success(tmp_path: Path, monkeypatch) -> None: - root = tmp_path / "memories" - root.mkdir() - (root / "note.md").write_text("hello\nworld\n", encoding="utf-8") - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(root)) - ctx = ToolCallContext(cwd=tmp_path) - - result = dispatch_tool( - "memories.read", - {"path": "note.md", "line_offset": 2, "max_lines": 1}, - ctx=ctx, - ) - assert not result.is_error - assert result.structured is not None - assert result.structured["path"] == "note.md" - assert result.structured["start_line_number"] == 2 - assert result.structured["content"] == "world\n" - - -def test_dispatch_read_binary_file(tmp_path: Path, monkeypatch) -> None: - root = tmp_path / "memories" - root.mkdir() - (root / "bin.md").write_bytes(b"\xff\xfe") - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(root)) - ctx = ToolCallContext(cwd=tmp_path) - - result = dispatch_tool("memories.read", {"path": "bin.md"}, ctx=ctx) - assert result.is_error - assert "not valid UTF-8 text" in result.content - - -def test_read_rejects_path_traversal(tmp_path: Path) -> None: - store = _store(tmp_path) - outside = tmp_path / "outside.txt" - outside.write_text("secret", encoding="utf-8") - (store.root / "ok.md").write_text("safe", encoding="utf-8") - - for bad in [ - "../outside.txt", - "nested/../../outside.txt", - str(outside), - "/etc/passwd", - ]: - with pytest.raises(MemoriesBackendError, match="must stay within|not found"): - store.read_memory(path=bad) - - -def test_read_rejects_symlink_escape(tmp_path: Path) -> None: - store = _store(tmp_path) - outside = tmp_path / "secret.txt" - outside.write_text("TOP SECRET", encoding="utf-8") - - (store.root / "link.md").symlink_to(outside) - with pytest.raises(MemoriesBackendError, match="symlink|must stay within"): - store.read_memory(path="link.md") - - (store.root / "escape").symlink_to(tmp_path) - with pytest.raises(MemoriesBackendError, match="symlink|must stay within"): - store.read_memory(path="escape/secret.txt") - - -def test_read_rejects_oversized_file(tmp_path: Path) -> None: - store = _store(tmp_path) - big = store.root / "big.md" - big.write_bytes(b"x" * (MAX_READ_FILE_BYTES + 1)) - - with pytest.raises(MemoriesBackendError, match="byte read limit"): - store.read_memory(path="big.md") - - -def test_dispatch_read_path_traversal(tmp_path: Path, monkeypatch) -> None: - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(tmp_path / "memories")) - outside = tmp_path / "outside.txt" - outside.write_text("secret", encoding="utf-8") - ctx = ToolCallContext(cwd=tmp_path) - - result = dispatch_tool("memories.read", {"path": "../outside.txt"}, ctx=ctx) - assert result.is_error - assert "must stay within" in result.content or "not found" in result.content - - result = dispatch_tool("memories.read", {"path": str(outside)}, ctx=ctx) - assert result.is_error - assert "must stay within" in result.content - - -def test_search_any_and_all_on_same_line(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "t.md").write_text("alpha beta\ngamma\n", encoding="utf-8") - - any_hit = store.search_memories(queries=["alpha", "gamma"]) - assert len(any_hit.matches) == 2 - - same_line = store.search_memories( - queries=["alpha", "beta"], - match_mode=SearchMatchMode(kind=SearchMatchModeKind.ALL_ON_SAME_LINE), - ) - assert len(same_line.matches) == 1 - assert same_line.matches[0].match_line_number == 1 - - -def test_search_all_within_lines(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "w.md").write_text("foo\nbar baz\n", encoding="utf-8") - - out = store.search_memories( - queries=["foo", "baz"], - match_mode=SearchMatchMode( - kind=SearchMatchModeKind.ALL_WITHIN_LINES, line_count=2 - ), - ) - assert len(out.matches) == 1 - assert "foo" in out.matches[0].content - assert "baz" in out.matches[0].content - - -def test_search_case_insensitive_multi_query(tmp_path: Path) -> None: - """Mirrors codex ext/memories search_tool_accepts_multiple_queries.""" - store = _store(tmp_path) - (store.root / "MEMORY.md").write_text( - "alpha only\nneedle only\nalpha needle\n", - encoding="utf-8", - ) - - out = store.search_memories(queries=["alpha", "needle"], case_sensitive=False) - assert [m.match_line_number for m in out.matches] == [1, 2, 3] - assert out.matches[0].matched_queries == ["alpha"] - assert out.matches[1].matched_queries == ["needle"] - assert out.matches[2].matched_queries == ["alpha", "needle"] - - -def test_search_windowed_all_within_lines_codex_shape(tmp_path: Path) -> None: - """Mirrors codex ext/memories search_tool_accepts_windowed_all_match_mode.""" - store = _store(tmp_path) - (store.root / "MEMORY.md").write_text("alpha\nmiddle\nneedle\n", encoding="utf-8") - - out = store.search_memories( - queries=["alpha", "needle"], - match_mode=SearchMatchMode( - kind=SearchMatchModeKind.ALL_WITHIN_LINES, line_count=3 - ), - ) - assert len(out.matches) == 1 - assert out.matches[0].match_line_number == 1 - assert out.matches[0].content == "alpha\nmiddle\nneedle" - assert out.matches[0].matched_queries == ["alpha", "needle"] - - -def test_search_no_results(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "note.md").write_text("hello world\n", encoding="utf-8") - - out = store.search_memories(queries=["missing"]) - assert out.matches == [] - assert out.next_cursor is None - assert not out.truncated - - -def test_search_empty_query_errors(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "note.md").write_text("x\n", encoding="utf-8") - - with pytest.raises(MemoriesBackendError, match="at least one query is required"): - store.search_memories(queries=[]) - - with pytest.raises( - MemoriesBackendError, match="queries must not contain empty strings" - ): - store.search_memories(queries=["ok", " "]) - - -def test_search_normalized_match(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "note.md").write_text("foo-bar_baz\n", encoding="utf-8") - - out = store.search_memories(queries=["foobarbaz"], normalized=True) - assert len(out.matches) == 1 - assert out.matches[0].match_line_number == 1 - - -def test_search_normalized_empty_query_error(tmp_path: Path) -> None: - store = _store(tmp_path) - - with pytest.raises(MemoriesBackendError, match="empty after normalization"): - store.search_memories(queries=["!!!"], normalized=True) - - -def test_search_context_lines_and_pagination(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "doc.md").write_text( - "line0\nhit1\nline2\nhit3\nline4\n", encoding="utf-8" - ) - - with_ctx = store.search_memories(queries=["hit"], context_lines=1) - assert with_ctx.matches[0].content == "line0\nhit1\nline2" - assert with_ctx.matches[0].content_start_line_number == 1 - - page1 = store.search_memories(queries=["hit"], max_results=1) - assert len(page1.matches) == 1 - assert page1.truncated - assert page1.next_cursor == "1" - - page2 = store.search_memories( - queries=["hit"], cursor=page1.next_cursor, max_results=1 - ) - assert len(page2.matches) == 1 - assert page2.matches[0].match_line_number == 4 - - -def test_search_path_scoped_and_skips_hidden(tmp_path: Path) -> None: - store = _store(tmp_path) - nested = store.root / "nested" - nested.mkdir() - (nested / "visible.md").write_text("secret keyword\n", encoding="utf-8") - (nested / ".hidden.md").write_text("secret keyword\n", encoding="utf-8") - (store.root / "other.md").write_text("secret keyword\n", encoding="utf-8") - - scoped = store.search_memories(queries=["secret"], path="nested") - paths = {m.path for m in scoped.matches} - assert paths == {"nested/visible.md"} - - -def test_search_rejects_path_traversal(tmp_path: Path) -> None: - store = _store(tmp_path) - outside = tmp_path / "outside.txt" - outside.write_text("needle\n", encoding="utf-8") - - with pytest.raises(MemoriesBackendError, match="must stay within|not found"): - store.search_memories(queries=["needle"], path="../outside.txt") - - -def test_search_query_limits_and_invalid_cursor(tmp_path: Path) -> None: - store = _store(tmp_path) - (store.root / "a.md").write_text("x\n", encoding="utf-8") - - too_many = [f"q{i}" for i in range(MAX_SEARCH_QUERIES + 1)] - with pytest.raises(MemoriesBackendError, match=f"at most {MAX_SEARCH_QUERIES}"): - store.search_memories(queries=too_many) - - with pytest.raises( - MemoriesBackendError, - match="all_within_lines.line_count must be a positive integer", - ): - store.search_memories( - queries=["x"], - match_mode=SearchMatchMode( - kind=SearchMatchModeKind.ALL_WITHIN_LINES, line_count=0 - ), - ) - - with pytest.raises( - MemoriesBackendError, - match=f"at most {MAX_SEARCH_MATCH_WINDOW_LINES}", - ): - store.search_memories( - queries=["x"], - match_mode=SearchMatchMode( - kind=SearchMatchModeKind.ALL_WITHIN_LINES, - line_count=MAX_SEARCH_MATCH_WINDOW_LINES + 1, - ), - ) - - with pytest.raises(MemoriesBackendError, match="exceeds result count"): - store.search_memories(queries=["x"], cursor="99") - - -def test_search_match_mode_from_wire_rejects_zero_line_count() -> None: - mode = SearchMatchMode.from_wire({"type": "all_within_lines", "line_count": 0}) - assert mode.line_count == 0 - - -def test_search_context_lines_clamped(tmp_path: Path) -> None: - store = _store(tmp_path) - lines = ( - "\n".join(f"line{i}" for i in range(10)) - + "\nneedle\n" - + "\n".join(f"tail{i}" for i in range(10)) - ) - (store.root / "big.md").write_text(lines, encoding="utf-8") - - out = store.search_memories( - queries=["needle"], context_lines=MAX_SEARCH_CONTEXT_LINES + 100 - ) - content_lines = out.matches[0].content.splitlines() - assert len(content_lines) <= 1 + 2 * MAX_SEARCH_CONTEXT_LINES - - -def test_dispatch_search_legacy_query_and_errors(tmp_path: Path, monkeypatch) -> None: - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(tmp_path / "memories")) - root = tmp_path / "memories" - root.mkdir() - (root / "note.md").write_text("findme here\n", encoding="utf-8") - ctx = ToolCallContext(cwd=tmp_path) - - legacy = dispatch_tool("memories.search", {"query": "findme"}, ctx=ctx) - assert not legacy.is_error - assert legacy.structured is not None - assert legacy.structured["matches"] - - empty = dispatch_tool("memories.search", {"queries": []}, ctx=ctx) - assert empty.is_error - assert "at least one query is required" in empty.content - - -def test_ad_hoc_note_path_and_validation(tmp_path: Path) -> None: - store = _store(tmp_path) - fname = "2026-05-23T10-11-12-test-note.md" - store.add_ad_hoc_note(filename=fname, note="remember me") - note_path = store.root / "extensions" / "ad_hoc" / "notes" / fname - assert note_path.is_file() - assert note_path.read_text(encoding="utf-8") == "remember me" - assert oct(note_path.stat().st_mode & 0o777) == oct(0o600) - - with pytest.raises(MemoriesBackendError, match="must use YYYY-MM-DDTHH-MM-SS"): - store.add_ad_hoc_note(filename="bad-name.md", note="x") - - with pytest.raises(MemoriesBackendError, match="must use YYYY-MM-DDTHH-MM-SS"): - store.add_ad_hoc_note( - filename="2026-05-23T10-11-12-evil/../escape.md", note="x" - ) - - -def test_ad_hoc_note_empty_content_rejected(tmp_path: Path) -> None: - store = _store(tmp_path) - fname = "2026-05-23T10-11-12-empty.md" - - with pytest.raises(MemoriesBackendError, match="must not be empty"): - store.add_ad_hoc_note(filename=fname, note="") - with pytest.raises(MemoriesBackendError, match="must not be empty"): - store.add_ad_hoc_note(filename=fname, note=" \n\t") - - assert not (store.root / "extensions" / "ad_hoc" / "notes" / fname).exists() - - -def test_ad_hoc_note_rejects_symlink_in_notes_dir(tmp_path: Path) -> None: - store = _store(tmp_path) - escape = tmp_path / "escape" - escape.mkdir() - (escape / "ad_hoc").mkdir() - (escape / "ad_hoc" / "notes").mkdir() - link = store.root / "extensions" - link.symlink_to(escape) - - with pytest.raises(MemoriesBackendError, match="symlink"): - store.add_ad_hoc_note(filename="2026-05-23T10-11-12-link.md", note="x") - - -def test_ad_hoc_note_content_too_large_rejected(tmp_path: Path) -> None: - store = _store(tmp_path) - fname = "2026-05-23T10-11-13-too-big.md" - oversized = "x" * (AD_HOC_NOTE_MAX_BYTES + 1) - - with pytest.raises(Exception, match="byte limit"): - store.add_ad_hoc_note(filename=fname, note=oversized) - - assert not (store.root / "extensions" / "ad_hoc" / "notes" / fname).exists() - - -def test_ad_hoc_note_duplicate_filename_rejected_without_overwrite( - tmp_path: Path, -) -> None: - store = _store(tmp_path) - fname = "2026-05-23T10-11-14-dup.md" - store.add_ad_hoc_note(filename=fname, note="first") - - with pytest.raises(Exception, match="already exists"): - store.add_ad_hoc_note(filename=fname, note="second") - - note_path = store.root / "extensions" / "ad_hoc" / "notes" / fname - assert note_path.read_text(encoding="utf-8") == "first" - - -def test_default_ad_hoc_filename_unique_for_identical_slug() -> None: - names = {default_ad_hoc_filename("same note") for _ in range(50)} - assert len(names) == 50 - - -def test_ad_hoc_note_concurrent_writes_do_not_conflict(tmp_path: Path) -> None: - store = _store(tmp_path) - errors: list[Exception] = [] - - def _add(i: int) -> None: - try: - store.add_ad_hoc_note( - filename=default_ad_hoc_filename("concurrent"), note=f"note {i}" - ) - except Exception as exc: # noqa: BLE001 - captured for assertion below - errors.append(exc) - - threads = [threading.Thread(target=_add, args=(i,)) for i in range(20)] - for t in threads: - t.start() - for t in threads: - t.join() - - assert not errors - notes_dir = store.root / "extensions" / "ad_hoc" / "notes" - assert len(list(notes_dir.iterdir())) == 20 - - -def test_dispatch_memories_wire(tmp_path: Path, monkeypatch) -> None: - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(tmp_path / "memories")) - ctx = ToolCallContext(cwd=tmp_path) - fname = "2026-05-23T12-00-00-remember-detail.md" - add = dispatch_tool( - "memories.add_ad_hoc_note", - {"filename": fname, "note": "user asked to remember"}, - ctx=ctx, - ) - assert not add.is_error - assert add.structured == {} - - listed = dispatch_tool( - "memories.list", {"path": "extensions/ad_hoc/notes"}, ctx=ctx - ) - assert not listed.is_error - assert listed.structured is not None - assert listed.structured["entries"] - - search = dispatch_tool( - "memories.search", - {"queries": ["remember"], "context_lines": 0}, - ctx=ctx, - ) - assert not search.is_error - assert search.structured is not None - assert search.structured["matches"] - - -def test_dispatch_add_ad_hoc_note_codex_wire_aliases( - tmp_path: Path, monkeypatch -) -> None: - monkeypatch.setenv("FORGE_MEMORIES_ROOT", str(tmp_path / "memories")) - ctx = ToolCallContext(cwd=tmp_path) - - auto = dispatch_tool( - "memories.add_ad_hoc_note", {"content": "remember via content"}, ctx=ctx - ) - assert not auto.is_error - notes_dir = tmp_path / "memories" / "extensions" / "ad_hoc" / "notes" - created = list(notes_dir.iterdir()) - assert len(created) == 1 - assert created[0].read_text(encoding="utf-8") == "remember via content" - - fname = "2026-05-23T12-01-00-named.md" - named = dispatch_tool( - "memories.add_ad_hoc_note", - {"content": "named note", "path": fname}, - ctx=ctx, - ) - assert not named.is_error - assert (notes_dir / fname).read_text(encoding="utf-8") == "named note" - - empty = dispatch_tool("memories.add_ad_hoc_note", {"content": " "}, ctx=ctx) - assert empty.is_error - assert "must not be empty" in empty.content diff --git a/tests/python/test_forge_p0_actors.py b/tests/python/test_forge_p0_actors.py deleted file mode 100644 index 25f337379..000000000 --- a/tests/python/test_forge_p0_actors.py +++ /dev/null @@ -1,142 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for Forge P0 Pulsing actors (inbox, supervisor, MCP hub, code registry).""" - -from __future__ import annotations - -import asyncio -import uuid - -import pytest - -import pulsing as pul -from pulsing.forge.event_inbox import ForgeEventInbox, ensure_forge_event_inbox -from pulsing.forge.events import ForgeEvent -from pulsing.forge.mcp.hub import McpHubActor, ensure_mcp_hub -from pulsing.forge.naming import ( - code_cell_registry_name, - forge_event_inbox_name, - mcp_hub_name, - worker_supervisor_name, -) -from pulsing.forge.code_mode.registry import ensure_code_cell_registry -from pulsing.forge.config import ToolWorkerConfig -from pulsing.forge.worker_supervisor import ForgeWorkerSupervisor - - -@pytest.mark.asyncio -async def test_forge_event_inbox_records_and_forwards() -> None: - host = f"forge_host_{uuid.uuid4().hex[:8]}" - received: dict[str, list] = {"side": [], "stream": []} - - @pul.remote - class _Host: - async def on_forge_side_effect(self, event: dict) -> None: - received["side"].append(dict(event)) - - async def on_forge_stream_event(self, event: dict) -> None: - received["stream"].append(dict(event)) - - await pul.init() - try: - await _Host.spawn(name=host, public=True) - inbox = await ensure_forge_event_inbox(host) - await asyncio.sleep(0.15) - await inbox.as_any().tell( - "on_forge_event", - ForgeEvent( - kind="plan_updated", - payload={"plan": [{"step": "a", "status": "pending"}]}, - ).to_dict(), - ) - await inbox.as_any().tell( - "on_forge_event", - ForgeEvent.exec_output_delta( - session_id=1, stream="pty", chunk="hi" - ).to_dict(), - ) - await asyncio.sleep(0.35) - events = await inbox.get_forge_events() - assert len(events) == 2 - assert len(received["side"]) == 1 - assert len(received["stream"]) == 1 - assert received["stream"][0]["kind"] == "exec_output_delta" - finally: - await pul.shutdown() - - -@pytest.mark.asyncio -async def test_forge_event_inbox_get_events() -> None: - host = f"forge_host_{uuid.uuid4().hex[:10]}" - await pul.init() - try: - inbox = await ForgeEventInbox.spawn(host, name=forge_event_inbox_name(host)) - await asyncio.sleep(0.1) - ev = ForgeEvent.tool_begin("Read", {"file_path": "x"}) - await inbox.as_any().tell("on_forge_event", ev.to_dict()) - await asyncio.sleep(0.15) - out = await inbox.get_forge_events() - assert len(out) == 1 - assert out[0]["kind"] == "tool_begin" - finally: - await pul.shutdown() - - -def test_forge_naming_helpers() -> None: - assert forge_event_inbox_name("craft/ws/ws1/alice") == "craft/ws/ws1/alice/events" - assert worker_supervisor_name("craft/ws/ws1/alice") == "craft/ws/ws1/alice/worker" - assert mcp_hub_name("ws1") == "craft/ws/ws1/_mcp_hub" - assert ( - code_cell_registry_name("craft/ws/ws1/alice") == "craft/ws/ws1/alice/code_cells" - ) - - -@pytest.mark.asyncio -async def test_mcp_hub_spawn_and_list() -> None: - ws = f"ws_{uuid.uuid4().hex[:8]}" - await pul.init() - try: - hub = await ensure_mcp_hub(ws, cwd=".") - await asyncio.sleep(0.1) - out = await hub.refresh() - assert out["ok"] is True - assert isinstance(out["tools"], list) - finally: - await pul.shutdown() - - -@pytest.mark.asyncio -async def test_code_cell_registry_exec() -> None: - host = f"forge_host_{uuid.uuid4().hex[:8]}" - - @pul.remote - class _ToolHost: - async def call_tool(self, name: str, kwargs: dict) -> dict: - if name == "Read": - return {"content": "file-body", "is_error": False} - return {"content": f"unknown {name}", "is_error": True} - - await pul.init() - try: - await _ToolHost.spawn(name=host, public=True) - reg = await ensure_code_cell_registry(host) - await asyncio.sleep(0.15) - source = 'text("ok")\n' - out = await reg.execute(source, host_name=host) - assert out["kind"] in {"result", "yielded"} - assert str(out["cell_id"]).startswith("cell-") - finally: - await pul.shutdown() - - -@pytest.mark.asyncio -async def test_worker_supervisor_spawn() -> None: - cfg = ToolWorkerConfig(cwd=".") - await pul.init() - try: - sup = ForgeWorkerSupervisor(cfg) - ping = await sup.ping() - assert ping.get("ok") is True - assert ping.get("kind") == "tool_worker" - await sup.close() - finally: - await pul.shutdown() diff --git a/tests/python/test_forge_p2p_events.py b/tests/python/test_forge_p2p_events.py deleted file mode 100644 index 828075399..000000000 --- a/tests/python/test_forge_p2p_events.py +++ /dev/null @@ -1,36 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for Forge P2P event transport.""" - -from __future__ import annotations - -from pulsing.forge.events import ForgeEvent, ForgeEventKind -from pulsing.forge.exec_output import ExecOutputDelta, ExecStream -from pulsing.forge.p2p_session import P2PToolSession -from pulsing.forge.runtime import LocalToolRuntime - - -def test_p2p_session_exec_delta() -> None: - received: list[ForgeEvent] = [] - session = P2PToolSession(emit=received.append) - session.on_exec_output_delta( - ExecOutputDelta(session_id=1, stream=ExecStream.PTY, chunk="hello") - ) - assert len(received) == 1 - assert received[0].kind == ForgeEventKind.EXEC_OUTPUT_DELTA.value - assert received[0].payload["chunk"] == "hello" - - -def test_local_runtime_exec_streams_via_p2p_session(tmp_path) -> None: - received: list[ForgeEvent] = [] - session = P2PToolSession(emit=received.append) - rt = LocalToolRuntime(cwd=str(tmp_path), session=session) - out = rt.call_tool( - "exec_command", - {"cmd": "echo stream_p2p", "yield_time_ms": 300, "tty": True}, - ) - assert not out.is_error - delta_kinds = [ - e.kind for e in received if e.kind == ForgeEventKind.EXEC_OUTPUT_DELTA.value - ] - assert delta_kinds - assert any("stream_p2p" in e.payload.get("chunk", "") for e in received) diff --git a/tests/python/test_forge_repl.py b/tests/python/test_forge_repl.py deleted file mode 100644 index 39dd2c340..000000000 --- a/tests/python/test_forge_repl.py +++ /dev/null @@ -1,100 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for Forge session REPL.""" - -from __future__ import annotations - -import json -from pathlib import Path - -from pulsing.forge.repl.parse import parse_line -from pulsing.forge.repl.session import ForgeReplSession -from pulsing.forge.repl.trace import TraceLog, TraceRecord, load_trace, save_trace - - -def test_parse_bare_tool_with_json() -> None: - cmd, args = parse_line('Read {"file_path": "README.md"}') - assert cmd == "call" - assert args["tool"] == "Read" - assert args["arguments"]["file_path"] == "README.md" - - -def test_parse_nu_flags() -> None: - cmd, args = parse_line("Glob --pattern *.py") - assert cmd == "call" - assert args["tool"] == "Glob" - assert args["arguments"]["pattern"] == "*.py" - - -def test_trace_roundtrip(tmp_path: Path) -> None: - log = TraceLog() - log.append( - TraceRecord( - seq=1, - kind="tool_call", - tool="Read", - arguments={"file_path": "a.txt"}, - result={"content": "hi", "is_error": False}, - ) - ) - path = tmp_path / "t.jsonl" - save_trace(path, log) - loaded = load_trace(path) - assert len(loaded.tool_calls()) == 1 - assert loaded.tool_calls()[0].tool == "Read" - - -def test_repl_call_read(tmp_path: Path) -> None: - f = tmp_path / "hello.txt" - f.write_text("world", encoding="utf-8") - session = ForgeReplSession(cwd=tmp_path) - out = session.call_tool("Read", {"file_path": "hello.txt"}) - assert not out.is_error - assert out.content == "world" - - -def test_replay_dry_run(tmp_path: Path) -> None: - log = TraceLog() - log.append( - TraceRecord( - seq=1, - kind="tool_call", - tool="Read", - arguments={"file_path": "x"}, - result={"content": "", "is_error": True}, - ) - ) - path = tmp_path / "replay.jsonl" - save_trace(path, log) - session = ForgeReplSession(cwd=tmp_path) - session.load_replay_trace(path) - msg = session.replay_step(dry_run=True) - assert "dry-run" in msg - assert "Read" in msg - - -def test_replay_verify_read(tmp_path: Path) -> None: - f = tmp_path / "a.txt" - f.write_text("same", encoding="utf-8") - log = TraceLog() - log.append( - TraceRecord( - seq=1, - kind="tool_call", - tool="Read", - arguments={"file_path": "a.txt"}, - result={"content": "same", "is_error": False}, - ) - ) - path = tmp_path / "v.jsonl" - save_trace(path, log) - session = ForgeReplSession(cwd=tmp_path) - session.load_replay_trace(path) - msg = session.replay_step(verify=True) - assert "[ok]" in msg - - -def test_session_table(tmp_path: Path) -> None: - session = ForgeReplSession(cwd=tmp_path, approval_mode="ask") - text = session.format_session_table() - assert "approval" in text - assert "ask" in text diff --git a/tests/python/test_forge_request_permissions.py b/tests/python/test_forge_request_permissions.py deleted file mode 100644 index 04a99de25..000000000 --- a/tests/python/test_forge_request_permissions.py +++ /dev/null @@ -1,122 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""request_permissions approval bridge and checker tests.""" - -from __future__ import annotations - -import pytest - -from pulsing.forge.approval_bridge import make_worker_permissions_callback -from pulsing.forge.permissions import ( - PermissionChecker, - is_permission_profile_effectively_empty, - is_permission_section_empty, -) -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE - - -def test_is_permission_section_empty_codex_shapes() -> None: - assert is_permission_section_empty({"enabled": None}) - assert is_permission_section_empty({"entries": []}) - assert is_permission_section_empty({"read": [], "write": []}) - assert not is_permission_section_empty({"enabled": True}) - assert not is_permission_section_empty({"write": ["subdir"]}) - - -def test_is_permission_profile_effectively_empty() -> None: - assert is_permission_profile_effectively_empty({}) - assert is_permission_profile_effectively_empty( - {"network": {"enabled": None}, "file_system": {"entries": []}} - ) - assert not is_permission_profile_effectively_empty({"network": {"enabled": True}}) - - -def test_worker_permissions_callback_requires_sink() -> None: - cb = make_worker_permissions_callback(None) - with pytest.raises(RuntimeError, match="approval sink"): - cb({"permissions": {"network": {"enabled": True}}}) - - -def test_worker_permissions_callback_rejects_empty_grant() -> None: - cb = make_worker_permissions_callback("fake-sink") - - def _fake_ask(_sink: str, _args: dict) -> dict: - return {"permissions": {"network": {"enabled": None}}, "scope": "turn"} - - import pulsing.forge.approval_bridge as bridge - - bridge.ask_request_permissions_sync = _fake_ask # type: ignore[assignment] - bridge.tell_forge_event_sync = lambda *_a, **_k: None # type: ignore[assignment] - with pytest.raises(RuntimeError, match="denied by host"): - cb({"permissions": {"network": {"enabled": True}}}) - - -def test_permission_checker_denies_request_permissions_without_callback() -> None: - checker = PermissionChecker(auto_approve=False) - out = checker.prompt_request_permissions( - {"permissions": {"network": {"enabled": True}}} - ) - assert out["permissions"] == {} - assert out["strict_auto_review"] is False - - -def test_permission_checker_prompt_callback_grants() -> None: - checker = PermissionChecker( - prompt_callback=lambda _tool, _summary: "allow", - ) - perms = {"network": {"enabled": True}} - out = checker.prompt_request_permissions({"permissions": perms}) - assert out["permissions"] == perms - assert out["scope"] == "session" - assert out["strict_auto_review"] is True - - -def test_permission_checker_auto_approves_request_permissions() -> None: - checker = PermissionChecker(auto_approve=True) - perms = {"network": {"enabled": True}} - out = checker.prompt_request_permissions({"permissions": perms}) - assert out["permissions"] == perms - assert out["scope"] == "session" - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_rust_rejects_empty_permissions_request() -> None: - from pulsing.forge.rust_runtime import RustForgeAdapter - - host = RustForgeAdapter.create( - cwd=".", - auto_approve=False, - event_callback=lambda _e: None, - request_permissions_callback=lambda _args: { - "permissions": {}, - "scope": "turn", - "strict_auto_review": False, - }, - ) - out = host.call_tool( - "request_permissions", - {"permissions": {"network": {"enabled": True}}}, - ) - assert out.is_error - assert "denied" in out.content.lower() - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_rust_rejects_empty_nested_permissions() -> None: - from pulsing.forge.rust_runtime import RustForgeAdapter - - host = RustForgeAdapter.create(cwd=".", auto_approve=False) - out = host.call_tool("request_permissions", {"permissions": {"network": {}}}) - assert out.is_error - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_rust_rejects_path_outside_cwd() -> None: - from pulsing.forge.rust_runtime import RustForgeAdapter - - host = RustForgeAdapter.create(cwd=".", auto_approve=False) - out = host.call_tool( - "request_permissions", - {"permissions": {"file_system": {"write": ["/etc/passwd"]}}}, - ) - assert out.is_error - assert "outside working directory" in out.content.lower() diff --git a/tests/python/test_forge_shell_approval.py b/tests/python/test_forge_shell_approval.py deleted file mode 100644 index 3a8f32404..000000000 --- a/tests/python/test_forge_shell_approval.py +++ /dev/null @@ -1,58 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Shell execpolicy + approval tests.""" - -from __future__ import annotations - -import pytest - -from pulsing.forge.permissions import PermissionChecker -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE - - -def test_permission_checker_auto_approves_exec() -> None: - checker = PermissionChecker(auto_approve=True) - assert ( - checker.prompt_exec_approval({"command": ["git", "reset", "--hard"]}) - == "approved" - ) - - -def test_permission_checker_denies_exec_without_callback() -> None: - checker = PermissionChecker(auto_approve=False) - assert checker.prompt_exec_approval({"command": ["echo", "x"]}) == "denied" - - -def test_permission_checker_exec_callback() -> None: - seen: list[dict] = [] - - def _cb(req: dict) -> str: - seen.append(req) - return "approved" - - checker = PermissionChecker(auto_approve=False, exec_approval_callback=_cb) - assert ( - checker.prompt_exec_approval({"command": ["curl", "example.com"]}) == "approved" - ) - assert seen[0]["command"] == ["curl", "example.com"] - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_rust_forbidden_git_reset_hard() -> None: - from pulsing.forge.rust_runtime import RustForgeAdapter - - host = RustForgeAdapter.create( - cwd=".", - auto_approve=True, - ) - out = host.call_tool("shell_command", {"command": "git reset --hard HEAD"}) - assert out.is_error - assert "forbidden" in out.content.lower() - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -def test_rust_exec_approval_blocks_without_callback() -> None: - from pulsing.forge.rust_runtime import RustForgeAdapter - - host = RustForgeAdapter.create(cwd=".", auto_approve=False) - out = host.call_tool("shell_command", {"command": "echo hello"}) - assert out.is_error diff --git a/tests/python/test_hybrid_forge_callable.py b/tests/python/test_hybrid_forge_callable.py deleted file mode 100644 index 90d3a9315..000000000 --- a/tests/python/test_hybrid_forge_callable.py +++ /dev/null @@ -1,82 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Backward-compatible wrapper — prefer tests/python/forge/test_gates.py.""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge.hybrid_runtime import HybridForgeRuntime -from pulsing.forge.integrated import FORGE_TOOL_NAMES -from pulsing.forge.rust_runtime import RUST_FORGE_AVAILABLE -from pulsing.testing.forge_harness import minimal_tool_args - -pytestmark = pytest.mark.forge - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -@pytest.mark.forge_l1 -def test_hybrid_all_tools_callable(tmp_path: Path) -> None: - rt = HybridForgeRuntime.create(cwd=str(tmp_path), auto_approve=True) - names = sorted(FORGE_TOOL_NAMES) - assert len(names) == 32 - failures: list[str] = [] - for name in names: - out = rt.call_tool(name, minimal_tool_args(name, tmp_path)) - if out.content.startswith("Unknown tool:"): - failures.append(name) - assert not failures, f"Unknown tool for: {failures}" - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -@pytest.mark.forge_l1 -def test_hybrid_mcp_list_resources(tmp_path: Path) -> None: - rt = HybridForgeRuntime.create(cwd=str(tmp_path), auto_approve=True) - out = rt.call_tool("list_mcp_resources", {}) - assert not out.content.startswith("Unknown tool:") - assert "MCP runtime is not initialized" not in out.content - assert "MCP runtime is not started" not in out.content - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -@pytest.mark.forge_l1 -def test_hybrid_list_mcp_resource_templates_validates_args(tmp_path: Path) -> None: - rt = HybridForgeRuntime.create(cwd=str(tmp_path), auto_approve=True) - missing_server = rt.call_tool("list_mcp_resource_templates", {}) - assert missing_server.is_error - assert "server is required" in missing_server.content - - empty_server = rt.call_tool("list_mcp_resource_templates", {"server": " "}) - assert empty_server.is_error - assert "server must be a non-empty string" in empty_server.content - - wired = rt.call_tool( - "list_mcp_resource_templates", - {"server": "demo"}, - ) - assert not wired.content.startswith("Unknown tool:") - assert "MCP runtime is not initialized" not in wired.content - - -@pytest.mark.skipif(not RUST_FORGE_AVAILABLE, reason="requires maturin develop") -@pytest.mark.forge_l1 -def test_hybrid_read_mcp_resource_validates_args(tmp_path: Path) -> None: - rt = HybridForgeRuntime.create(cwd=str(tmp_path), auto_approve=True) - missing_server = rt.call_tool("read_mcp_resource", {"uri": "file:///dev/null"}) - assert missing_server.is_error - assert "server is required" in missing_server.content - - bad_uri = rt.call_tool( - "read_mcp_resource", - {"server": "demo", "uri": "not-a-uri"}, - ) - assert bad_uri.is_error - assert "invalid uri" in bad_uri.content.lower() - - wired = rt.call_tool( - "read_mcp_resource", - {"server": "demo", "uri": "file:///dev/null"}, - ) - assert not wired.content.startswith("Unknown tool:") - assert "MCP runtime is not initialized" not in wired.content diff --git a/tests/python/test_permissions_modes.py b/tests/python/test_permissions_modes.py deleted file mode 100644 index 1411f3e74..000000000 --- a/tests/python/test_permissions_modes.py +++ /dev/null @@ -1,38 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Permission checks.""" - -from __future__ import annotations - -from pulsing.agent.loop.permissions import PermissionChecker -from pulsing.agent.loop.tools_pkg import ReadTool, WriteTool - - -def test_auto_approve_allows_write() -> None: - c = PermissionChecker(auto_approve=True) - w = WriteTool() - assert c.check(w, {"file_path": "/tmp/x", "content": "y"}) == "allow" - - -def test_read_only_allowed_without_auto_approve() -> None: - c = PermissionChecker(auto_approve=False) - r = ReadTool() - assert c.check(r, {"file_path": "/etc/hosts"}) == "allow" - - -def test_write_denied_without_auto_approve() -> None: - c = PermissionChecker(auto_approve=False) - w = WriteTool() - assert c.check(w, {"file_path": "/tmp/x", "content": "y"}) == "deny" - - -def test_prompt_callback_once() -> None: - calls = {"n": 0} - - def cb(_tool: str, _summary: str) -> str: - calls["n"] += 1 - return "once" if calls["n"] == 1 else "deny" - - c = PermissionChecker(prompt_callback=cb) - w = WriteTool() - assert c.check(w, {"file_path": "/tmp/x", "content": "y"}) == "allow" - assert c.check(w, {"file_path": "/tmp/x", "content": "z"}) == "deny" diff --git a/tests/python/test_pulsing_cli_helpers.py b/tests/python/test_pulsing_cli_helpers.py index 46a71371f..5554b80b9 100644 --- a/tests/python/test_pulsing_cli_helpers.py +++ b/tests/python/test_pulsing_cli_helpers.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""Tests for pulsing top-level CLI helpers.""" +"""Tests for actor CLI argument forwarding.""" from __future__ import annotations @@ -10,18 +10,18 @@ def test_rewrite_actor_argv_injects_extra_kwargs() -> None: argv = [ "pulsing", "actor", - "pkg.Cls", + "pkg.Counter", "--addr", "0.0.0.0:8000", "--", - "--model_name", - "gpt2", + "--initial", + "10", ] out = rewrite_actor_argv(argv) assert out[1] == "actor" assert "-D" in out assert "actor.extra_kwargs" in out[-1] - assert "model_name" in out[-1] + assert "initial" in out[-1] def test_rewrite_actor_argv_unchanged_without_dash_dash() -> None: diff --git a/tests/python/test_pulsing_forge.py b/tests/python/test_pulsing_forge.py deleted file mode 100644 index e861f5781..000000000 --- a/tests/python/test_pulsing_forge.py +++ /dev/null @@ -1,168 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for pulsing.forge (independent of Craft).""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.forge import ( - LocalToolRuntime, - LocalToolSession, - PlanItem, - StepStatus, - ToolResult, - UpdatePlanArgs, -) - - -def test_local_read(tmp_path: Path) -> None: - p = tmp_path / "x.txt" - p.write_text("hi", encoding="utf-8") - rt = LocalToolRuntime(cwd=str(tmp_path)) - out = rt.call_tool("Read", {"file_path": str(p)}) - assert out == ToolResult(content="hi") - - -def test_local_glob(tmp_path: Path) -> None: - (tmp_path / "a.py").write_text("1", encoding="utf-8") - rt = LocalToolRuntime(cwd=str(tmp_path)) - out = rt.call_tool("Glob", {"pattern": "*.py", "path": str(tmp_path)}) - assert "a.py" in out.content - - -def test_shell_command_codex_args(tmp_path: Path) -> None: - rt = LocalToolRuntime(cwd=str(tmp_path)) - out = rt.call_tool( - "shell_command", - {"command": "echo hi", "workdir": str(tmp_path), "timeout_ms": 5000}, - ) - assert not out.is_error - assert "hi" in out.content - - -def test_exec_command_session(tmp_path: Path) -> None: - rt = LocalToolRuntime(cwd=str(tmp_path)) - out = rt.call_tool( - "exec_command", - {"cmd": "sleep 1 && echo done", "yield_time_ms": 300, "tty": False}, - ) - assert not out.is_error - assert out.structured is not None - - -def test_exec_command_pty_and_streaming(tmp_path: Path) -> None: - session = LocalToolSession() - rt = LocalToolRuntime(cwd=str(tmp_path), session=session) - out = rt.call_tool( - "exec_command", - {"cmd": "echo pty_ok", "yield_time_ms": 300, "tty": True}, - ) - assert not out.is_error - assert out.structured is not None - assert "pty_ok" in (out.structured.get("output") or "") - assert session.exec_deltas - - -def test_runtime_close_kills_background_exec_sessions(tmp_path: Path) -> None: - """Long-running exec_command sessions must not survive runtime teardown.""" - for tty in (False, True): - rt = LocalToolRuntime(cwd=str(tmp_path)) - out = rt.call_tool( - "exec_command", - {"cmd": "sleep 30", "yield_time_ms": 100, "tty": tty}, - ) - assert out.structured is not None - session_id = out.structured.get("session_id") - assert session_id is not None - session = rt.context.exec._sessions[session_id] - if tty: - assert session.pty is not None - proc = session.pty.proc - assert session.pty.poll() is None - else: - proc = session.proc - assert proc is not None - assert proc.poll() is None - - rt.close() - - assert proc.poll() is not None - assert not rt.context.exec._sessions - - -def test_view_image_structured(tmp_path: Path) -> None: - # minimal 1x1 PNG - p = tmp_path / "x.png" - p.write_bytes( - bytes.fromhex( - "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489" - "0000000a49444154789c630001000005000108d4a7e00000000049454e44ae426082" - ) - ) - rt = LocalToolRuntime(cwd=str(tmp_path)) - out = rt.call_tool("view_image", {"path": str(p), "detail": "high"}) - assert not out.is_error - assert out.structured is not None - items = out.structured.get("content_items") or [] - assert items and items[0]["type"] == "input_image" - assert str(items[0]["image_url"]).startswith("data:image/") - - -def test_apply_patch_add_file(tmp_path: Path) -> None: - rt = LocalToolRuntime(cwd=str(tmp_path)) - patch = "*** Begin Patch\n*** Add File: hello.txt\n+hello world\n*** End Patch\n" - out = rt.call_tool("apply_patch", {"patch": patch}) - assert not out.is_error - assert (tmp_path / "hello.txt").read_text(encoding="utf-8") == "hello world\n" - - -def test_update_plan_session(tmp_path: Path) -> None: - session = LocalToolSession() - rt = LocalToolRuntime(cwd=str(tmp_path), session=session) - out = rt.call_tool( - "update_plan", - {"plan": [{"step": "one", "status": "pending"}]}, - ) - assert not out.is_error - assert session.plan == [PlanItem(step="one", status=StepStatus.PENDING)] - - -def test_new_context_session(tmp_path: Path) -> None: - session = LocalToolSession() - rt = LocalToolRuntime(cwd=str(tmp_path), session=session) - out = rt.call_tool("new_context", {}) - assert not out.is_error - assert session.new_context_requested is True - - -def test_forge_environment_entrypoint(tmp_path: Path) -> None: - from pulsing.forge import ForgeEnvironment - - env = ForgeEnvironment.ephemeral(cwd=str(tmp_path)) - out = env.runtime().call_tool( - "shell_command", {"cmd": "echo ok", "workdir": str(tmp_path)} - ) - assert not out.is_error - assert "ok" in out.content - - -@pytest.mark.asyncio -async def test_tool_worker_actor_spawn() -> None: - import pulsing as pul - from pulsing.forge import ToolWorkerActor, ToolWorkerConfig - - await pul.init() - try: - worker = await ToolWorkerActor.spawn( - config=ToolWorkerConfig(cwd="."), - public=False, - ) - pong = await worker.ping() - assert pong.get("ok") is True - out = await worker.Read(file_path="README.md") - assert isinstance(out, dict) - assert "content" in out - finally: - await pul.shutdown() diff --git a/tests/python/test_sandbox_policy.py b/tests/python/test_sandbox_policy.py deleted file mode 100644 index 2df2db640..000000000 --- a/tests/python/test_sandbox_policy.py +++ /dev/null @@ -1,65 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -from pulsing.forge.sandbox import build_bash_exec, normalize_policy - - -def test_normalize_policy() -> None: - assert normalize_policy(None) == "off" - assert normalize_policy("restricted") == "restricted" - assert normalize_policy("bwrap") == "bwrap" - assert normalize_policy("bogus") == "off" - - -def test_build_bash_exec_off_uses_sh_c() -> None: - argv, env, label = build_bash_exec( - "echo hi", - cwd="/tmp", - policy="off", - dangerously_disable_sandbox=False, - timeout=5, - ) - assert argv[:3] == ["/bin/sh", "-c", "echo hi"] - assert env is None - assert "sandbox=off" in label or "shell" in label - - -def test_effective_shell_policy_require_escalated() -> None: - from pulsing.forge.context import ToolCallContext - from pulsing.forge.handlers import _effective_shell_policy - - ctx = ToolCallContext(cwd=Path("."), sandbox_policy="restricted") - args = {"sandbox_permissions": "require_escalated"} - assert _effective_shell_policy(ctx, args, "restricted") == "off" - - -def test_login_restricted_policy_still_clears_env() -> None: - """Regression: login=true must not bypass the restricted-env wrapper.""" - argv, env, label = build_bash_exec( - "echo hi", - cwd="/tmp", - policy="restricted", - dangerously_disable_sandbox=False, - timeout=5, - login=True, - ) - assert argv[0] == "env" - assert argv[1] == "-i" - assert env is not None - assert "-lc" in argv - assert "restricted env" in label - - -def test_login_off_policy_uses_bash_lc() -> None: - argv, env, label = build_bash_exec( - "echo hi", - cwd="/tmp", - policy="off", - dangerously_disable_sandbox=False, - timeout=5, - login=True, - ) - assert argv == ["bash", "-lc", "echo hi"] - assert env is None - assert "sandbox=off" in label diff --git a/tests/python/test_workflow_context.py b/tests/python/test_workflow_context.py index 4dccefed7..88c6ab0fb 100644 --- a/tests/python/test_workflow_context.py +++ b/tests/python/test_workflow_context.py @@ -12,7 +12,7 @@ def test_init_scaffolds_workflows(tmp_path: Path) -> None: - init_workspace(tmp_path, template="minimal", seed_npcs=False) + init_workspace(tmp_path, template="minimal") workflows = tmp_path / ".pulsing" / "workflows" assert (workflows / "README.md").is_file() assert (workflows / "example.py").is_file() @@ -22,7 +22,7 @@ def test_init_scaffolds_workflows(tmp_path: Path) -> None: def test_workflow_context_checkpoint(tmp_path: Path) -> None: - init_workspace(tmp_path, template="minimal", seed_npcs=False) + init_workspace(tmp_path, template="minimal") (tmp_path / "note.txt").write_text("v1", encoding="utf-8") ctx = WorkflowContext(root=tmp_path) @@ -36,7 +36,7 @@ def test_workflow_context_checkpoint(tmp_path: Path) -> None: def test_workflow_run_sync(tmp_path: Path) -> None: - init_workspace(tmp_path, template="minimal", seed_npcs=False) + init_workspace(tmp_path, template="minimal") seen: list[str] = [] def main(ctx: WorkflowContext) -> None: @@ -47,7 +47,7 @@ def main(ctx: WorkflowContext) -> None: def test_workflow_run_async(tmp_path: Path) -> None: - init_workspace(tmp_path, template="minimal", seed_npcs=False) + init_workspace(tmp_path, template="minimal") seen: list[str] = [] async def main(ctx: WorkflowContext) -> None: diff --git a/tests/python/test_workspace_init_guide.py b/tests/python/test_workspace_init_guide.py deleted file mode 100644 index 469beea80..000000000 --- a/tests/python/test_workspace_init_guide.py +++ /dev/null @@ -1,40 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for LLM-guided ``pulsing init``.""" - -from __future__ import annotations - -import json -from pathlib import Path - -import pytest - -from pulsing.workspace.bootstrap import init_workspace -from pulsing.workspace.init_guide import run_init_guide - - -@pytest.mark.asyncio -async def test_init_stores_guide_in_manifest(tmp_path: Path) -> None: - init_workspace( - tmp_path, - template="minimal", - seed_npcs=False, - guide="Python ML project with pytest", - provider="demo", - model="demo", - ) - data = json.loads((tmp_path / ".pulsing" / "workspace.json").read_text()) - assert data.get("init_guide") == "Python ML project with pytest" - - -@pytest.mark.asyncio -async def test_init_guide_demo_writes_readme(tmp_path: Path) -> None: - init_workspace(tmp_path, template="minimal", seed_npcs=False, guide=None) - await run_init_guide( - tmp_path, - "Create README.md describing a minimal Python CLI tool with pytest", - provider="demo", - model="demo", - ) - readme = tmp_path / "README.md" - assert readme.is_file() - assert readme.read_text(encoding="utf-8") diff --git a/tests/python/test_workspace_journal.py b/tests/python/test_workspace_journal.py index 79d6c024f..519eaac3e 100644 --- a/tests/python/test_workspace_journal.py +++ b/tests/python/test_workspace_journal.py @@ -19,7 +19,7 @@ def test_init_checkpoint_rollback_roundtrip( monkeypatch.chdir(tmp_path) (tmp_path / "hello.txt").write_text("v1", encoding="utf-8") - result = init_workspace(template="minimal", seed_npcs=False) + result = init_workspace(template="minimal") assert result.created assert (tmp_path / ".pulsing" / "cluster.json").is_file() assert (tmp_path / ".pulsing" / "workspace.json").is_file() @@ -39,7 +39,7 @@ def test_init_checkpoint_rollback_roundtrip( def test_init_idempotent(tmp_path: Path) -> None: - first = init_workspace(tmp_path, template="minimal", seed_npcs=False) - second = init_workspace(tmp_path, template="minimal", seed_npcs=False) + first = init_workspace(tmp_path, template="minimal") + second = init_workspace(tmp_path, template="minimal") assert first.created assert not second.created diff --git a/tests/python/test_workspace_minimal_demo.py b/tests/python/test_workspace_minimal_demo.py deleted file mode 100644 index 180d6f5c5..000000000 --- a/tests/python/test_workspace_minimal_demo.py +++ /dev/null @@ -1,24 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Smoke test for workspace_minimal_demo (offline demo LLM).""" - -from __future__ import annotations - -from pathlib import Path - -import pytest - -from pulsing.workspace.minimal_demo import run_workspace_minimal_demo - - -@pytest.mark.asyncio -async def test_workspace_minimal_demo_offline(tmp_path: Path) -> None: - out = await run_workspace_minimal_demo( - tmp_path, - message="list project files with Glob", - provider="demo", - ) - text = str(out.get("assistant_text") or out.get("error") or "") - assert text - assert out.get("error") is None - assert (tmp_path / ".pulsing" / "cluster.json").is_file() - assert (tmp_path / ".pulsing" / "history" / "HEAD").is_file() diff --git a/tests/rust/README.md b/tests/rust/README.md index e1ba68f3a..f2a09de05 100644 --- a/tests/rust/README.md +++ b/tests/rust/README.md @@ -6,15 +6,12 @@ Rust tests are located in the respective crates: # Run pulsing-actor unit tests cargo test -p pulsing-actor -# Run pulsing-bench unit tests -cargo test -p pulsing-bench - # Run all tests -cargo test --workspace +cargo test --workspace --exclude pulsing-py ``` ## Test Locations - `crates/pulsing-actor/src/**/*.rs` - Unit tests (inline `#[cfg(test)]` modules) - `crates/pulsing-actor/tests/` - Integration tests -- `crates/pulsing-bench/src/**/*.rs` - Unit tests +- `crates/pulsing-workspace/src/` - Workspace journal tests