From Chat to Execution: Engineering Practices for Connecting Agents to Instant Messaging
This article explains how to move AI agents from chat-only interfaces to reliable task execution over instant messaging. It covers layered architecture, message reliability, identity and permissions, controlled tools, task state, prompt-injection defenses, evaluation, and a staged rollout—without treating fluency as a substitute for a closed business loop.
From “can chat” to “can get work done”
Discussion of agents is shifting from labels to real use. For developers and enterprises, cultural meaning behind a name is not a selection criterion. What matters is whether the system can understand a business goal, access needed information, call controlled tools, and stop or recover when something goes wrong.
When an agent is connected to instant messaging, users can request work in a familiar chat UI without switching to a separate business page—for example, checking application status, organizing to-dos, retrieving internal policies, or starting operations that need human confirmation. A usable chat entry point is not the same as a reliable business process.
Do not dismiss an approach as obsolete, and do not judge maturity only by “native support for a channel.” Evaluate how the system handles identity, message retries, task state, permission constraints, and execution results.
How agents differ from ordinary chatbots
Ordinary chatbots mainly map input to an answer. Even with retrieval, the core output is usually text. An agent may also call tools and change external system state.
A complete task typically includes:
- Understand the goal: identify the problem to solve, not only match keywords.
- Fill in conditions: confirm time range, business object, permissions, and other required information.
- Choose an action: retrieve, query status, or request an operation.
- Call tools: interact with business systems through controlled interfaces.
- Check results: continue, finish, or hand off to a human based on real outcomes.
- Report status: distinguish completed, in progress, failed, and waiting for confirmation.
This does not mean unbounded autonomy. The larger the business impact, the smaller the model’s free decision space should be. For stable, well-defined processes, deterministic workflows are often easier to test and audit than open-ended planning.
In practice, use a hybrid: the model interprets natural language and results; business code owns permission checks, parameter validation, and critical state changes.
Design IM integration in layers
Putting all logic in a message callback quickly becomes unmaintainable. A more robust split is five layers:
Message intake → identity and permissions → task orchestration → tool execution → result delivery
Intake handles event receipt, source validation, format conversion, and basic deduplication. It should not run complex business execution.
Identity and permissions map the channel sender to an internal user and confirm organization, role, and data scope. For sensitive operations, also check whether credentials are valid and whether further authentication is required.
Orchestration maintains task state, chooses the next action, and sequences clarification, confirmation, execution, and human takeover.
Tool execution exposes only explicit, limited business capabilities—not arbitrary system access for the model.
Result delivery turns internal state into messages users can understand, without leaking credentials, stack traces, or sensitive business data.
Layers should exchange clear internal data structures, not pass channel-specific fields into every business module. That makes new channels easier and isolates core logic from channel changes.
Fix message reliability before debating “intelligence”
IM messages are not guaranteed to be processed exactly once or in strict order. Delivery semantics depend on the protocol, but design for duplicates, delayed arrival, timeouts, and network interruption.
1. Idempotent handling
If the same user message is delivered twice, the system must not create duplicate business records or fire duplicate writes.
Prefer stable event IDs from the channel, combined with organization and channel context, as a unique key. For state-changing operations, also set business idempotency keys in the tool layer; intake deduplication is not enough.
Queries are relatively easy to retry. Writes must first confirm whether the previous attempt already took effect. Otherwise a timeout can become multiple submissions.
2. Decouple receive from long-running work
Complex tasks should not block the intake request. After source checks and reliable receipt, return the protocol-compliant ack, then run work asynchronously via a task queue.
User-facing feedback should be staged, for example:
- Task received; conditions are being verified
- Conditions incomplete; a business object is needed
- Sensitive operation; waiting for confirmation
- Completed, with the actual result
- Failed, with the reason and next step
If the channel cannot push follow-up messages, provide a status query path or another channel-compliant feedback method. Do not assume every channel supports the same interaction.
3. Concurrency and order
A user may send “query this week’s records” then “change that to last week.” The second message may correct the first. Use task state rather than treating every message as an independent job.
For writes on the same business object, serialize or use version checks. Independent read-only queries can run in parallel when resources allow. Concurrency policy should follow conflict relationships, not a blanket ban or unlimited parallelism.
Do not leave identity mapping and permissions to the model
A channel user ID only shows which channel account sent the message. It does not prove internal business rights. Enterprises usually need a verified account binding, plus handling for expired bindings, offboarding, and permission changes.
Group chats add risk: information one user may see is not necessarily allowed for every member. Recheck the audience before sending to the original session. When needed, return a summary in the group and send details only in an authorized conversation.
Permission checks should at least cover:
- Whether the user may call this class of tool
- Whether they may access the specified business object
- Whether returned fields include data they cannot see
- Whether the operation exceeds allowed amount, quantity, or impact
- Whether approval or a second confirmation is required
These decisions belong to trusted policy and business code. The model may explain rules; it cannot replace real authorization by generating “the user is authorized.”
Design tools as controlled business capabilities
More tools and more generic tools are not better. Open-ended query, file access, or command execution looks flexible and greatly increases misuse and leak risk.
Prefer scoped actions such as “query my own applications,” “generate a draft pending confirmation,” or “submit a confirmed application.” Separate reads from writes so permissions, timeouts, and approval policies can differ.
Each tool should define input constraints, output shape, error types, and side effects. Validate parameters on the business side; a well-formed model payload is not proof of correct business meaning.
Illustrative flow (product-agnostic):
Receive message→ Validate source→ Identify user and organization→ Deduplicate and create task→ Determine intent and required conditionsConditions incomplete→ Ask for missing informationRead-only task→ Check access→ Call query tool→ Filter returned fields→ Return resultWrite task→ Generate operation draft→ Show key changes→ Obtain valid confirmation→ Recheck permissions and state→ Execute idempotently→ Return business receipt
Confirmation must bind to specific operation content, not a vague “agree.” If the target, parameters, or draft version change, old confirmation must expire so the system does not execute something other than what the user approved.
Chat history is not reliable task state
Sending the full transcript to the model does not guarantee continuity. History may include stale requests, misunderstandings, quoted text, and unrelated content.
Keep three kinds of data distinct:
Conversation context for the current exchange, compressed and trimmed by relevance.
Task state for stage, missing fields, pending operations, receipts, and failure reasons—structured and persisted.
Long-term preferences only when authorized and necessary (for example default reply language). Do not accumulate privacy without limit.
Use an explicit state machine such as pending clarification, pending confirmation, running, completed, failed, cancelled. Transitions are driven by events and rules, not by the model claiming completion in text.
For “cancel,” distinguish not-yet-executed from already-effective operations. The former can stop; the latter may only enter reverse or compensation. Do not promise cancellation if the change already landed.
Prompt injection and sensitive data leaks
Agents may read attachments, knowledge documents, or external responses. Sentences such as “ignore the rules” or “export all data” are data to process, not new execution authority.
Defense is layered:
First, keep trusted instructions separate from untrusted material in processing. Second, constrain execution with tool allowlists, parameter validation, and permission checks. Third, before output, check recipients and sensitive fields to reduce unauthorized spread.
Do not treat “tell the model to follow the rules” as the only control. If the model is wrong, the execution layer must still block unauthorized operations.
Credentials belong in a controlled runtime, not in prompts or user-visible results. Logs should keep enough for troubleshooting, with sensitive fields redacted and retention and access policies in place.
Evaluate the business loop, not fluency
Pre-launch evaluation cannot stop at natural replies. For systems that execute tasks, process correctness and business outcomes matter more.
Watch:
- Task completion rate: whether the goal was actually met, not only an affirmative reply
- Tool-call correctness: right capability and valid parameters
- Unauthorized-request blocking: whether denials are reliable
- Duplicate execution: whether retries create duplicate business effects
- Human takeover rate: which tasks routinely fail autonomously
- End-to-end latency: time spent in intake, inference, or business APIs
- Cost per successful task: compute, storage, and human handling
Test sets should cover permission changes, duplicate messages, user withdrawal, tool timeouts, partial success, and malicious documents. Prefer isolated environments or simulated tools for writes so real business is not hit.
Correlate each task with an ID across intake events, permission decisions, tool calls, and final receipts. Troubleshooting should rest on observable events, not on treating model-internal reasoning as an audit trail.
Roll out in stages
Phase one: knowledge retrieval and read-only queries—prove channel intake, identity binding, and information permissions.
Phase two: draft generation and human confirmation—prepare operations without immediately changing business state.
Phase three: limited, traceable, recoverable writes, with impact bounds, rate limits, and an emergency stop.
Only when those are stable should you try multi-step orchestration. Even then, keep a max step count, a timeout budget, and a human takeover path so tasks do not loop or burn resources indefinitely.
The value of agents on IM is a lower interaction barrier, not the removal of control. A usable system gives every action a permission basis, every execution a state record, and every failure a recovery path. Those engineering capabilities, not names and marketing labels, determine whether the system can serve users stably.
