Skip to content

Add pi coding agent tool#362

Merged
ModerRAS merged 3 commits into
masterfrom
codex/rmux-pi-coding-agent
Jun 1, 2026
Merged

Add pi coding agent tool#362
ModerRAS merged 3 commits into
masterfrom
codex/rmux-pi-coding-agent

Conversation

@ModerRAS

@ModerRAS ModerRAS commented May 31, 2026

Copy link
Copy Markdown
Owner

Summary

  • add run/get/cancel coding-agent tools backed by Redis job state and Telegram chat whitelist/path guardrails
  • add a Rust coding-agent sidecar that consumes coding jobs, runs pi RPC sessions, and posts reports
  • resume the LLM loop automatically after sidecar reports, with bilingual docs and focused tests

Validation

  • dotnet test TelegramSearchBot.Test/TelegramSearchBot.Test.csproj --filter FullyQualifiedName~CodingAgentToolServiceTests --no-restore --verbosity minimal
  • dotnet build TelegramSearchBot.sln --no-restore --configuration Debug
  • cargo fmt --manifest-path TelegramSearchBot.CodingAgentSidecar/Cargo.toml -- --check
  • cargo test --manifest-path TelegramSearchBot.CodingAgentSidecar/Cargo.toml

Summary by CodeRabbit

  • New Features

    • Coding Agent Tool enabling background job execution with configurable timeouts and resource controls
    • Job status tracking and cancellation capabilities for created jobs
    • Automated completion notifications with optional LLM loop resumption
  • Documentation

    • Added comprehensive Coding Agent Tool configuration and workflow guide
    • Updated tool documentation with job management specifications
  • Tests

    • Added coverage for Coding Agent Tool functionality and validation

@coderabbitai

coderabbitai Bot commented May 31, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ModerRAS, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 42 minutes and 50 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 703b5967-bacd-4b31-b3d5-38061b11e6e3

📥 Commits

Reviewing files that changed from the base of the PR and between 9898ced and af2fac8.

⛔ Files ignored due to path filters (1)
  • TelegramSearchBot.CodingAgentSidecar/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (17)
  • .gitignore
  • Docs/README_CodingAgentTool.md
  • Docs/README_MCP.md
  • TelegramSearchBot.CodingAgentSidecar/Cargo.toml
  • TelegramSearchBot.CodingAgentSidecar/README.md
  • TelegramSearchBot.CodingAgentSidecar/src/main.rs
  • TelegramSearchBot.Common/Env.cs
  • TelegramSearchBot.Common/Model/AI/LlmAgentContracts.cs
  • TelegramSearchBot.LLM/Service/Tools/CodingAgentJobService.cs
  • TelegramSearchBot.LLM/Service/Tools/CodingAgentPathPolicy.cs
  • TelegramSearchBot.LLM/Service/Tools/CodingAgentToolService.cs
  • TelegramSearchBot.Test/Service/AI/LLM/CodingAgentToolServiceTests.cs
  • TelegramSearchBot.Test/Service/AI/LLM/InMemoryRedisTestHarness.cs
  • TelegramSearchBot/Extension/ServiceCollectionExtension.cs
  • TelegramSearchBot/Service/AI/LLM/CodingAgentReportConsumer.cs
  • TelegramSearchBot/Service/AI/LLM/CodingAgentSidecarLauncherService.cs
  • TelegramSearchBot/Service/AI/LLM/LLMTaskQueueService.cs
📝 Walkthrough

Walkthrough

This PR introduces a complete coding-agent feature enabling background code execution tasks. The LLM enqueues jobs via run_coding_agent, a Rust sidecar process consumes jobs from Redis, executes pi --mode rpc with optional multi-agent support, and publishes results. The main process consumes reports, sends Telegram messages, and auto-continues the LLM session with iteration-limit resumption. Changes include configuration, job lifecycle contracts, path validation, tool exposure, a complete Rust sidecar, report consumption with LLM auto-continuation, DI wiring, and comprehensive tests and documentation.

Changes

Coding Agent Feature

Layer / File(s) Summary
Configuration Schema and Job Contracts
TelegramSearchBot.Common/Env.cs, TelegramSearchBot.Common/Model/AI/LlmAgentContracts.cs
New configuration schema loading coding-agent settings (enabled flag, group allowlist, denied paths, timeouts, concurrency limits, command names). Job status enum, request/report DTOs, and Redis key constants define the feature contract across C# and Rust.
Workspace Path Validation
TelegramSearchBot.LLM/Service/Tools/CodingAgentPathPolicy.cs
Path policy validates and normalizes workspace directories: expands environment variables and home-directory shortcuts (~, ~/, ~\), checks existence, rejects root paths and denied prefixes with platform-aware case sensitivity.
Job Queueing and State Management
TelegramSearchBot.LLM/Service/Tools/CodingAgentJobService.cs
Redis-backed service that enqueues jobs (enforcing concurrent-job limits via Redis sets), retrieves job state as a case-insensitive dictionary, and manages cancellation with chat-id ownership verification.
LLM Tool Service Entry Points
TelegramSearchBot.LLM/Service/Tools/CodingAgentToolService.cs
Three tools exposed to the LLM: run_coding_agent (validates input and enqueues), get_coding_agent_job (fetches state), and cancel_coding_agent_job (requests cancellation). Enforces group-id allowlist and chat ownership.
Rust Sidecar: Job Consumption and Execution
TelegramSearchBot.CodingAgentSidecar/Cargo.toml, TelegramSearchBot.CodingAgentSidecar/src/main.rs
Complete Rust implementation that pulls jobs from Redis, executes pi --mode rpc with RPC stdin/stdout protocol, parses JSONL output, supports optional multi-agent sequential execution, monitors timeout/cancellation via Redis, and publishes reports back. Includes per-job logging, session management, and unit tests.
Report Consumption and LLM Auto-Continuation
TelegramSearchBot/Service/AI/LLM/CodingAgentReportConsumer.cs, TelegramSearchBot/Service/AI/LLM/LLMTaskQueueService.cs
Background service consuming job reports from Redis, sending formatted Telegram messages with job metadata, and auto-continuing LLM sessions via task-queue orchestration or in-process execution. Handles iteration-limit resumption, bot identity resolution, and concurrent processing.
Process Launch, Wiring, and Integration
TelegramSearchBot/Service/AI/LLM/CodingAgentSidecarLauncherService.cs, TelegramSearchBot/Extension/ServiceCollectionExtension.cs
Hosted service managing sidecar process startup/shutdown with CLI path resolution and logging. Dependency injection wiring registers job service, path policy, tool service, sidecar launcher, and report consumer.
Tests, Documentation, and Build Configuration
TelegramSearchBot.Test/Service/AI/LLM/CodingAgentToolServiceTests.cs, TelegramSearchBot.Test/Service/AI/LLM/InMemoryRedisTestHarness.cs, Docs/README_CodingAgentTool.md, Docs/README_MCP.md, .gitignore
Test suite covering path validation, job enqueue persistence, tool access control, and allowlist enforcement. Test infrastructure adds Redis set mocking. User-facing documentation describes workflow, configuration, build steps, and multi-agent semantics. Build artifact rules updated for Rust sidecar.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • ModerRAS/TelegramSearchBot#350: Introduces IBotIdentityProvider abstraction for bot identity, which the report consumer directly depends on to resolve bot username before auto-continuing the LLM session.
  • ModerRAS/TelegramSearchBot#265: Establishes Redis agent contracts and process-separation plumbing (LlmAgentContracts.cs, Env.cs); this PR builds on that foundation by adding coding-agent job/report DTOs and keys to the same contract space.

Poem

🐰 A rabbit's ode to background tasks

From prompt to sidecar, jobs take flight,
Rust echoes back through Redis' light,
Reports flow in, continuations bloom—
The LLM never leaves the room.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.93% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'Add pi coding agent tool' accurately summarizes the main change: introducing new coding agent functionality with pi integration, as evidenced by the new CodingAgentToolService, supporting infrastructure, and Rust sidecar.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/rmux-pi-coding-agent

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented May 31, 2026

Copy link
Copy Markdown
Contributor

PR Check Report

Summary

Test Results

Platform Status Details
Ubuntu Passed Tests passed, artifacts uploaded
Windows Passed Tests passed, artifacts uploaded

Code Quality

  • Code formatting check
  • Security vulnerability scan
  • Dependency analysis
  • Code coverage collection

Test Artifacts

  • Test results artifacts count: 2
  • Code coverage uploaded to Codecov

Links


This report is auto-generated by GitHub Actions

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@TelegramSearchBot.Common/Env.cs`:
- Around line 220-227: The current deduplication uses
StringComparer.OrdinalIgnoreCase in ResolveCodingAgentDeniedPathPrefixes which
collapses distinct paths on case-sensitive OSes; change the Distinct comparer to
an OS-aware comparer that matches CodingAgentPathPolicy.GetPathComparison() so
deduplication follows the same case-sensitivity rules used later (e.g.,
construct or select a StringComparer based on
CodingAgentPathPolicy.GetPathComparison() and use that in Distinct), ensuring
ResolveCodingAgentDeniedPathPrefixes and
CodingAgentPathPolicy.GetPathComparison() treat path casing consistently.

In `@TelegramSearchBot.LLM/Service/Tools/CodingAgentJobService.cs`:
- Around line 30-55: The current concurrency gate uses separate calls
(SetLengthAsync and SetAddAsync) so two callers can race; replace the separate
check/add/queue sequence with a single Redis-side atomic operation (use a Lua
script via IDatabase.ScriptEvaluate or a MULTI/EXEC transaction) that performs:
check the size of LlmAgentRedisKeys.CodingAgentActiveJobSet (SCARD), if below
Env.CodingAgentMaxConcurrentJobs then SADD the request.JobId into
CodingAgentActiveJobSet, HSET the stateKey (same fields written by
HashSetAsync), set the key TTL (EXPIRE StateTtl), and LPUSH (or RPUSH consistent
with ListLeftPushAsync) the payload into LlmAgentRedisKeys.CodingAgentJobQueue,
returning success/failure; update code around SetLengthAsync, HashSetAsync,
KeyExpireAsync, SetAddAsync, and ListLeftPushAsync to call this script and
handle the failure path (throw InvalidOperationException when script returns
"limit reached").

In `@TelegramSearchBot.LLM/Service/Tools/CodingAgentToolService.cs`:
- Around line 10-11: The CodingAgentToolService class is currently registered
with
[Injectable(Microsoft.Extensions.DependencyInjection.ServiceLifetime.Transient)]
but must follow the repository convention for IService implementations and be
registered as a singleton; update the attribute on the CodingAgentToolService
class (the Injectable attribute applied to class CodingAgentToolService) to use
ServiceLifetime.Singleton so the DI scanner treats this IService implementation
as a singleton.

In `@TelegramSearchBot.RmuxSidecar/src/main.rs`:
- Around line 133-139: The BRPOP call currently uses .await? which will
propagate any Redis error out of main; instead wrap the BRPOP/query_async call
in error handling: if query_async on queue_conn returns an Err, log the error
(including context like "BRPOP failed"), drop/close the existing queue_conn,
attempt to recreate it by calling
client.get_multiplexed_async_connection().await in a small retry/backoff loop,
and then continue the outer loop to resume consuming jobs; keep the successful
path returning Some((String,String)) unchanged so only transient Redis errors
trigger reconnect and not process exit (refer to queue_conn,
client.get_multiplexed_async_connection, BRPOP and JOB_QUEUE).
- Around line 165-310: process_job can return early after setting the job
Running and leave state/report/cleanup incomplete; wrap the main work in a
fallible inner block (e.g. an async closure or helper run_core) that returns the
final_status, error_message, outputs, rmux_session_names and report payload,
then in a guaranteed outer finally/cleanup section (after the inner block
completes or errors) perform the terminal update_state call, push the final
CodingAgentJobReport to REPORT_QUEUE, call cleanup_job, and append the final log
line; ensure you reference and use the existing functions/symbols update_state,
cleanup_job, CodingAgentJobReport, REPORT_QUEUE, append_line and the local
variables started_at/log_path/request.job_id so the finalization always runs
even if the inner block returns Err early.

In `@TelegramSearchBot/Service/AI/LLM/CodingAgentReportConsumer.cs`:
- Around line 55-58: The consumer's loop in CodingAgentReportConsumer is letting
a malformed JSON payload throw and fault the BackgroundService; wrap the
JsonConvert.DeserializeObject<CodingAgentJobReport>(payload) call (and the
second DeserializeObject usage around lines 70-75) in a try/catch that catches
JsonException/Exception, log the payload and error via the existing logger, and
continue the loop instead of allowing the exception to escape; ensure you only
rethrow OperationCanceledException/RedisException as before and keep the rest of
the loop resilient to bad payloads.
- Around line 212-218: The report currently exposes local filesystem details by
appending report.WorkingDirectory and report.LogPath directly in
CodingAgentReportConsumer; remove or redact these fields before sending to
Telegram: stop calling sb.AppendLine for report.WorkingDirectory and
report.LogPath (or replace them with a job-scoped identifier such as a short
hash or the directory basename) and keep non-sensitive fields like
report.RmuxSessionNames unchanged (e.g., use string.Join on
report.RmuxSessionNames as already done). Ensure any redaction logic is applied
where Workspace (report.WorkingDirectory) and Log (report.LogPath) are formatted
so no absolute paths are emitted.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8f97d202-e7d5-4861-830d-14216870d72e

📥 Commits

Reviewing files that changed from the base of the PR and between 0023b10 and b963802.

⛔ Files ignored due to path filters (1)
  • TelegramSearchBot.RmuxSidecar/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (17)
  • .gitignore
  • Docs/README_CodingAgentTool.md
  • Docs/README_MCP.md
  • TelegramSearchBot.Common/Env.cs
  • TelegramSearchBot.Common/Model/AI/LlmAgentContracts.cs
  • TelegramSearchBot.LLM/Service/Tools/CodingAgentJobService.cs
  • TelegramSearchBot.LLM/Service/Tools/CodingAgentPathPolicy.cs
  • TelegramSearchBot.LLM/Service/Tools/CodingAgentToolService.cs
  • TelegramSearchBot.RmuxSidecar/Cargo.toml
  • TelegramSearchBot.RmuxSidecar/README.md
  • TelegramSearchBot.RmuxSidecar/src/main.rs
  • TelegramSearchBot.Test/Service/AI/LLM/CodingAgentToolServiceTests.cs
  • TelegramSearchBot.Test/Service/AI/LLM/InMemoryRedisTestHarness.cs
  • TelegramSearchBot/Extension/ServiceCollectionExtension.cs
  • TelegramSearchBot/Service/AI/LLM/CodingAgentReportConsumer.cs
  • TelegramSearchBot/Service/AI/LLM/LLMTaskQueueService.cs
  • TelegramSearchBot/Service/AI/LLM/RmuxSidecarLauncherService.cs

Comment thread TelegramSearchBot.Common/Env.cs
Comment thread TelegramSearchBot.LLM/Service/Tools/CodingAgentJobService.cs Outdated
Comment thread TelegramSearchBot.LLM/Service/Tools/CodingAgentToolService.cs Outdated
Comment thread TelegramSearchBot.CodingAgentSidecar/src/main.rs Outdated
Comment thread TelegramSearchBot.CodingAgentSidecar/src/main.rs Outdated
Comment thread TelegramSearchBot/Service/AI/LLM/CodingAgentReportConsumer.cs Outdated
Comment thread TelegramSearchBot/Service/AI/LLM/CodingAgentReportConsumer.cs Outdated
@ModerRAS ModerRAS changed the title Add rmux pi coding agent tool Add pi coding agent tool Jun 1, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
TelegramSearchBot.CodingAgentSidecar/src/main.rs (1)

624-635: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Write each log line in a single append.

append_line() does two separate writes, while run_agent() and the stderr task can append to the same file concurrently. That can interleave bytes across lines and make job logs unreadable.

Proposed fix
 async fn append_line(path: &Path, line: &str) -> Result<()> {
     if let Some(parent) = path.parent() {
         tokio::fs::create_dir_all(parent).await?;
     }
     let mut file = tokio::fs::OpenOptions::new()
         .create(true)
         .append(true)
         .open(path)
         .await?;
-    file.write_all(line.as_bytes()).await?;
-    file.write_all(b"\n").await?;
+    let mut buffer = Vec::with_capacity(line.len() + 1);
+    buffer.extend_from_slice(line.as_bytes());
+    buffer.push(b'\n');
+    file.write_all(&buffer).await?;
     Ok(())
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@TelegramSearchBot.CodingAgentSidecar/src/main.rs` around lines 624 - 635,
append_line() currently issues two separate writes which can interleave when
run_agent() and the stderr appender write concurrently; change append_line() to
perform a single atomic write by composing the line with its trailing newline
(e.g., format!("{}\n", line) or by building a single byte buffer) and calling
write_all once so each log line is appended in one syscall.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@TelegramSearchBot.CodingAgentSidecar/src/main.rs`:
- Around line 624-635: append_line() currently issues two separate writes which
can interleave when run_agent() and the stderr appender write concurrently;
change append_line() to perform a single atomic write by composing the line with
its trailing newline (e.g., format!("{}\n", line) or by building a single byte
buffer) and calling write_all once so each log line is appended in one syscall.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 305e5c34-e6c2-4d73-be99-47a7b770e16c

📥 Commits

Reviewing files that changed from the base of the PR and between b963802 and 9898ced.

⛔ Files ignored due to path filters (1)
  • TelegramSearchBot.CodingAgentSidecar/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (12)
  • .gitignore
  • Docs/README_CodingAgentTool.md
  • Docs/README_MCP.md
  • TelegramSearchBot.CodingAgentSidecar/Cargo.toml
  • TelegramSearchBot.CodingAgentSidecar/README.md
  • TelegramSearchBot.CodingAgentSidecar/src/main.rs
  • TelegramSearchBot.Common/Env.cs
  • TelegramSearchBot.Common/Model/AI/LlmAgentContracts.cs
  • TelegramSearchBot.LLM/Service/Tools/CodingAgentToolService.cs
  • TelegramSearchBot/Extension/ServiceCollectionExtension.cs
  • TelegramSearchBot/Service/AI/LLM/CodingAgentReportConsumer.cs
  • TelegramSearchBot/Service/AI/LLM/CodingAgentSidecarLauncherService.cs
💤 Files with no reviewable changes (2)
  • TelegramSearchBot.Common/Model/AI/LlmAgentContracts.cs
  • TelegramSearchBot/Service/AI/LLM/CodingAgentReportConsumer.cs
✅ Files skipped from review due to trivial changes (3)
  • TelegramSearchBot.CodingAgentSidecar/README.md
  • Docs/README_CodingAgentTool.md
  • Docs/README_MCP.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • TelegramSearchBot/Extension/ServiceCollectionExtension.cs
  • TelegramSearchBot.LLM/Service/Tools/CodingAgentToolService.cs
  • TelegramSearchBot.Common/Env.cs

@ModerRAS ModerRAS force-pushed the codex/rmux-pi-coding-agent branch from 9898ced to ec32871 Compare June 1, 2026 07:06
@ModerRAS ModerRAS force-pushed the codex/rmux-pi-coding-agent branch from ec32871 to af2fac8 Compare June 1, 2026 07:08
@ModerRAS ModerRAS merged commit 4bcb77f into master Jun 1, 2026
5 checks passed
@ModerRAS ModerRAS deleted the codex/rmux-pi-coding-agent branch June 1, 2026 11:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant