Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
package dingtalk
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/dbid"
)
// originDingTalkChat is the issue.origin_type label for issues created through
// the DingTalk /issue command. Keep it aligned with the database CHECK
// constraint, like the existing lark_chat and slack_chat channel origins.
const originDingTalkChat = "dingtalk_chat"
// This file is the DingTalk ResolverSet: the platform-specific seams the
// channel-agnostic engine.Router runs the inbound pipeline through. It is built
// entirely on the generic channel_* queries plus the shared engine.ChatSession,
// mirroring the Feishu and Slack ResolverSets.
// NewDingTalkResolverSet assembles the DingTalk ResolverSet over the generated
// queries + a tx starter (for the shared session service). The replier delivers
// the outbound binding-prompt / status / issue-created notices; pass a nil
// engine.OutboundReplier to disable them. The classic robot send API exposes no
// per-message reaction, so the ack notifier stands in for a typing indicator (a
// "working on it" message on ingest); pass nil to disable it. Media is optional:
// when configured it uses the shared MediaResolver and intent-ledger pipeline.
func NewDingTalkResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OutboundReplier, ack *ackNotifier, media engine.MediaResolver, botNames *BotNameResolver) engine.ResolverSet {
groupPresence := &groupPresenceObserver{
q: q,
botNames: botNames,
logger: slog.Default(),
}
set := engine.ResolverSet{
Installation: &installationResolver{q: q},
Identity: &identityResolver{q: q},
Dedup: &deduper{q: q},
Session: &sessionBinder{session: engine.NewChatSession(q, tx, TypeDingTalk, engine.SessionTitles{
Group: "DingTalk group",
Direct: "DingTalk direct message",
Fallback: "DingTalk chat",
}), groupPresence: groupPresence, replies: replyClient(ack)},
Audit: &auditor{q: q},
Replier: replier,
OriginType: originDingTalkChat,
}
// Guard against assigning a nil *ackNotifier into the interface field (which
// would make set.Typing a non-nil typed-nil); mirrors Slack/Feishu.
if ack != nil {
set.Typing = ack
}
if media != nil {
set.Media = media
}
return set
}
var (
_ engine.InstallationResolver = (*installationResolver)(nil)
_ engine.IdentityResolver = (*identityResolver)(nil)
_ engine.Deduper = (*deduper)(nil)
_ engine.SessionBinder = (*sessionBinder)(nil)
_ engine.Auditor = (*auditor)(nil)
)
// dingtalkBindingConfig is the opaque outbound routing persisted on the chat
// binding's config: enough to address a proactive reply back into the
// originating conversation. StaffID is the lone recipient of a 1:1 chat; for a
// group it is empty (the group is addressed by its conversation id).
type dingtalkBindingConfig struct {
ConversationType string `json:"conversation_type"`
ConversationID string `json:"conversation_id"`
StaffID string `json:"staff_id,omitempty"`
}
// dingtalkSessionRouting derives the session-isolation key and the outbound
// routing config from one inbound message. DingTalk has no threads, so a
// conversation (1:1 or group) is one continuous session keyed by its
// conversation id; the config carries everything the outbound path needs to send
// back.
func dingtalkSessionRouting(msg channel.InboundMessage) (bindingKey string, config []byte) {
chatID := msg.Source.ChatID
cfg := dingtalkBindingConfig{
ConversationType: convTypeGroup,
ConversationID: chatID,
}
if msg.Source.ChatType == channel.ChatTypeP2P {
cfg.ConversationType = convTypeP2P
cfg.StaffID = msg.Source.SenderID
}
raw, _ := json.Marshal(cfg)
return chatID, raw
}
// dingtalkVisibleQuoteText returns only the current user-authored turn for the
// Markdown quote shown in a group reply. The adapter's raw CurrentText keeps
// media placeholders in order without the quoted history.
// CommandText remains the fallback for older/internal callers.
func dingtalkVisibleQuoteText(msg channel.InboundMessage) string {
if raw, err := decodeDingTalkRaw(msg); err == nil {
if quote := strings.TrimSpace(raw.CurrentText); quote != "" {
return quote
}
}
quote := strings.TrimSpace(msg.CommandText)
if quote == "" {
// Older/internal callers may not populate CommandText. Falling back is
// safe only when Text has not been reply-enriched and is not media.
if msg.ReplyTo != nil || msg.Type == channel.MsgTypeImage {
return ""
}
quote = strings.TrimSpace(msg.Text)
}
return quote
}
// outboundTarget recovers the send target from a chat binding's config, falling
// back to the channel_chat_id when the config is missing or unparsable.
func outboundTarget(b db.ChannelChatSessionBinding) sendTarget {
target := sendTarget{ConversationType: convTypeGroup, ConversationID: b.ChannelChatID}
if len(b.Config) > 0 {
var cfg dingtalkBindingConfig
if err := json.Unmarshal(b.Config, &cfg); err == nil {
if cfg.ConversationType != "" {
target.ConversationType = cfg.ConversationType
}
if cfg.ConversationID != "" {
target.ConversationID = cfg.ConversationID
}
target.StaffID = cfg.StaffID
}
}
return target
}
func decodeDingTalkRaw(msg channel.InboundMessage) (dingtalkRawEvent, error) {
var raw dingtalkRawEvent
if len(msg.Raw) == 0 {
return dingtalkRawEvent{}, errors.New("dingtalk: inbound message Raw is empty")
}
if err := json.Unmarshal(msg.Raw, &raw); err != nil {
return dingtalkRawEvent{}, fmt.Errorf("decode dingtalk inbound raw: %w", err)
}
return raw, nil
}
func nullText(s string) pgtype.Text {
if s == "" {
return pgtype.Text{}
}
return pgtype.Text{String: s, Valid: true}
}
// ---- installation routing ----
type installationResolver struct{ q *db.Queries }
func (r *installationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
raw, err := decodeDingTalkRaw(msg)
if err != nil {
return engine.ResolvedInstallation{}, err
}
// Route by the AppKey the receiving connection stamped into the envelope.
// Each installation has its own Stream connection, so the stamped AppKey
// uniquely identifies the installation (the DingTalk callback itself carries
// no robot code).
inst, err := r.q.GetChannelInstallationByAppID(ctx, db.GetChannelInstallationByAppIDParams{
ChannelType: string(TypeDingTalk),
AppID: raw.AppID,
})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return engine.ResolvedInstallation{}, engine.ErrInstallationNotFound
}
return engine.ResolvedInstallation{}, err
}
return engine.ResolvedInstallation{
ID: inst.ID,
WorkspaceID: inst.WorkspaceID,
AgentID: inst.AgentID,
InstallerUserID: inst.InstallerUserID,
Active: inst.Status == "active",
Platform: inst,
}, nil
}
// ---- identity ----
type identityResolver struct{ q *db.Queries }
func (r *identityResolver) ResolveSender(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) (engine.ResolvedIdentity, error) {
binding, err := r.q.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{
InstallationID: inst.ID,
ChannelUserID: msg.Source.SenderID,
})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return engine.ResolvedIdentity{}, engine.ErrSenderUnbound
}
return engine.ResolvedIdentity{}, err
}
// Binding existence no longer proves membership (no FK); re-check.
if _, err := r.q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
UserID: binding.MulticaUserID,
WorkspaceID: inst.WorkspaceID,
}); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return engine.ResolvedIdentity{}, engine.ErrSenderNotMember
}
return engine.ResolvedIdentity{}, err
}
return engine.ResolvedIdentity{UserID: binding.MulticaUserID}, nil
}
// ---- dedup ----
type deduper struct{ q *db.Queries }
func (r *deduper) Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (pgtype.UUID, error) {
claim, err := r.q.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{
InstallationID: installationID,
MessageID: messageID,
})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return pgtype.UUID{}, engine.ErrDuplicate
}
return pgtype.UUID{}, err
}
return claim.ClaimToken, nil
}
func (r *deduper) Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
_, err := r.q.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
InstallationID: installationID,
MessageID: messageID,
ClaimToken: claimToken,
})
return err
}
func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
_, err := r.q.ReleaseChannelInboundDedup(ctx, db.ReleaseChannelInboundDedupParams{
InstallationID: installationID,
MessageID: messageID,
ClaimToken: claimToken,
})
return err
}
// ---- session bind / append ----
type chatSession interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
StartSession(ctx context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error)
MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}
type groupPresenceQueries interface {
UpsertDingTalkBotIdentity(ctx context.Context, arg db.UpsertDingTalkBotIdentityParams) (pgtype.UUID, error)
RecordDingTalkGroupPresence(ctx context.Context, arg db.RecordDingTalkGroupPresenceParams) (pgtype.UUID, error)
RecordDingTalkGroupActivity(ctx context.Context, arg db.RecordDingTalkGroupActivityParams) (pgtype.UUID, error)
}
// groupPresenceObserver records product metadata after group-addressing and
// sender-membership checks have accepted the message.
type groupPresenceObserver struct {
q groupPresenceQueries
botNames *BotNameResolver
logger *slog.Logger
}
func (o *groupPresenceObserver) Observe(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) error {
if o == nil || o.q == nil || msg.Source.ChatType != channel.ChatTypeGroup {
return nil
}
raw, err := decodeDingTalkRaw(msg)
if err != nil {
return err
}
botName := ""
botIdentityIssue := ""
if o.botNames != nil {
if installation, ok := inst.Platform.(db.ChannelInstallation); ok {
botName, err = o.botNames.Resolve(ctx, installation, msg.Source.ChatID)
if err != nil {
if errors.Is(err, errMissingChatManagePermission) {
botIdentityIssue = botIdentityIssueMissingChatManage
}
logger := o.logger
if logger == nil {
logger = slog.Default()
}
logger.WarnContext(ctx, "dingtalk: could not resolve readable bot identity",
"installation_id", inst.ID,
"conversation_id", msg.Source.ChatID,
"error", err,
)
botName = ""
}
}
}
_, err = o.q.UpsertDingTalkBotIdentity(ctx, db.UpsertDingTalkBotIdentityParams{
BotName: botName,
BotIdentityIssue: botIdentityIssue,
InstallationID: inst.ID,
WorkspaceID: inst.WorkspaceID,
})
if err != nil {
return err
}
_, err = o.q.RecordDingTalkGroupPresence(ctx, db.RecordDingTalkGroupPresenceParams{
ConversationID: msg.Source.ChatID,
ConversationTitle: raw.ConversationTitle,
InstallationID: inst.ID,
WorkspaceID: inst.WorkspaceID,
})
return err
}
// RecordActivity advances the counters only after AppendUserMessage commits.
// Presence discovery runs earlier, after addressing and membership checks, but
// counting there would include messages whose durable append later fails.
func (o *groupPresenceObserver) RecordActivity(ctx context.Context, installationID pgtype.UUID, msg channel.InboundMessage) error {
if o == nil || o.q == nil || msg.Source.ChatType != channel.ChatTypeGroup {
return nil
}
_, err := o.q.RecordDingTalkGroupActivity(ctx, db.RecordDingTalkGroupActivityParams{
InstallationID: installationID,
ConversationID: msg.Source.ChatID,
})
return err
}
func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {
bindingKey, config := dingtalkSessionRouting(p.Message)
var release func()
defer func() {
if release != nil {
release()
}
}()
beforeCommit := p.BeforeCommit
if p.PersistMessage {
beforeCommit = func(ctx context.Context, tx pgx.Tx, session db.ChatSession) error {
release = r.replies.beginReplyInput(session.ID)
if p.BeforeCommit != nil {
return p.BeforeCommit(ctx, tx, session)
}
return nil
}
}
result, err := r.session.StartSession(ctx, engine.StartSessionInput{
EnsureSessionInput: engine.EnsureSessionInput{
WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,
InstallationID: p.Installation.ID, Sender: p.Creator,
BindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,
},
Initiator: p.Sender,
Body: p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID, ThreadID: p.Message.Source.ThreadID,
ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,
BeforeCommit: beforeCommit,
})
if err != nil {
return engine.StartSessionResult{}, err
}
if err := r.groupPresence.Observe(ctx, p.Installation, p.Message); err != nil {
logger := slog.Default()
if r.groupPresence != nil && r.groupPresence.logger != nil {
logger = r.groupPresence.logger
}
logger.WarnContext(ctx, "dingtalk: could not record group presence",
"installation_id", p.Installation.ID,
"conversation_id", p.Message.Source.ChatID,
"error", err,
)
}
if p.PersistMessage {
r.replies.rememberReplySource(p.Installation.ID, result.Append.MessageID, result.SessionID, p.Message)
if err := r.groupPresence.RecordActivity(ctx, p.Installation.ID, p.Message); err != nil {
logger := slog.Default()
if r.groupPresence != nil && r.groupPresence.logger != nil {
logger = r.groupPresence.logger
}
logger.WarnContext(ctx, "dingtalk: could not record group activity",
"installation_id", p.Installation.ID,
"conversation_id", p.Message.Source.ChatID,
"error", err,
)
}
}
return engine.StartSessionResult{
SessionID: result.SessionID, BindingID: result.BindingID,
RouteRevision: result.RouteRevision, Append: result.Append,
}, nil
}
type sessionBinder struct {
replies *Client
session chatSession
groupPresence *groupPresenceObserver
}
func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
bindingKey, config := dingtalkSessionRouting(p.Message)
sessionID, err := r.session.EnsureSession(ctx, engine.EnsureSessionInput{
WorkspaceID: p.Installation.WorkspaceID,
AgentID: p.Installation.AgentID,
InstallationID: p.Installation.ID,
Sender: p.Sender,
BindingKey: bindingKey,
BindingConfig: config,
ChatType: p.Message.Source.ChatType,
})
if err != nil {
return pgtype.UUID{}, err
}
// Group inventory is best-effort metadata. A lookup or write failure must
// not turn a valid group mention into a failed chat message.
if err := r.groupPresence.Observe(ctx, p.Installation, p.Message); err != nil {
logger := slog.Default()
if r.groupPresence != nil && r.groupPresence.logger != nil {
logger = r.groupPresence.logger
}
logger.WarnContext(ctx, "dingtalk: could not record group presence",
"installation_id", p.Installation.ID,
"conversation_id", p.Message.Source.ChatID,
"error", err,
)
}
return sessionID, nil
}
func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
return r.session.MarkPendingFresh(ctx, sessionID, messageID)
}
func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
release := r.replies.beginReplyInput(p.SessionID)
defer release()
commandText := p.Message.CommandText
if commandText == "" {
commandText = p.Message.Text
}
result, err := r.session.AppendUserMessage(ctx, engine.AppendInput{
SessionID: p.SessionID,
Sender: p.Sender,
InstallationID: p.InstallationID,
Body: p.Message.Text,
CommandText: commandText,
MessageID: p.Message.MessageID,
ThreadID: p.Message.Source.ThreadID,
ClaimToken: p.ClaimToken,
MediaPendingSeconds: p.MediaPendingSeconds,
ForceFresh: p.Message.ForceFresh,
})
if err != nil {
return engine.AppendResult{}, err
}
// Group inventory is best-effort product metadata. The message and dedup
// mark are already durable, so a counter write failure must not release the
// claim or make DingTalk retry and risk a duplicate user-visible turn.
if err := r.groupPresence.RecordActivity(ctx, p.InstallationID, p.Message); err != nil {
logger := slog.Default()
if r.groupPresence != nil && r.groupPresence.logger != nil {
logger = r.groupPresence.logger
}
logger.WarnContext(ctx, "dingtalk: could not record group activity",
"installation_id", p.InstallationID,
"conversation_id", p.Message.Source.ChatID,
"error", err,
)
}
r.replies.rememberReplySource(p.InstallationID, result.MessageID, p.SessionID, p.Message)
return result, nil
}
func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) (engine.BindMediaResult, error) {
in := engine.BindMediaInput{
MessageID: p.MessageID,
SessionID: p.SessionID,
WorkspaceID: p.WorkspaceID,
Sender: p.Sender,
IssueID: p.IssueID,
IssueDescriptionBase: p.IssueDescriptionBase,
IssueCommandText: p.IssueCommandText,
Body: p.Body,
MediaRefs: p.MediaRefs,
}
if richer, ok := r.session.(interface {
BindMediaRefsWithResult(context.Context, engine.BindMediaInput) (engine.BindMediaResult, error)
}); ok {
return richer.BindMediaRefsWithResult(ctx, in)
}
return engine.BindMediaResult{}, r.session.BindMediaRefs(ctx, in)
}
// ---- audit ----
type auditor struct{ q *db.Queries }
func (r *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
return r.q.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
ID: dbid.NewV7(),
ChannelType: string(TypeDingTalk),
EventType: "message",
DropReason: string(reason),
InstallationID: instID,
ChannelChatID: nullText(msg.Source.ChatID),
ChannelEventID: nullText(msg.EventID),
ChannelMessageID: nullText(msg.MessageID),
})
}
// replyClient keeps notifier attribution local to the DingTalk adapter.
func replyClient(ack *ackNotifier) *Client {
if ack == nil {
return nil
}
return ack.client
}