Instant Messaging-Driven Coding Agents: Protocol Integration and Controlled Execution

    This article examines how to build an instant messaging-driven coding agent that can inspect and modify code repositories remotely. It covers protocol integration, unified event modeling, deduplication, task state machines, agent and tool boundaries, path and command isolation, approval flows, progress reporting, and a staged path from a read-only prototype to controlled execution. The emphasis is on separating interaction from execution and enforcing authorization, isolation, auditability, and idempotency outside the model. Readers gain an architecture and implementation checklist for reliable remote coding agents.

    1. From Remote Chat to Remote Execution: What Really Changes Is the Permission Boundary

    Consider a scenario: a developer is away from the computer but needs to check a source file for potential defects. The user sends “check the exception handling in the entry file” through instant messaging. The server receives the request, reads the relevant code, finds call relationships, runs tests when necessary, and finally sends the analysis conclusion back to the mobile device.

    The fundamental difference between such a system and an ordinary question-answering bot is not that the answer is longer or that the model is better at writing code. The difference is that it can invoke tools and change state in the real environment.

    Therefore, the design goal cannot stop at “messages can be received and answers can be sent.” A complete system needs to solve four problems:

    1. Does the message come from an authorized user?
    2. What task should the natural-language request be converted into?
    3. Which files can the agent access, and which operations can it perform?
    4. If execution fails, how can the system recover and explain the result?

    The core principle is: the messaging channel handles interaction, the task control layer handles decisions, the agent runtime handles reasoning, and controlled tools handle execution. The model should not be allowed to decide all security boundaries directly.

    2. Overall Architecture: Decouple the Interaction Entry Point from the Execution Environment

    A general implementation can use the following chain:

    1. Mobile instant messaging
    2. ↓
    3. Messaging protocol adaptation layer
    4. ↓
    5. Identity verification and task entry
    6. ↓
    7. Task queue and session management
    8. ↓
    9. Coding agent runtime
    10. ↓
    11. Controlled file tools and command executor
    12. ↓
    13. Result assembly and message delivery

    These components do not necessarily need to be split into multiple independent services. For personal use or small-scale validation, they can first be implemented in the same process, but clear module boundaries should be retained.

    2.1 Messaging Protocol Adaptation Layer

    This layer receives messages, parses events, maintains connection state, and sends replies. It exposes only a unified message structure to upper layers and does not expose underlying protocol details.

    2.2 Task Control Layer

    This layer handles authentication, deduplication, queuing, timeouts, cancellation, and approval. It decides whether a task can enter the execution stage, rather than passing every received text directly to the agent.

    2.3 Agent Runtime

    The runtime connects to reasoning capabilities and tool invocation mechanisms through a development kit or a unified calling interface. Based on the task description, it chooses to read files, search code, propose modifications, or run validation.

    2.4 Tool Execution Layer

    This layer enforces permission limits, including working-directory constraints, file access control, process isolation, network restrictions, and output truncation. Security controls should be enforced at this layer and must not rely only on prompts.

    The value of this layering is that changing the messaging integration method does not require rewriting the tool execution logic; adjusting the agent implementation should not affect identity authentication and task auditing.

    3. Protocol Integration: Prefer Authorized Interfaces and Handle Protocol Analysis with Caution

    Instant messaging integration may use event push or continuous polling. Each approach has engineering trade-offs.

    Event push usually requires the service to have a reachable receiving endpoint and to verify the request source. Continuous polling can reduce dependence on a public endpoint, but it requires maintaining cursors, handling reconnections, and controlling request frequency.

    If a public, authorized integration capability exists, it should be preferred. Protocol analysis should be conducted only in test environments where authorization is explicitly obtained and relevant usage constraints are followed; protocol analysis should not be used to bypass access controls or obtain other people’s sessions.

    3.1 Analyze the Message Lifecycle First, Not Just the Packet Format

    A working integration layer needs to understand the following processes:

    • How to establish and maintain a legitimate session;
    • How to identify the message source and session ownership;
    • How to distinguish text, attachments, and system events;
    • How to confirm that a message has been received;
    • How to handle duplicate delivery, disconnection, and recovery;
    • How to determine whether a reply was sent successfully.

    Parsing a message successfully once does not prove that the integration is reliable. The parts most prone to problems are often recovery after a connection interruption and control of side effects when messages are duplicated.

    3.2 Use a Unified Event Model to Isolate Protocol Changes

    The following structure is only for illustrating internal design and is not an interface of any specific service:

    1. Message event:
    2. Source identifier
    3. Session identifier
    4. Message identifier
    5. Receipt time
    6. Message type
    7. Body content
    8. Attachment reference

    The protocol adaptation layer converts events from different sources into this structure, so the task entry does not need to understand the underlying packets.

    Attachments must not be trusted directly. File size, type, storage location, and read permissions all need to be checked; user-uploaded content should also be treated as untrusted input.

    3.3 Use Deduplication to Avoid Repeated Execution

    Messaging systems may deliver messages more than once. For chat replies, a duplicate is only a user-experience issue; for code changes or command execution, a duplicate may cause real damage.

    A stable message identifier should be used to create deduplication records. If the underlying system does not provide a reliable identifier, an internal identifier can be constructed by combining source, session, and event attributes, but text content alone must not be used because a user may send two identical instructions in succession.

    Task records should be persisted before entering the execution queue. Even so, the system should not casually claim to implement strict “execute once”: a process crash may occur after a tool operation completes but before the state record is written. For write operations, recovery still needs to combine execution logs, result checks, and human confirmation.

    4. Task Modeling: Do Not Turn the Entire Chat History Directly into Execution Instructions

    Instant messaging has the characteristics of omitted context, casual expression, and mixed tasks. For example, what file and what problem does “fix it while you’re at it” refer to? The latest sentence alone is often not enough to determine this.

    It is recommended to abstract a task into the following information:

    1. Task:
    2. User identity
    3. Project identifier
    4. Working directory
    5. Goal description
    6. Operation level
    7. Context reference
    8. Current state
    9. Execution result

    The working directory and operation level should be determined after server-side validation, rather than accepting arbitrary user input.

    4.1 Clearly Distinguish Three Types of Operations

    Read-only analysis: read files, search references, and summarize risks without modifying the project.

    Change generation: produce a diff or modification proposal and wait for user confirmation before applying it.

    Controlled execution: run permitted tests or inspection tasks and record the execution results.

    “Running tests” does not mean “no side effects.” Test scripts in a project may start processes, access the network, write files, or even execute arbitrary code, so isolation and resource limits are still required.

    4.2 Design a Recoverable State Machine

    A task can go through:

    1. Received → Pending execution → Executing → Pending confirmation → Completed
    2. ↘ Execution failed
    3. ↘ Cancelled

    Not every task enters “pending confirmation”; read-only tasks can usually complete directly. State changes should be persisted so that the service can identify unfinished tasks after a restart.

    For the same project, write tasks should preferably be executed serially. Whether read-only tasks can run concurrently depends on whether they share a stable code snapshot. Otherwise, one task may read inconsistent content while another task is modifying files.

    5. Agent Integration: Let the Model Propose Operations, Let the System Constrain Operations

    Coding agents usually follow a loop of “reason—call tools—read results—continue reasoning.” The server should design the tool set as a limited, inspectable set of capabilities rather than providing an unrestricted execution entry point.

    For example:

    • Read text files within a specified directory;
    • Search code within a limited scope;
    • Submit structured modification proposals;
    • Apply approved file changes;
    • Run predefined validation tasks.

    The tool names, fields, and return formats here are internal designs of the implementer; it should not be assumed that a particular development kit provides these capabilities by default.

    5.1 Distinguish Model Output from Execution Facts

    The model saying “the issue has been fixed” does not mean the modification was actually written to disk; a tool returning “command started” does not mean validation has succeeded.

    The final result must be generated based on actual execution records, and at least the following should be made clear:

    • Which files were read;
    • Which locations were modified;
    • Which validations were executed;
    • Whether the validations ended normally;
    • Which conclusions remain unverified.

    If tests were not run, “validation not run” should be clearly marked, and static inferences must not be presented as confirmed results.

    5.2 Guard Against Instruction Interference in Code and Documentation

    Source files, comments, documentation, and tool output may contain persuasive text, such as requests to ignore existing rules or read sensitive files. This content is task material, not a higher-priority operational instruction.

    Prompts can remind the agent to distinguish the two, but the real defense is still external permission control: even if the model is influenced, it must not be able to break out of the allowed directories, network, and tool scope.

    6. Security Boundaries: Remote Entry Points Must Be More Conservative Than Local Interaction

    A remote coding assistant expands the attack surface. A compromised messaging account, leaked session credentials, or user error may all translate into execution risk on the server.

    6.1 Handle Identity and Authorization Separately

    Confirming that a message comes from a certain account only solves the identity problem. It is still necessary to determine whether that account is authorized to access the corresponding project and whether it has modification rights.

    Personal use scenarios should also maintain an explicit allowlist; do not treat “message received” as “authorization granted.”

    6.2 File Access Restrictions Must Cover Real Paths

    Path checks should not only exclude parent-directory traversal but also consider cases such as symbolic links. Checking a string prefix is not sufficient to prove that a file is inside the allowed directory.

    Sensitive configurations, keys, and credential files should be restricted independently. Blocking them before the tool reads them is more reliable than trying to remove sensitive content during the reply stage.

    6.3 Use Least Privilege for Command Execution

    Do not directly concatenate user messages into command strings. Use structured parameters, limit executable tasks, and set execution time limits, process resources, and output size.

    The execution environment should preferably use an isolated workspace, avoid carrying production credentials, and restrict unnecessary network access by default. Containerization can provide an isolation foundation, but it cannot replace permission, mount, and resource configuration.

    6.4 Use Preview and Confirmation for High-Risk Operations

    For operations such as deleting files, overwriting configurations, or making large-scale modifications, the system should first show the plan and a diff summary, then wait for explicit confirmation.

    Confirmation should be bound to a specific task and change version. If files change during the confirmation period, the original approval should not automatically authorize new modifications; the diff should be checked again and confirmation repeated as appropriate.

    7. Message Delivery: Provide Progress Instead of Dumping Execution Logs

    Agent tasks may take a long time. If there is only a final reply, users may easily think the request did not take effect and send it again.

    Progress can be reported in stages:

    1. Request received, with a task identifier;
    2. Task started, with the current operation scope;
    3. When confirmation is needed, show a change summary;
    4. Task finished, returning the conclusion and validation status.

    Long logs should be truncated or saved as controlled attachments to avoid flooding the chat and leaking environment information. The final message should preferably include four items: “issues found, handling approach, validation result, remaining risks.”

    Execution success and delivery success should also be recorded separately. If a task has completed but the reply failed to send, only the result should be retried, not the code modification.

    8. From a Minimal Prototype to a Reliable System

    A minimal prototype can first complete a read-only loop: receive messages from authorized users, analyze code in a fixed working directory, and return structured conclusions. At this stage, arbitrary commands are not opened, and files are not modified directly.

    The second stage adds task persistence, deduplication, cancellation, timeouts, and execution logs to verify behavior after disconnection and restart.

    The third stage introduces change proposals, approval mechanisms, isolated validation, and failure recovery. Saving a baseline snapshot or diff record before modification helps with diagnosis, but rollback must also check whether subsequent modifications exist and must not directly overwrite the work of other tasks.

    Testing should cover not only normal flows but also abnormal cases such as duplicate messages, expired sessions, path traversal, tool timeouts, failed replies, mid-task exits, and cancellation races.

    Prototype code can be small, but short code does not mean engineering completeness. What really determines reliability is whether duplicate side effects can be avoided after a failure occurs and whether execution facts can be traced.

    9. Conclusion: Build Convenience on Top of Controlled Execution

    Driving a coding agent remotely through instant messaging is essentially building a task control entry point for a code workspace. Protocol integration solves “how to receive requests,” the agent solves “how to understand and advance tasks,” and permissions, isolation, state management, and auditing solve “how to complete tasks safely.”

    A reasonable rollout order is: first implement authorized integration and read-only analysis, then improve the task lifecycle, and finally enable controlled modification and validation. Only when every file access, every change, and every execution result can be explained, confirmed, and traced does a remote coding assistant move from a convenient demo to a trustworthy part of the development toolchain.