---
description: "Platform-neutral IM host for admitting chats, storing messages with per-chat sequence numbers, hosting agent sessions, publishing with durable receipts, and driving turn output renderers."
kind: "package-reference"
---
# @deepseek-ai/dsh-im
English | [中文](README.zh.md)
## Summary
Admit IM chats by rule, store every admitted message with a per-chat sequence number, and dispatch messages on the `im/message` waterfall so mounted plugins can route them to hosted agent sessions. The package manages session records, bindings, durable inbox deliveries, outbound publication receipts, message formatting, history queries, the `im_*` tools, and per-turn activity snapshots for output renderers. It also provides an optional default dispatcher session for addressed messages that no routing plugin claims. Use the [IM profile](../im-bundle/README.md) for a complete deployment, or mount this package directly when composing custom IM automation.
## Table of Contents
- [Use this package](#use-this-package)
- [Understand the implementation](#understand-the-implementation)
- [Further Exploration](#further-exploration)
- [Model Experience](#model-experience)
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
- [Dev Note](#dev-note)
-----
## Use this package
The [IM bundle](../im-bundle/README.md) adds `@deepseek-ai/dsh-im`, the Feishu/Lark adapter, and [`session-commands`](../im-session-commands/README.md) to an existing profile, whose base layer supplies persistence, agent presets, and compaction; the operator's patch configures `defaultDispatch`. In a custom composition, mount `@deepseek-ai/dsh-im` with explicit `sources` and either mount a plugin that listens on `im/message` or configure `defaultDispatch`; without one of those, admitted messages are stored and marked `ignored` without reaching any agent.
### Responsibilities across packages
`@deepseek-ai/dsh-im` manages message storage, session hosting, access control, and tool registration, while separate plugins can handle slash commands, custom message routing, and turn rendering.
| Responsibility | Owner |
|---|---|
| Message admission, `im_messages` store, `im/message` waterfall, default dispatcher | `@deepseek-ai/dsh-im` |
| Hosted sessions (`im_sessions`), outbound publication (`im_receipts`), formatting, history | `@deepseek-ai/dsh-im` |
| Turn activity tracking (`im/activity`) and output renderer registry (`ctx.im.outputs`) | `@deepseek-ai/dsh-im` |
| `im_read`, `im_history`, `im_members`, `im_read_image`, `im_read_file`, `im_send`, `im_reply`, `im_send_file` | `@deepseek-ai/dsh-im` (when `tools` and `systemPrompt` are present) |
| Chat slash commands (`/stop`, `/clear`, `/new`, `/status`, `/help`, passthrough) | [`session-commands`](../im-session-commands/README.md) |
| Platform protocol, element normalization, mode selection, and transport adapters | `@deepseek-ai/cordis-plugin-im-core` and the Lark/QQ adapters |
### Sources and admission
Each entry in `sources` is an ordered admission rule. A rule specifies a unique `id`, a `bot` (`lark:cli_xxx`, `qq:102106848`, or `*`), optional `chats` and `users` allowlists, whether hosted sessions may publish into those chats (`writable`), and whether to store all messages or only messages that address the bot (`store`). The first matching rule admits the message, and its `id` is recorded as the `source` of the chat and message.
| Field | Default | Meaning |
|---|---|---|
| `sources[].id` | required | Unique rule id; stored on `ImChat.source` and `ImMessageEvent.source` |
| `sources[].bot` | required | Bot id, or `*` to match any mounted bot |
| `sources[].chats` | any chat | Allowed platform chat ids |
| `sources[].users` | any sender | Allowed sender user ids |
| `sources[].writable` | `false` | Whether hosted sessions may publish into chats admitted by this rule |
| `sources[].store` | `'all'` | `'all'` stores every message; `'addressed'` stores only messages that address the bot |
| `retentionMs` | 30 days | Minimum age before settled messages, event digests, delivery records, and reset receipts expire |
| `maxRecords` | `10000` | Maximum retained message records per chat and maximum retained send receipts |
| `maxInputBytes` | 256 KiB | Maximum UTF-8 byte size of one stored inbound message or delivery record |
| `retryIntervalMs` | 5 s | Interval for re-dispatching pending messages, retrying pending deliveries, and sweeping expired records |
| `compositionWarnMs` | 30 s | Warning threshold while intake dispatch and session recovery wait for Loader composition to settle |
| `platformTimeoutMs` | 30 s | Deadline of one platform request: the re-read of a card or a merged forward, and the text of a quoted reply |
| `media.download` / `media.maxBytes` / `media.maxItems` / `media.timeoutMs` | `true` / 10 MiB / 9 / 30 s | Whether to download inbound images and files into attachments, the per-item and per-message limits, and the deadline of one inbound fetch |
| `media.source.file` / `media.source.internal` | `false` / `false` | Whether a received message may make this host fetch a `file:` source, and an `http(s)` source whose host is, or resolves to, a loopback, private, link-local or multicast address |
| `send.maxMediaBytes` / `send.operationTimeoutMs` | 10 MiB / 30 s | Size limit of the bytes inlined for a file of another execution world, and the per-send timeout |
| `tools.readOnly` / `tools.maxReadBytes` / `tools.maxHistoryItems` / `tools.maxMembers` / `tools.maxMemberPages` / `tools.fileDir` | `false` / 64 KiB / 50 / 200 / 10 / `.dsh/im` | Whether to register only read tools, maximum tool output bytes, maximum `im_history` page size, maximum members and platform pages one `im_members` call reads, and the session-relative directory `im_read_file` stages a downloaded file in |
| `defaultDispatch` | absent | Optional [default dispatcher](#the-default-dispatcher): `agentPreset`, `provider`, `model`, and absolute `cwd` (required), plus `output` (`'none'`), `delivery` (`'steer'`), `restrict` (no tool restriction), and `prompt` (`im:dispatcher` at order 81) |
Messages from chats that match no rule are neither stored nor emitted. See the generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-im) for the complete schema.
### Durability and the message store
Inbound intake (`satori/receive`) resolves only after both the message record and the event deduplication record are written to `im_messages`, and the platform adapter acknowledges the event afterwards. Redelivering a `(bot, eventId)` already recorded is a no-op. A payload that drifted from the recorded one—an edited body, a mention list, a timestamp—is logged once and still acknowledged, so the platform cannot loop on the same message. Every stored message—inbound or own outbound—receives a monotonically increasing per-chat sequence number (`seq`), which `ctx.im.history` uses for pagination and lookup.
A message whose event carries less than a reader needs is re-read once at intake. A card arrives as the projection the platform is willing to describe, and a merged forward arrives as its container alone; for both, the stored content is what the platform read returns — the card JSON, and the container together with its entries. A read that would push the message past `maxInputBytes` is not used: a message over that bound is refused whole, so the reference the event carried is stored instead.
The dispatch loop runs the `im/message` waterfall for each pending message: different chats dispatch concurrently, while messages within the same chat dispatch sequentially in `seq` order. When the waterfall finishes, the store records `handled` (with the plugin name and optional session ids) or `ignored`. If a listener throws, the message remains `pending` and is retried on the next `retryIntervalMs` tick or after a restart. Listeners must therefore be idempotent: session deliveries deduplicate by delivery `id`, session resets deduplicate by `operationId`, and outbound sends deduplicate by `operationId`. Retention sweeps delete only expired settled records; pending messages and pending receipts never expire automatically. `ctx.im.status()` returns a diagnostic snapshot of mounted bots, sources, sessions, pending counts, and recent outcomes.
### Hosted sessions
`ctx.im.sessions` manages one active session per owner-defined key (such as `conversation:`, `im:dispatcher`, `task:`, or `oneshot:`). Each `ImSessionRecord` stores the agent composition (`agentPreset`, `cwd`, `provider`, `model`, optional `restrict`), chat `bindings`, `output` renderer id, optional `parent` session id, `ephemeral` flag, and owner `meta`. The `sessionId` is derived deterministically from `key` and `generation`: calling `reset` cancels and disposes the active agent, increments `generation`, and issues a new `sessionId`.
| Method | Behavior |
|---|---|
| `ensure(spec)` | Create a session record by `key`, or update `composition`, `bindings`, `output`, and `meta` on the existing record |
| `get(keyOrId)` / `list(filter)` | Look up a session record by key or `sessionId`, or list records filtered by `owner`, `chat`, or `parent` |
| `forChat(chat)` | List sessions bound to `chat` |
| `deliver(target, delivery)` | Persist a delivery intent and insert it into the session's inbox (`steer`, `followup`, or `inject`) |
| `reset(key, reason, options?)` | Cancel and dispose the active agent, delete unadmitted deliveries, advance `generation`, and return the replaced `SessionId` (recording a durable receipt when `options.operationId` is set, and skipping when `options.expectedGeneration` no longer matches) |
| `bind(target, bindings)` | Replace the chat bindings of a session |
| `stop(target)` | Cancel the running turn of a session; returns `false` if the session is not running |
| `agent(target)` | Open or resume the live `Agent` for a session using its stored composition (serializes behind in-flight `reset()`/`admit()` on the stable `key`; throws `ImError('unavailable')` for a retired `SessionId` or uncommitted reset receipt, opens the new generation by `key`, and throws `ImError('access')` if unhosted) |
| `of(sessionId)` | Walk the `parent` chain from `sessionId` to find the nearest hosted session record; the walk follows only subagent creators (`origin: 'subagent'`), so a side conversation or an ordinary fork that retained a parent id inherits no chat from its source |
| `trigger(sessionId)` | Return the `ImMessage` whose delivery started the session's current turn |
Each `ImBinding` grants access to one `chat`, with `writable` controlling publish permission, `home` marking the default chat for tools and output renderers, and `thread` restricting the binding to a specific thread. `deliver` writes the delivery intent to `im_sessions` before opening the agent, and reconciles against `agent/inbox/spliced` events in the session log on recovery so restarts never duplicate inbox messages. `steer` joins a running turn at the next step (or starts a turn if idle), `followup` queues a new turn, and `inject` adds context for the next turn without waking an idle agent.
### Outbound publication, formatting, and history
All outbound messages go through `ctx.im.send` (single message) or `ctx.im.stream` (streaming updates). Every publication also re-verifies the target chat against the current `config.sources` rule named on the stored chat record (throwing `ImError('access')` if the rule was removed or narrowed so the chat is no longer admitted, and self-healing on the next inbound frame if another configured rule now admits it). When `options.session` is provided, that session or one of its hosted ancestors must have a writable binding for the target chat. Passing `options.quote` must name a message stored in `im_messages` for the target chat (keys from another bot, another chat, or unstored/expired keys are rejected with `ImError('access')`); it prepends a `` element to the message content and attaches the quoted message's stored `referrer` to the target, enabling platform thread placement and passive replies. Passing `options.referrer` hands the adapter an explicit reply context — the `referrer` of an interaction the publication answers, such as a QQ button click, so the answer is a passive reply to that click; it replaces the referrer a quote or thread would supply, grants no access, and is not part of the receipt digest. Passing `options.thread` targets a specific thread id, or `true` to reply in the quoted message's thread. An explicit `thread` string must belong to the target chat: the sender reuses a matching stored message's `referrer` when available, otherwise the adapter resolves and verifies the anchor against the platform (`published: 'no'` if resolution or chat ownership fails). When every writable binding of `options.session` for the chat is confined to `thread`, `options.thread` is omitted, and `options.quote` names a thread root message (one with no `thread` field of its own), `send` and `stream` forward that root message id as `Target.thread` so the reply stays in the thread. A publication that names neither a thread nor a message stays in the thread its session answered last (`ImSessions.trigger`): that is where the session's own answers go, because output renderers quote the trigger and inherit its thread, so the chat's own timeline is not where a task's work belongs. A session confined to `thread` therefore publishes into the answered thread without naming it, and a bare publication is refused only when the answered message belongs to another thread.
When `options.operationId` is provided, the sender writes a `pending` receipt to `im_receipts` before calling the platform, then updates it to `confirmed`, `failed` (when the platform explicitly rejected the send before publishing), `partial` (when a multi-part send or an opened stream failed after publishing at least one part or frame that remains in the chat), or `uncertain` (on network failure, timeout, cancellation after dispatch, or an unrecorded crash state). Replaying the same `operationId` with the same target and content returns the stored receipt without resending; reusing an `operationId` with different parameters throws a `conflict` error.
Published content names its media by URL. A `data:` or `base64:` source carries its own bytes and a `satori:` source is resolved by the core; a `file:` or `http(s)` source is fetched by this process during prepare, through `ctx.http` — the same service every plugin uses, with no scheme or address policy. `im_send_file` therefore publishes the file at the path the session names as an absolute `file:` URL when the filesystem is host-backed, and inlines the bytes only for a working directory in another execution world (an SSH workspace), bounded by `send.maxMediaBytes`. Nothing confines that path: `cwd` is only the base for a relative one, `~` expands, and the read range is whatever this process can open.
`ctx.im.format` converts stored `ImMessage` records into model-facing user message content:
- `xml` (default): formats each message as `正文 [图片 #12.1]`, adding `self="true"` for own messages and `quote="#10"` when quoting a stored message in the same chat.
- `line`: formats each message as a single line (`#12 14:07 张三(u_1) ↩#10 李四: 原文: 正文`) for compact history inspection.
Media elements in message text are replaced with stable per-chat labels such as `[图片 #12.1]` or `[文件 #12.2 report.pdf]`. When `media: true` is passed to `format`, admitted images are downloaded into attachments and appended as `image` content blocks after the text block, and every other admitted element (a file, voice message, or video) is stored verbatim and appended as a `file` content block, which request assembly projects to the read-only saved path.
Because the sender writes the message, and not the session reading it, a download is refused before any I/O unless `media.source` accepts the source: a `file:` element (a path of this host) and an `http(s)` element whose host is, or resolves to, a loopback, private, link-local or multicast address are reported as skipped in the transcript instead of being fetched. Inline `data:`/`base64:` sources are always admitted, and a `satori:` resource is admitted under the route of the bot that received the message only: the adapter downloads it with that application's credentials, so within that route a message id and resource key a member names are fetched even when they belong to a chat no source admits. The fetch that follows does not follow a redirect (a 3xx answer is skipped), a host the resolver cannot answer for is refused, and the whole download, body included, ends at `media.timeoutMs` (default 30 s). The address rule classifies the answer of one lookup and does not pin the connection to it: the fetch resolves the name again, so a name whose answer changes in between (DNS rebinding) can still reach an address the rule refuses.
A `forward` element renders as one line: `[合并转发 #id]` while nothing has read its entries, otherwise `[合并转发 #id: 名字: 内容 …]` with a bounded preview. `im_read` of a stored reference expands it through a platform read, so the entries are readable without the store having to be rewritten, and `im_read_image` or `im_read_file` of a label inside one takes the same read — which is what puts a forwarded conversation's pictures and files where its media refs can find them. A forward nested in the entries keeps a `[合并转发 #id]` line of its own, with the entries that follow it indented under it: the platform returns the whole tree in one answer.
### Activity tracking and output renderers
For each turn of a hosted session, the activity tracker builds an `ImActivity` snapshot containing the turn number, status (`running`, `done`, `cancelled`, `error`), trigger message, and ordered `segments` (accumulated assistant `text`, `reasoning`, and `tool` calls with bounded argument and result previews). Every update emits `im/activity` with the change kind (`start`, `delta`, `tool`, `end`).
If a session's `output` names a renderer a mounted plugin registered, `ctx.im.outputs` calls `renderer.begin(activity, io)` on `start`, `update(activity, change)` on `delta` and `tool`, and `end(activity)` on `end`. The target chat is the trigger message's chat when the session has a writable binding for it, or the session's writable `home` binding otherwise; if neither is writable, nothing is rendered. When `output` is `'none'` (the default), no renderer runs and the agent publishes only when it calls `im_send`, `im_reply`, or `im_send_file`. `ctx.im.outputs` also re-emits button clicks in admitted chats as `im/button`, option picks in a `