Skip to content

Local agent ReAct loop with history management and context budgeting #1006

Closed

Description

@malibio

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 CancellationToken stops mid-generation
  • Unit tests with mock ChatInferenceEngine and mock AgentToolExecutor
  • Code passes bun run quality:fix

Technical Specifications

New Modules

  • packages/desktop-app/src-tauri/src/local_agent/agent_loop.rs
  • packages/desktop-app/src-tauri/src/local_agent/prompt_templates.rs
  • packages/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

  • LocalAgentService manages 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::Token as Tauri events (local-agent://chunk)
  • Forward StreamingChunk::ToolCall as Tauri events (local-agent://tool)
  • Buffer partial tool-call tokens until complete, then emit
  • Forward status changes as local-agent://status events

Reference Files

  • packages/desktop-app/src-tauri/src/app_services.rs — service ownership pattern
  • packages/core/src/playbook/engine.rs — event-driven loop pattern
  • Architecture doc: nodespace-docs/architecture/acp-integration.md section 2

Exports

  • LocalAgentLoop — the ReAct loop implementation
  • LocalAgentService — session management facade

Dependencies

Related Issues

Activity

  1. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Implementation Guide

    Start Here

    1. Read packages/desktop-app/src-tauri/src/app_services.rs — understand the hot-swap lifecycle:

      • AppServices (line 42) wraps Arc<RwLock<Option<ActiveServices>>> — services can be replaced at runtime
      • switch_database() (line 174) — drain-then-replace protocol. Your LocalAgentService must survive this.
      • Service accessors (lines 66-118) return Result<Arc<T>, CommandError> — never panic on missing services
    2. Read packages/desktop-app/src-tauri/src/lib.rs — initialization sequence:

      • ShutdownToken (line 202) — Tauri-managed cancellation token for background tasks
      • initialize_domain_event_forwarder() (line 48) — example of subscribing to domain events
      • initialize_playbook_engine() (line 94) — example of a second event subscriber
      • initialize_mcp_server() (line 142) — key pattern: independent service NOT in AppServices, created in lib.rs
    3. Read packages/desktop-app/src-tauri/src/mcp_integration.rs — the MCP service follows the exact pattern your LocalAgentService should follow: independent Tauri managed state, obtains NodeService per-operation from AppServices.

    Service Ownership Pattern

    Per the ACP architecture doc, agent services must NOT live inside ActiveServices — they must survive database hot-swaps:

    // In lib.rs setup — OUTSIDE AppServices:
    app.manage(LocalAgentService::new(models_dir));
    
    // In commands — obtain NodeService per-operation:
    async fn local_agent_send(
        app_services: State<'_, AppServices>,
        agent: State<'_, LocalAgentService>,
        session_id: String,
        message: String,
    ) -> Result<StopReason, CommandError> {
        let node_service = app_services.node_service().await?;
        agent.send_message(session_id, message, &node_service).await
    }

    Tauri Event Emission

    The domain event forwarder at lib.rs:48 shows the pattern for emitting events to the frontend:

    app_handle.emit("event-name", payload)?;

    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

    • LocalAgentService is long-lived (app lifetime, survives hot-swap)
    • Sessions are per-conversation — created when user opens an ai-chat node, ended when they close it
    • The service holds sessions in a HashMap<String, AgentSession>
    • Each session holds conversation history (Vec<ChatMessage>) and the cancel token

    Cancellation

    Use tokio_util::sync::CancellationToken (same as ShutdownToken pattern in lib.rs). The agent loop checks cancel.is_cancelled() between inference iterations and tool executions.

  2. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Baseline: Frontend tests fail due to missing .svelte-kit/tsconfig.json in worktree (pre-existing). Rust tests will be used for validation.

  3. self-assigned this
    on Apr 3, 2026
  4. added 2 commits that reference this issue on Apr 3, 2026
    8579dd2
    382462a
  5. added a commit that references this issue on Jun 22, 2026
    f179ec2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions