When an AI assistant can glance at your macOS Dock, read the Windows PowerShell history, or list Linux brew packages, the interaction jumps from “guess what I want” to “I see exactly what you need”. My first attempt at a desktop Claude agent used a static prompt that listed a handful of generic CLI commands. The result? Half‑baked suggestions, unnecessary token waste, and a UI that froze every time Claude streamed a response.
What you really need is a *context‑aware* prompt that the backend builds on‑the‑fly, fed with OS‑specific details, and an event‑driven UI that never blocks while the model streams tokens.
- Detect OS details with Python
platformandpsutilonce, cache, and inject them as JSON payload. - Use Tauri 2.x for a lightweight, native‑look GUI; keep the UI thread free with Rust‑async bridges.
- Maintain a stateful Claude session via Anthropic SDK 3.x to reuse context and tool definitions.
- Stream tokens through a Rust‑mpsc channel into the frontend, updating a scrolling view in real‑time.
- Wrap every tool call in retry, circuit‑breaker, and sandbox logic to keep the desktop safe.
Before you start: Python 3.12+, Rust 1.73+, Tauri 2.0+, Anthropic SDK 3.x, Claude 3.7 Sonnet API key, psutil ≥ 6.0, platformdirs ≥ 4.1, Node 20 (for Tauri), and a recent C++ build toolchain (MSVC/Clang/GCC).
Dynamic OS‑Aware Prompt Engineering with Claude (2026)
Dynamic Prompt Engineering based on OS context involves building an AI agent that detects the user’s operating system (macOS, Windows, Linux) and injects specific commands, file paths, and tool syntax into its prompts in real‑time. This guide shows you how to build such a system in 2026 using Python for context detection, the Anthropic Claude SDK for the AI backbone, and Tauri for a cross‑platform GUI that streams responses without freezing.
Architecture Overview & Tech Stack
| Component | Reason for selection (2026) |
|---|---|
| OS Detection & Context Builder | Python’s platform + psutil give reliable, cross‑platform introspection; they run fast and can be cached. |
| GUI Framework | Tauri 2.x keeps the binary under 15 MB, uses Rust’s async runtime, and renders native web UI. PyQt 6 is powerful but ships a heavy Qt runtime; we’ll fallback to it only for a “quick‑proto” version. |
| AI Backend | Anthropic SDK 3.x supports stateful sessions, tool‑use protocol, and token streaming over HTTP/2. |
| Event Loop / State Sync | Rust async + Tokio drives the bridge; Python runs in a separate process communicating via JSON‑RPC over a local socket. This eliminates UI blocking. |
graph TD
UI[GUI (Tauri)] -->|JSON-RPC| PY[Python Context Engine]
PY -->|JSON| CLAUDE[Claude Session]
CLAUDE -->|stream| UI
UI -->|user action| PY
PY -->|cache| OSCTX[OS Context Cache]
Core Component: OS Detection & Context Builder
The builder lives in a pure‑Python module (os_context.py). It gathers:
- OS name, release, architecture.
- Path to the default shell (
/bin/bash,pwsh.exe, etc.). - Presence of common dev tools (
git,docker,brew,choco). - Hotkey mappings (⌘+C vs Ctrl+C) for UI hints.
All data are emitted as a JSON schema that the prompt orchestration layer can slice and dice.
GUI Framework: Tauri vs. PyQt 6
- Tauri – tiny installer, leverages the OS’s web view, integrates Rust async nicely. Ideal for production packaging.
- PyQt 6 – richer widget set, easier for pure‑Python developers, but bundles a 70 MB Qt lib. Use only for rapid prototyping.
My take: start with Tauri; if you hit a UI limitation, drop a PyQt window as a modal for that specific feature.
AI Backend: Claude 3.7 Sonnet
Claude 3.7 Sonnet adds a tool‑use endpoint that expects a list of JSON‑encoded tool definitions. We’ll register a run_shell tool that receives a sanitized command string and returns stdout/stderr. The SDK automatically re‑uses the session token, cutting latency.
Event Loop & State Synchronization
- Rust side:
tokio::sync::mpscchannel streams Claude tokens to the web view. The channel is bounded (size = 64) to avoid memory bursts. - Python side: An
asynciotask watches a local Unix‑domain socket (named pipe on Windows) for UI requests, processes them, and pushes responses back on the same socket.
The separation guarantees that the UI never blocks, even when Claude pauses for a tool call.
—
Step 1: Building the Core OS Context Detection Engine
Create a package os_context/ with the following file.
# os_context/__init__.py
# Python 3.12+ | psutil 6.0.0 | platformdirs 4.1.0
import json
import platform
import psutil
from pathlib import Path
from typing import Dict, List
# Cache results for the process lifetime
_CACHE: Dict[str, any] = {}
def _detect_shell() -> str:
system = platform.system()
if system == "Windows":
return "pwsh.exe" if shutil.which("pwsh") else "cmd.exe"
if system == "Darwin":
return "/bin/zsh"
return "/bin/bash"
def _list_installed_tools() -> List[str]:
candidates = {
"git": ["git"],
"docker": ["docker"],
"brew": ["brew"],
"chocolatey": ["choco"],
"npm": ["npm"],
"cargo": ["cargo"]
}
installed = []
for name, exe in candidates.items():
if any(shutil.which(bin) for bin in exe):
installed.append(name)
return installed
def build_context() -> Dict[str, any]:
global _CACHE
if _CACHE:
return _CACHE
ctx = {
"os": platform.system(),
"release": platform.release(),
"architecture": platform.machine(),
"shell": _detect_shell(),
"cpu_count": psutil.cpu_count(logical=True),
"memory_gb": round(psutil.virtual_memory().total / (1024**3), 1),
"tools": _list_installed_tools(),
"home_dir": str(Path.home()),
}
# Sanitize paths – replace backslashes on Windows with forward slashes for JSON consistency
ctx["home_dir"] = ctx["home_dir"].replace("\\", "/")
_CACHE = ctx
return ctx
def as_json() -> str:
return json.dumps(build_context(), separators=(",", ":"))
The module is deliberately small and pure‑Python, making it easy to unit‑test (see the *State Synchronization* principle in the intro). The as_json() function will be called by the JSON‑RPC server whenever the UI asks for fresh context.
Caching and Sanitizing
We store the detection result in a module‑level _CACHE. A change in the underlying system (e.g., a new tool installed) requires a manual “Refresh” button that clears the cache:
def clear_cache() -> None:
global _CACHE
_CACHE.clear()
The UI can invoke this RPC method after user confirmation.
—
Step 2: Designing the Prompt Orchestration Layer
The orchestration lives in prompt_engine/. It accepts raw user input, injects OS context, and builds a structured Claude request.
# prompt_engine/engine.py
# Anthropic SDK 3.2.0 | Python 3.12+
import json
import uuid
from typing import Dict, List, Any
from anthropic import Anthropic, Stream
from os_context import as_json
class PromptQueue:
"""Priority queue for context injection."""
def __init__(self):
self._queue: List[Dict[str, Any]] = []
def add(self, payload: Dict[str, Any], priority: int = 5) -> None:
payload["priority"] = priority
self._queue.append(payload)
self._queue.sort(key=lambda x: x["priority"])
def pop(self) -> Dict[str, Any]:
return self._queue.pop(0) if self._queue else {}
class ClaudeClient:
def __init__(self, api_key: str):
self.client = Anthropic(api_key=api_key)
self.session_id = str(uuid.uuid4())
self.history: List[Dict] = []
self.tools = [
{
"name": "run_shell",
"description": "Execute a sanitized shell command on the host OS.",
"input_schema": {
"type": "object",
"properties": {"command": {"type": "string"}},
"required": ["command"]
}
}
]
def _build_message(self, user_prompt: str, context: str) -> List[Dict]:
system_prompt = (
f"You are a cross‑platform assistant. Provide commands matching the user's OS. "
f"Use the following context to tailor your answer: {context}"
)
return [
{"role": "system", "content": system_prompt},
*self.history,
{"role": "user", "content": user_prompt}
]
def chat(self, user_prompt: str, stream_callback) -> None:
ctx = as_json()
messages = self._build_message(user_prompt, ctx)
try:
with self.client.messages.stream(
model="claude-3-7-sonnet-202406",
max_tokens=1024,
temperature=0.0,
system=messages[0]["content"],
messages=messages[1:],
tools=self.tools,
stream=True,
session_id=self.session_id,
) as stream:
for event in stream:
if isinstance(event, Stream.ResponseDelta):
# Incremental token callback
stream_callback(event.delta)
elif isinstance(event, Stream.ToolUse):
# Tool-use loop
self._handle_tool(event)
except Exception as exc:
# Circuit‑breaker style fallback
stream_callback(f"\n[Error] Claude call failed: {exc}\n")
raise
def _handle_tool(self, tool_event) -> None:
"""Execute the requested tool, then feed the result back."""
if tool_event.name != "run_shell":
return
cmd = tool_event.input.get("command", "")
sanitized = self._sanitize_command(cmd)
try:
result = subprocess.run(
sanitized, shell=True, capture_output=True, text=True, timeout=10
)
output = result.stdout or result.stderr
except subprocess.TimeoutExpired:
output = "[Timeout] Command took longer than 10 s"
except Exception as e:
output = f"[Tool error] {e}"
# Send tool result back to Claude
self.client.messages.create(
model="claude-3-7-sonnet-202406",
max_tokens=0,
temperature=0.0,
system="",
messages=[
{"role": "assistant", "content": [{"type": "tool_result", "tool_use_id": tool_event.id, "content": output}]}
],
session_id=self.session_id,
)
@staticmethod
def _sanitize_command(cmd: str) -> str:
# Very strict allow‑list – only whitelisted binaries
allowed = {"git", "ls", "dir", "cat", "type", "docker", "brew", "choco", "npm"}
parts = cmd.split()
if parts and parts[0] not in allowed:
raise ValueError(f"Command '{parts[0]}' is not in the allow‑list.")
return cmd
What this does
- Pulls fresh OS context (cached) and injects it into a system message.
- Sends a streaming request; each token is fed to the UI via
stream_callback. - If Claude asks for a tool,
_handle_toolruns the command in a sandboxed subprocess, applies a timeout, and feeds the result back.
Priority‑Based Injection Queue
The PromptQueue lets the UI schedule a “refresh context” payload with high priority (e.g., priority=1) so that it reaches Claude before normal user queries. This solves the “static prompt” issue highlighted at the start.
—
Step 3: Creating the Interactive GUI with Tauri (Rust + Frontend)
Project Scaffold
# Install Tauri CLI (Node 20 + Rust)
npm create tauri-app@latest os‑aware‑claude
cd os-aware-claude
# Choose "Vanilla" + "Rust", then install dependencies
cargo add tokio
cargo add serde_json
cargo add tauri-plugin-shell
The generated folder contains src-tauri/ (Rust) and src/ (frontend). We’ll replace the default UI with a minimal React 18 + Vite setup because it handles live updates nicely.
src/main.rs – Async Bridge
// src-tauri/src/main.rs
// Tauri 2.0.0 | Rust 1.73
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Manager, Runtime, State};
use tokio::sync::mpsc::{self, UnboundedSender};
use std::process::Stdio;
use std::sync::Arc;
#[derive(Clone, Serialize, Deserialize)]
struct UiRequest {
kind: String,
payload: String,
}
#[derive(Clone, Serialize, Deserialize)]
struct UiResponse {
kind: String,
data: String,
}
// Shared bridge state
struct Bridge {
tx: UnboundedSender<UiResponse>,
}
#[tauri::command]
async fn invoke_backend(
request: UiRequest,
app: AppHandle,
bridge: State<'_, Arc<Bridge>>,
) -> Result<(), String> {
match request.kind.as_str() {
"prompt" => {
let tx = bridge.tx.clone();
tokio::spawn(async move {
// Call the Python engine via JSON‑RPC over a local socket
if let Err(e) = call_python_engine(request.payload, tx).await {
eprintln!("Backend error: {}", e);
}
});
Ok(())
}
"refresh_context" => {
// Simple one‑off RPC to ask Python for fresh context
let ctx = python::get_context().await?;
app.emit_all("context-updated", ctx).map_err(|e| e.to_string())
}
_ => Err("Unknown request".into()),
}
}
// Async wrapper for Python subprocess
async fn call_python_engine(
user_prompt: String,
ui_tx: UnboundedSender<UiResponse>,
) -> Result<(), Box<dyn std::error::Error>> {
// Spawn the Python script with async stdio
let mut child = tokio::process::Command::new("python")
.arg("-m")
.arg("prompt_engine.runner")
.arg(user_prompt)
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let mut stdout = child.stdout.take().expect("Failed to capture stdout");
let mut reader = tokio::io::BufReader::new(stdout);
let mut line = String::new();
while reader.read_line(&mut line).await? != 0 {
ui_tx.send(UiResponse {
kind: "token".into(),
data: line.clone(),
})?;
line.clear();
}
let status = child.wait().await?;
if !status.success() {
return Err("Python engine exited with error".into());
}
Ok(())
}
fn main() {
let (tx, mut rx) = mpsc::unbounded_channel::<UiResponse>();
let bridge = Arc::new(Bridge { tx });
// Spawn a task that forwards UI responses to the webview
tauri::async_runtime::spawn(async move {
while let Some(msg) = rx.recv().await {
// This uses Tauri's event system
tauri::api::event::emit_all("backend-message", msg).unwrap();
}
});
tauri::Builder::default()