Repository navigation
Closed
Description
Overview
Implement the core ReAct (Reason + Act) loop that drives the local agent. This is the orchestration layer: it takes a user message, constructs prompts, calls the inference engine, parses tool calls, executes tools, feeds results back, and repeats until the model produces a final response or hits limits.
Can be developed against a mock ChatInferenceEngine and integrated with the real NLP engine (#999) later.
Acceptance Criteria
- Single-turn conversation: user asks question, model responds (no tools needed)
- Multi-step tool use: model calls search_nodes, gets results, synthesizes answer
- Chain of tool calls: model calls search_semantic, then get_node, then responds
- Max iteration limit: loop terminates after 5 tool-call rounds with partial answer
- History summarization triggers at 6k tokens, preserves recent context
- Status transitions emitted for each phase (Idle -> Thinking -> ToolExecution -> Streaming -> Idle)
- Streaming tokens forwarded correctly (text chunks and tool-call chunks distinguished)
- Session create/resume with persistent history
- Cancellation via
CancellationTokenstops mid-generation - Unit tests with mock
ChatInferenceEngineand mockAgentToolExecutor - Code passes
bun run quality:fix
Technical Specifications
New Modules
packages/desktop-app/src-tauri/src/local_agent/agent_loop.rspackages/desktop-app/src-tauri/src/local_agent/prompt_templates.rspackages/desktop-app/src-tauri/src/local_agent/mod.rs(LocalAgentService)
ReAct Loop
User Message
|
v
Build message history (system prompt + conversation + tool results)
|
v
Run ChatInferenceEngine::generate() (stream tokens via callback)
|
v
Response contains tool calls?
|-- Yes: Execute via AgentToolExecutor
| Append tool results to history
| Loop back (max 5 iterations)
|
|-- No: End turn, return final response
|
|-- MaxTokens: End turn, return partial response
Prompt Templates
System prompt structure:
You are a knowledge graph assistant for NodeSpace. You help users organize, search, and manage their knowledge.
Available tools:
[tool definitions with JSON schemas]
When you need information, use the available tools. Always cite node IDs so users can verify.
Tool call format: [TOOL_CALLS]function_name[ARGS]{"param": "value"}
Tool result format:
Tool: search_nodes
Result: Found 3 nodes:
1. [id:abc123] "Billing Architecture" (component-spec)
2. [id:def456] "Payment Processing" (text)
3. [id:ghi789] "Invoice Schema" (schema)
History summarization prompt:
Summarize the following conversation history into key facts and context. Preserve node IDs, tool results, and user preferences. Be concise.
[older messages]
History Management
- Maintain conversation as
Vec<ChatMessage> - Total context budget: 8k tokens
- Reserved: 2k tokens for system prompt + tool definitions
- Available for history: 6k tokens
- When history exceeds 6k: summarize older turns into condensed message, keep recent 2-3 turns verbatim
- Summarization uses same inference engine (single-shot, no tools)
Session Management
LocalAgentServicemanages active sessions- Create session: generate UUID, initialize empty history, set status to Idle
- Resume session: load existing history, continue from where left off
- End session: clean up resources
- One active session at a time (new session replaces old)
Streaming Bridge
- Forward
StreamingChunk::Tokenas Tauri events (local-agent://chunk) - Forward
StreamingChunk::ToolCallas Tauri events (local-agent://tool) - Buffer partial tool-call tokens until complete, then emit
- Forward status changes as
local-agent://statusevents
Reference Files
packages/desktop-app/src-tauri/src/app_services.rs— service ownership patternpackages/core/src/playbook/engine.rs— event-driven loop pattern- Architecture doc:
nodespace-docs/architecture/acp-integration.mdsection 2
Exports
LocalAgentLoop— the ReAct loop implementationLocalAgentService— session management facade
Dependencies
- Shared types, traits, and interface contracts for agent subsystems #998 (types/traits)
- NLP Engine: Chat inference with streaming and tool-call parsing #999 (chat inference — can develop against mock, integrate later)
Related Issues
- ACP Integration and Local LLM Capability #997 (parent epic)
- Local agent ReAct loop with history management and context budgeting #1006 (agent tools — consumed but can develop in parallel)
Activity
malibio commentedon Apr 3, 2026
Implementation Guide
Start Here
Read
packages/desktop-app/src-tauri/src/app_services.rs— understand the hot-swap lifecycle:AppServices(line 42) wrapsArc<RwLock<Option<ActiveServices>>>— services can be replaced at runtimeswitch_database()(line 174) — drain-then-replace protocol. YourLocalAgentServicemust survive this.Result<Arc<T>, CommandError>— never panic on missing servicesRead
packages/desktop-app/src-tauri/src/lib.rs— initialization sequence:ShutdownToken(line 202) — Tauri-managed cancellation token for background tasksinitialize_domain_event_forwarder()(line 48) — example of subscribing to domain eventsinitialize_playbook_engine()(line 94) — example of a second event subscriberinitialize_mcp_server()(line 142) — key pattern: independent service NOT in AppServices, created in lib.rsRead
packages/desktop-app/src-tauri/src/mcp_integration.rs— the MCP service follows the exact pattern yourLocalAgentServiceshould follow: independent Tauri managed state, obtainsNodeServiceper-operation fromAppServices.Service Ownership Pattern
Per the ACP architecture doc, agent services must NOT live inside
ActiveServices— they must survive database hot-swaps:Tauri Event Emission
The domain event forwarder at
lib.rs:48shows the pattern for emitting events to the frontend:Your agent loop emits:
local-agent://chunk— streaming tokens (text: String)local-agent://tool— tool execution updates (tool_name, status, result_summary)local-agent://status— status transitions (Idle, Thinking, ToolExecution, Streaming)Session vs Service Lifecycle
LocalAgentServiceis long-lived (app lifetime, survives hot-swap)HashMap<String, AgentSession>Vec<ChatMessage>) and the cancel tokenCancellation
Use
tokio_util::sync::CancellationToken(same asShutdownTokenpattern in lib.rs). The agent loop checkscancel.is_cancelled()between inference iterations and tool executions.malibio commentedon Apr 3, 2026
Baseline: Frontend tests fail due to missing .svelte-kit/tsconfig.json in worktree (pre-existing). Rust tests will be used for validation.
feat: local agent ReAct loop with history management and context budg…
feat: local agent ReAct loop with history management and context budg…
feat: local agent ReAct loop with history management and context budg…