Desktop AI Agent Architecture: From Conversation to Execution

    This article breaks down the architecture of desktop AI agents for readers who want to understand or build them. It explains how these agents differ from ordinary chat assistants by reading and writing local files, invoking local programs, and decomposing vague requests into multi-step operations. It then covers four core modules—Planner, Executor, permission and sandbox, and cloud collaboration—along with a structured task instruction format, JSON and Python examples, error codes, and security, backup, and logging.

    This article is intended for readers who want to understand or develop desktop AI agents. The main difference between these tools and ordinary chat assistants is that they can read and write local files, invoke local programs, and break a vague request into multiple operations. Greater capability also means greater cost when something goes wrong, so architecture design and security controls need to be considered together.

    1. From Conversation to Execution: Where the Capability Boundary Lies

    The output of a traditional chat assistant is text; after reading it, the user takes action. The output of an agent is an action, such as moving files, generating a spreadsheet, or submitting code. This difference determines the risk level. If the assistant generates an incorrect piece of text, the user can ignore it. If it incorrectly deletes a batch of files, the data may not be recoverable.

    Practical desktop agents usually cover three types of capabilities:

    1. Local file operations: organizing directories, batch renaming, format conversion, or reading multiple documents and generating a summary, all based on natural-language instructions.
    2. Tool invocation: calling software already installed on the machine or external interfaces, such as using an image tool to add watermarks in batches.
    3. Remote triggering: the user sends an instruction through an instant messaging tool, the desktop client executes it while online, and the result is sent back.

    All three types of capabilities require the client to run locally. The web version is limited by the browser sandbox and usually cannot access arbitrary local directories, so full execution capabilities require a desktop client built with Electron, Tauri, or similar approaches.

    2. The Four Core Architecture Modules

    A maintainable desktop agent generally contains four modules. The input, output, and failure handling of each module should be designed separately.

    Module Input Output Failure handling Permission boundary
    Planner User instructions, directory context Structured Action sequence Return clarification questions; do not guess Read-only context; no direct file access
    Executor Action sequence Execution results and error codes Terminate on timeout; retry according to rules Executes only allowlisted templates
    Permission and sandbox Execution request Allow or deny Deny by default Directory allowlist; least privilege
    Cloud collaboration Authentication requests, instructions, logs Forwarded results, audit records Message redelivery with a retry cap Stores only necessary metadata

    Planner is responsible for decomposing complex requirements into actions. Its output must conform to a fixed format; free text generated by the model cannot be passed directly to the system for execution. Mechanisms such as Function Calling can constrain the output structure, but the system still needs a validation layer over the result.

    Executor only executes operation templates in the allowlist. If the model is allowed to generate arbitrary scripts and run them directly, operations are difficult to audit and easy to exploit through prompt injection.

    Permissions and sandboxing should deny by default. Directory access, network requests, and process invocation all require separate authorization. A sandbox can be implemented with Docker containers, lightweight virtual machines, or OS-provided restricted process mechanisms; the choice depends on the platform and available resources.

    Cloud services are suitable for authentication, instruction relay, and log collection. Regardless of which cloud vendor’s object storage or message queue is used, three things must be handled. First, use TLS encryption at the transport layer. Second, Webhook requests carry signatures and validate timestamps to prevent replay attacks. Third, paths, file names, and tokens in logs must be redacted. If you do not want to be tied to a single vendor, you can use self-hosted message middleware or open-source queue services.

    3. Task Instruction Format and a Practical Example

    When the task “convert all txt files in the directory to md format” is given to the agent, Planner should output a structured instruction rather than a bare script. The following example includes a version number, authorization scope, parameters, and timeout settings:

    1. {
    2. "schema_version": "1.0",
    3. "task_id": "task_98765",
    4. "authorization": {
    5. "grant_id": "notes_dir_grant_01",
    6. "allowed_root": "C:/Users/Documents/Notes"
    7. },
    8. "actions": [
    9. {
    10. "action_id": "a1",
    11. "type": "run_template",
    12. "template_id": "txt_to_md",
    13. "params": {
    14. "directory": "C:/Users/Documents/Notes",
    15. "dry_run": true
    16. },
    17. "timeout_ms": 30000,
    18. "max_retries": 1
    19. }
    20. ]
    21. }

    After Executor receives the request, it first validates the schema and authorization scope. If the directory is not within allowed_root, it directly returns error code E_SCOPE_DENIED and does not perform any operation.

    After the preview result is returned to the user and the user confirms, the system initiates a second request with dry_run set to false. This way the user can first see which files will be changed.

    The corresponding template code is below. It requires Python 3.8 or later, and files are read as UTF-8:

    1. from pathlib import Path
    2. ALLOWED_ROOT = Path("C:/Users/Documents/Notes").resolve()
    3. def txt_to_md(directory: str, dry_run: bool = True) -> list[str]:
    4. root = Path(directory).resolve()
    5. if ALLOWED_ROOT not in [root, *root.parents]:
    6. raise PermissionError("E_SCOPE_DENIED: directory is outside the authorized scope")
    7. plan = []
    8. for src in sorted(root.glob("*.txt")):
    9. dst = src.with_suffix(".md")
    10. if dst.exists():
    11. continue # Skip if the destination already exists to avoid overwriting
    12. plan.append((src, dst))
    13. if dry_run:
    14. return [f"{s.name} -> {d.name}" for s, d in plan]
    15. for src, dst in plan:
    16. text = src.read_text(encoding="utf-8")
    17. tmp = dst.with_name(dst.name + ".tmp")
    18. tmp.write_text(text, encoding="utf-8")
    19. tmp.replace(dst) # Write to a temporary file first, then replace, so a mid-way failure does not leave a partial file
    20. return [f"{s.name} -> {d.name}" for s, d in plan]

    This code keeps the original txt files and only creates new md files, with the content copied as plain text. If you need to convert headings, tables, and other elements into standard Markdown syntax, you should use a conversion tool such as pandoc instead.

    Common error codes are as follows:

    • E_SCOPE_DENIED: The directory is outside the authorized scope.
    • E_CONFIRM_REQUIRED: A write operation has not been confirmed by the user.
    • E_TIMEOUT: The task exceeds timeout_ms, is terminated, and temporary files are cleaned up.
    • E_IO: Read/write failure; the specific file name is returned to help locate the issue.

    4. Security, Backup, and Logging