* feat(i18n): layered catalogs — plugin packs and user overlay over bundled locales
* feat(tui): i18n layer — en catalog, nanostore runtime, RPC pack loader, _keys.tui.json emitter
ui-tui/src/i18n/: en.ts (facade over topical siblings under en/), types.ts
(Translations + dotted TranslationKey derived from en), runtime.ts ($locale/
$catalog atoms, translateFrom active→en→key, pack merge with string→fn
wrapping for {0}/{1} placeholders), loader.ts (display.language →
i18n.catalog {lang, surface:'tui'}, English when the method is missing),
useT()/useLocale() hooks, t() for non-React code. useConfigSync feeds the
loader from the existing config.get full hydration. `npm run i18n:keys`
writes locales/_keys.tui.json (sorted flat key list) and runs before build.
* feat(plugins): provides_locales manifest field, ctx.register_locale/register_locale_dir, manifest-only language packs
* chore(tui): split en catalog siblings by lane (slash sibling)
* feat(plugins): validate language packs — parse, text-only, key-subset WARN against en / _keys exports
* feat(tui_gateway): i18n.languages / i18n.catalog RPC + regenerated contracts
* feat(config): display.language accepts any supported_languages() id, refuses unknown ids with the list
* docs(i18n): language packs user guide, pluggable display.language, plugin developer section, AGENTS notes
* feat(plugins): report language-pack layers in the mid-run activation summary
* feat(tui): wire status bar, composer placeholders, hotkey help and approval/clarify/confirm prompts through i18n
StatusRule maps compared state values (ready/running…/summoning) to catalog
text at render via displayStatus(); hotkeys()/placeholder() resolve lazily so
a pack that arrives after boot applies. Catalog grows to 81 keys.
* feat(desktop): pluggable app locales — registry, host.i18n.registerAppLocale, backend packs, keys emitter
- Locale widens to string (BundledLocale keeps the union); TRANSLATIONS stays
the bundled record and every consumer resolves through the registry.
- src/i18n/registry.ts: registerAppLocale(id, {endonym, rtl, translations})
layers partial packs (nested or flat dotted) over bundled/en via
mergeTranslations; a string over a function-valued en entry becomes a
positional {0}/{1} formatter; $appLocaleVersion bumps so translators
re-render; per-source disposers + replaceAppLocaleSource for atomic swaps.
- Backend packs: i18n.languages + i18n.catalog {surface:'desktop'} feed the
registry as source 'backend' (method-not-found is silent); re-synced on
socket open, display.language change and profile switch. A saved pack-only
language is promoted once its pack registers.
- SDK: host.i18n.registerAppLocale / languageOptions; ctx.i18n.registerAppLocale
tracked for unload. Docs in the desktop plugin SDK guide + skill reference.
- Language switcher lists bundled ∪ registered ∪ backend, endonym-only; RTL
from the registry (applyDocumentLocale takes rtl).
- npm run i18n:keys emits locales/_keys.desktop.json (wired into build).
* i18n(cli): route /topup + /subscription copy through t() (cli.billing.*, cli.subscription.*)
Module-level copy tables and modal choice tuples in cli_billing_mixin.py froze
English at import, before display.language was known. They are now key tables /
builder functions evaluated at call time; every user-facing line in the /usage
balance block, /subscription and the five /topup screens reads the catalog.
Choice VALUES stay English identifiers. Fragment-assembled status lines
(Plan: … → cancels · $x left · renews …) become full templates.
* i18n(gateway): exec-approval card contract + base/run/run_busy/run_inbound replies through t()
- base_exec_approval: EA_* English constants stay; add ea_header_text()/ea_reason_label_text()/
ea_smart_deny_line_text()/ea_default_reason_text()/ea_action_labels()/approval_timed_out_notice()
accessors; deadline + timed-out notice resolve via gateway.exec_approval.*
- BasePlatformAdapter._EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/_EA_ACTION_LABELS become
properties (adapters still shadow them with markup class attrs)
- run.py: provider error replies table holds catalog keys; _CONTEXT_OVERFLOW_REPLY -> _context_overflow_reply()
- run_busy/run_inbound: typed approval + slash-confirm matchers accept English ∪ approval.inputs.* (t())
- locales/en.yaml: gateway.exec_approval/busy/errors/... namespaces
* i18n(cli): wire modal, loops, agent-setup mixins through t() (cli.* keys)
* i18n(platforms): route Slack, Matrix and Feishu user-facing text through t()
Exec-approval markup overrides (_EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/
_EA_ACTION_LABELS) become per-call properties over the shared
gateway.exec_approval.* contract keys, so Slack's 3000-char section budget
measures the resolved template. Slack _APPROVAL_DECISIONS/_CONFIRM_DECISIONS,
Feishu _APPROVAL_LABEL_MAP and Matrix _EA_LEGEND/_EA_TYPED_HINT turn into
key tables resolved at click time; the Matrix typed hints become whole
sentences per offered tier instead of spliced fragments. Slack button labels
are cut to 75 chars and select placeholders to 150 after translation; the
model-facing clarify fallback answer ('choice N') stays English while the
card copy localizes.
locales/en.yaml gains the gateway.exec_approval.* contract keys plus the
platform.shared.* / platform.slack.* / platform.matrix.* / platform.feishu.*
namespaces (and the keys for the other adapters wired in follow-up commits).
* i18n(gateway): run_turn / run_turn_runner / approval-settle copy through t()
- status hints, proxy errors, background task notices, progress heartbeats, session info lines
- tool progress chrome (tool_head/tool_pending/tool_preview/tool_verbose) shared by base.format_tool_event
- run_turn_runner:1406 Chinese clarify placeholder -> gateway.clarify.native_stream_placeholder (zh text kept in zh.yaml)
- _UNEXPECTED_SILENCE_REPLY/_CLARIFY_EXPIRED_NOTICE -> accessor functions
* i18n(platforms): route Google Chat and Teams user-facing text through t()
Google Chat clarify card, typing placeholder, orphan-card labels and the whole
/setup-files reply set (module constants become platform.google_chat.setup_files.*
keys resolved at reply time). The attachment-fallback notice that shipped
hardcoded in Spanish is keyed with an English en value; es.yaml carries the
original Spanish text for those four keys.
Teams approval card header/reason use the gateway.exec_approval.* contract,
_APPROVAL_LABELS becomes a key table resolved at click time, and the meeting
summary writer resolves its section headings/fallbacks per render.
* i18n(platforms): route LINE, WeCom, email, DingTalk, IRC and Home Assistant text through t()
LINE default copy constants become catalog keys resolved in __init__ (the
LINE_*_TEXT / extra.* operator overrides still win); the busy-ack bypass
matcher keys on the leading emoji marker only, so it keeps firing once the
gateway busy heads are localized. WeCom media size/format notices that shipped
hardcoded in Chinese are keyed with English en values and zh.yaml carries the
original Chinese text. DingTalk emotion bubbles resolve per send.
* i18n(cli): route /model switch output and -q status lines through t() (cli.model.*, cli.single_query.*)
Switch-summary labels shared with the gateway reuse gateway.model.* keys
(provider/context/max-output/capabilities/prompt-caching); CLI-only variants
(glyph or no-backtick forms) live under cli.model.*. The hand-padded /model usage
block becomes a (form, description-key) table padded at render time so the
command syntax stays fixed while descriptions translate. -q 'Error:' reuses
gateway.model.error_prefix.
* i18n(cli): route TUI panel/hint/placeholder copy through t() (cli.tui.*)
_APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS become key tables resolved at
render time; vault/sudo panel bodies are one catalog value per panel split on
newline; inline plurals use <key>_one/<key>_other. Adds the cli.* namespace
(shared/tui/voice/render/subagents/dock) to locales/en.yaml.
* i18n(cli): voice/wake-word CLI copy through t() (cli.voice.*)
RuntimeError texts raised in _voice_start_recording are human copy (callers
print {e}) and are keyed; the Termux requirement-check match stays English.
Wake state ids stay internal, only their labels localize.
* i18n(cli): live-work dock, subagent monitor and render copy through t()
cli.subagents.* / cli.dock.* / cli.render.*; count fragments pluralize via
_one/_other keys, verdict table holds keys resolved at paint time so width
clipping measures the translated text.
* i18n(gateway): unauthorized/pairing, voice, topics, shutdown, startup, notifications, kanban pings through t()
* i18n(cli): move tips + composer placeholders into the catalog (tips.tNNN / tips.placeholder.pNN)
get_random_tip()/get_random_composer_placeholder() pick a key from the English catalog
(the parity baseline, probed once per process) and resolve it through t() for the active
language, so language packs translate tips like any other string. Also lands the cli.*
en.yaml namespace consumed by the CLI info/help/error-copy wiring in the next commit.
* i18n(cli): wire chat-turn + session mixins through t(); kanban log trimmer matches t() output
* test(cli): assert TUI/dock/voice copy via t(key); prove labels resolve at render time
Pinned-English assertions in the approval-UI, live-work dock and voice tests now
go through the catalog. New test swaps the catalog after import and checks the
approval panel + hint row follow it (the reason _APPROVAL_CHOICE_LABELS and
_TUI_MODAL_HINTS became key tables).
* i18n(cli): route CLI info/help/error copy through t() (cli.* namespace)
cli_info_mixin: /help consumes CommandDef.describe() (added to commands.py: slash.<name>.description
with fallback to .description), section titles/skill/quick-command headers, /tools, /toolsets,
/usage labels, /context, /whoami, /insights, /gateway status, tool-progress labels, bang-shell
denials, MCP config-watch + /reload-mcp confirm/reload lines, /reload-skills, and the session-store
warning all read the catalog at call time (module-level label tables became functions so the
active language is honoured after startup). cli.py: worktree cleanup, tirith warning, show_config
(labels re-padded at print time), quick/plugin/skill slash-command errors, ambiguous-command hint,
stdin error, gateway start, profile warning. cli_chat_error_copy / cli_unknown_command /
cli_output / cli_init_mixin: chat error panel copy, did-you-mean lines, n-more / yes-no prompt
(localized affirmative initial alongside 'y'), unknown-toolsets warning.
* i18n(w1a): wire agent display/explainers/approval + slash registry/help through t()
- hermes_cli/commands.py: CommandDef.describe() resolves slash.<name>.description
at call time; category labels via slash.category.*; help/alias/usage suffixes
via slash.shared.*; gateway_help_lines and commands_platforms/slash_exec use them.
- agent/display.py: display.verb.* resolved at call time via get_tool_verb();
bridge/spinner/thinking-verb/cute-row/failure/preview/diff text via display.*.
- agent/turn_explainers.py: exit-reason / persistence-cause tables become call-time
lookups (explainer.exit.*, explainer.persistence.*, explainer.file_mutation.*).
- agent/background_review.py, session_activity.py, context_breakdown.py,
status_output.py: review summaries, iteration progress, context notices.
- tools/approval.py, approval_context.py: approval.summary.*, approval.noun.*,
approval.window.* pluralized keys.
- gateway/slash_commands*.py: remaining raw strings (busy, whoami, platform,
bundles, memory, skills, approvals, set_home, diff, update, debug, profile,
heartbeat, refine, review, subgoal, loop, retry, compress codex path, save,
sessions, model guard/errors, agents rows, topup, login). HISTORY_UNREADABLE
keeps its English constant; callers use history_unreadable() ->
gateway.shared.history_unreadable.
- locales/en.yaml: new approval/display/explainer/slash blocks + gateway leftovers.
* i18n(telegram): route adapter chat copy through t()
Approval card (header/reason/smart-deny as HTML-escaped properties), inline
button labels, callback toasts (cut at Telegram's 200-char cap), model/choice
pickers, clarify/update/slash-confirm prompts, gmail-triage labels and the
inbound-media failure notice now come from the catalog. _UNAUTHORIZED is a
lazy _unauthorized() so the import no longer binds a language. The command
menu carries a language+payload fingerprint (forum scopes re-register on
change) and BotCommand descriptions are cut at 256.
Adds gateway.exec_approval.* (WAVE2 contract), platform.telegram.*,
platform.discord.* and the slash.*.description keys the Discord table shares
with the CLI registry to locales/en.yaml.
* i18n(gateway/platforms): whatsapp_cloud, yuanbao, weixin, signal, api_server copy through t()
- whatsapp_cloud: clarify list/buttons, approve/deny + slash-confirm labels via platform.whatsapp.* (t()-then-truncate at 20/24/72 caps); _EA_HEADER becomes a property wrapping ea_header_text()
- yuanbao: SLOW_RESPONSE_MESSAGE -> slow_response_message() (platform.yuanbao.slow_response_notice; zh keeps the original text); cron-wrapper markers centralized as module constants for strip_cron_wrapper
- api_server: PROVIDER_AUTH_FAILED_LABEL/PROVIDER_RATE_LIMITED_LABEL stay English for run.py matchers; user_text() renders via t()
- signal/_format_wait, weixin voice caption, openai_routes transformed notice
- run_turn: second _UNEXPECTED_SILENCE_REPLY consumer -> accessor
* i18n(discord): route adapter chat copy through t()
Native slash-command table becomes _NATIVE_SLASH_COMMAND_SPECS holding catalog
keys; _native_slash_commands() resolves descriptions, parameter descriptions
and Choice names for the active language, each cut at Discord's 100-char cap,
and the app-command sync fingerprint now includes get_language() so a
display.language change re-syncs. Exec-approval card (gateway.exec_approval.*
contract), slash-confirm / clarify / update views, model+choice pickers,
thread creation, forum titles, voice acks, the response-truncation notice,
the unauthorized-slash security alert and the media upload-size notices all
read from platform.discord.*. Decorator-declared button labels are relabelled
in __init__ (80-char cap); embed titles cut at 256, select placeholders at
150, option label/description at 100. _UNAUTHORIZED is a lazy _unauthorized().
* i18n(cli): wire status-bar, stream, terminal mixins + terminal_input through t(); rename kwargs that shadow t(key)
* i18n: wire hermes_cli/cli_commands_mixin.py slash-command copy through t()
- 431 new leaves under cli.commands.<cmd>.* in locales/en.yaml; 12 rows reuse
existing gateway.* keys (rollback, diff, resume, branch, btw, model, reasoning)
via a _gt() helper so CLI and gateway replies stay identical.
- Module-level English tables (_BUSY_MODE_*, _REASONING_TOGGLES, _HATCH_PROGRESS,
_DIFF_LABELS, _LOCAL_ENGINE_LINES) become call-time catalog lookups keyed by id.
- Verb tables (Enabling/Disabling, Paused/Resumed/Triggered, planned/done,
Updating/Generating) are one full template per variant; plurals use
<key>_one/<key>_other via _tn(); hand-padded column labels (/snapshot list)
translate the value and re-pad at the call site.
- Multi-line usage blocks are single catalog values split with _lines().
- Model-facing system notes and DB-stored reasons stay English (EXCLUDED).
* tests: assert /handoff, /worktree, /login CLI copy via t(key) instead of pinned English
* test(i18n): pin Telegram/Discord adapter catalog wiring
Lazy unauthorized notice, exec-approval contract keys, HTML escaping before
Telegram <b> wrapping, 200-char toast / 256-char BotCommand caps, Discord
100-char app-command text and 80-char button caps, and language-bearing
command-menu fingerprints on both platforms.
* i18n: reconcile cli.shared on/off vs enabled/disabled after lane merge
* i18n: describe() in TUI-gateway slash listings; localize TUI exit resume hint
* i18n(tr): translate bundled catalog + tui pack
* i18n(ja): translate bundled catalog + tui pack
* i18n(ko): translate bundled catalog + tui pack
* i18n(zh): translate bundled catalog + tui pack
* i18n(fr): translate bundled catalog + tui pack
* i18n(af): translate bundled catalog + tui pack
* i18n(uk): translate bundled catalog + tui pack
* i18n(ar): translate bundled catalog + tui pack
* i18n(pt): translate bundled catalog + tui pack
* i18n(it): translate bundled catalog + tui pack
* i18n(es): translate bundled catalog + tui pack
* i18n(zh-hant): translate bundled catalog + tui pack
* i18n(ru): translate bundled catalog + tui pack
* i18n(hu): translate bundled catalog + tui pack
* i18n(hu): translate pre-existing English-valued leftovers (kanban wake, /context, /status, fast labels)
* i18n(de): translate bundled catalog + tui pack
* i18n(ga): translate bundled catalog + tui pack
* test(i18n): fixture matches _normalize_lang(lang, home) signature
* i18n(tui): scaffold userMessages/slashCmd en siblings
* i18n(tui): wire secure prompts + content tables
* feat(tui): i18n — wire billing, subscription, connection-setup and journey overlays
Adds en siblings billing.ts / subscription.ts / connection.ts (namespaces
billing, subscription, connection, journey) and routes every user-facing
literal in billingOverlay, subscriptionOverlay, connectionSetupOverlay and
journey through useT()/messages(). Module-level label tables became lazy
(scopeStillDeniedResult(), verbOf(T, action)); auto-reload rows dispatch on
stable ids instead of label text. Regenerates locales/_keys.tui.json.
* i18n(tui): wire slash ops/wake replies
* i18n(tui): wire pickers (modelPicker, activeSessionSwitcher, petPicker)
* i18n(tui): wire slash core/debug/setup replies
* i18n(tui): wire hubs (agents overlay/panel/controls, skills, plugins)
* i18n(tui): wire slash session/topup/subscription replies
* i18n(tui): wire chat bits (branding, thinking, messageLine, loaders, todo, queued, banner, entry)
* i18n(tui): register t3 siblings (pickers, hubs, secure, content, chatBits) and regenerate keys
* i18n(tui): wire userMessages copy through the userMessages namespace
* i18n(tui): lazy-copy test for userMessages, regenerate _keys.tui.json
* i18n(tui): wire session/gateway/lib text through the TUI catalog (lane t2)
Adds en siblings session.ts, gatewayMsg.ts, libText.ts (namespaces session,
gatewayMsg, libText) and routes user-facing literals in app/{useMainApp,
useSessionLifecycle,useInputHandlers,turnController,createServerRequestHandler,
setupHandoff,createGatewayEventHandler}.ts, gatewayClient displayed reasons,
lib/*, domain/*, hooks/* through t()/messages(). Status-bar state values that
code compares against, backend-matched strings, log lines, model-bound text,
and machine 'error:' prefixes stay literal. Regenerates locales/_keys.tui.json
(232 keys).
* i18n: serve bundled locales/<lang>.tui.yaml under overlay/packs; TUI pack parity test; regen _keys.tui.json (1250)
* i18n: translate pre-existing English stubs in bundled locales (424 leaves, 14 locales)
* tui: i18n-export-en script (English templates for pack translators)
* docs(i18n): bundled TUI packs are the bottom layer of the tui surface
* i18n(ru): translate TUI pack
* i18n(ar): translate TUI pack
* i18n(es): translate TUI pack
* i18n(pt): translate TUI pack
* i18n(ko): translate TUI pack
* i18n(de): translate TUI pack
* i18n(ja): translate TUI pack
* i18n(fr): translate TUI pack
* i18n(tr): translate TUI pack
* i18n(it): translate TUI pack
* i18n(zh): translate TUI pack
* i18n(zh-hant): translate TUI pack
* i18n(hu): translate TUI pack
* i18n(uk): translate TUI pack
1,169 missing keys translated; 81 pre-existing kept byte-identical. Parity OK missing=0 extra=0 placeholder_mismatch=0 empty=0.
Deliberately identical to en: chatBits.branding.mcpSummary ({0} MCP), chatBits.thinking.agentsHint ((/agents)), session.main.voiceStt (◉ STT), session.main.voiceTtsSuffix ( [tts]), slashCmd.core.help.tuiSection (TUI), slashCmd.core.history.hermesTag (Hermes #{0}), slashCmd.debug.heapdump.heapPath (heapdump: {0}), slashCmd.debug.mem.rss (rss), subscription.stepUp.title (Remote Spending — product feature name, as in core catalog), content.faces.* (glyph-only kaomoji).
* i18n(ga): translate TUI pack
* i18n(af): translate TUI pack
* plugin_guard: locale catalogs in language packs step down the agent-config family
A translated status line such as "Updating AGENTS.md" in locales/<lang>.yaml is UI text the loader
reads as a string leaf; it cannot edit a file. The bundled en.yaml itself tripped agent_config_mod
at critical, making any faithful language pack uninstallable. Injection shapes keep full severity.
* plugin_validate_locales: read key exports with utf-8-sig (Windows footgun lint)
* i18n(relay): route relay adapter prompt copy through t(); drop dead import-bound approval header
Adds platform.relay.* (5 keys) to en and all 16 bundled locales, reusing the sibling platform
translations for the confirm buttons and the Other option.
* ci: fix TUI import order, MDX table pipe, main's overflow-warning wording in all locales; fresh-install fixture carries the i18n kernel
- ui-tui/src/i18n/en.ts: perfectionist/sort-imports (slash before slashCmd)
- docs plugins/index.md: escape the | inside the provides_locales table cell (MDX parsed <id> as JSX)
- display.notice.uncompressed_context_overflow: adopt main's wording (names compression.enabled: false
and /compact) in en + 16 locales; the guardrail test pins that phrase
- tests/scripts/test_fresh_source_install.py: the installer tail now resolves CLI text through
agent.i18n, so the fixture tree carries the i18n kernel + en.yaml (not the agent runtime)
* docs(desktop-plugin-sdk): double-backtick the template-literal example (MDX evaluated ${n})
* test(e2e): display.language is validated against the live language set; exclude it from the arbitrary-string set property
* commands: keep the localized COMMANDS/COMMANDS_BY_CATEGORY module __getattr__ after the compat block removal
* build: never write locales/_keys.*.json from the desktop/TUI builds; regenerate the committed desktop key export
The desktop build regenerated locales/_keys.desktop.json in the checkout, so a
hermes update that rebuilt the app left the tree dirty (Desktop update E2E:
'M locales/_keys.desktop.json'). The key exports are committed artifacts pinned
to en.ts by apps/desktop/scripts/i18n-keys.test.mjs and ui-tui i18n:keys:check;
builds read them, never write them. Regenerated after main's new desktop strings.
* test: unbreak two main-red timing tests the PR merge-ref inherits
- test_local_runtime racing fake publishes the modern state record (legacy pid-only
records are rejected since 65ff3ad353; main has been red on this test since)
- test_run_progress_topics ManyProgressLinesAgent waits for the first bubble instead of
a fixed 0.35s, which a loaded CI runner does not always meet
* chore(i18n): regenerate desktop key catalog for main's new strings (model pricing, copy changelog)
* test(e2e): torture-chamber fd monitor confirms a deleted sidecar is still held before calling it a leak
SQLite's WAL last-close unlinks -shm before closing its descriptor (unixShmUnmap, then
unixShmPurge), so a healthy close shows a (deleted) -shm for microseconds; the 20ms poll
occasionally caught that window on the short-lived opener and failed the episode.
* chore(i18n): regenerate desktop key catalog for main's telemetry/consent strings
* chore(i18n): regenerate desktop key catalog after main sync
---------
Co-authored-by: Teknium <teknium@nousresearch.com>
859 lines
51 KiB
Python
859 lines
51 KiB
Python
"""DingTalk platform adapter (Stream Mode via dingtalk-stream >=0.20; replies via session webhook markdown or AI Cards).
|
|
Requires ``pip install "dingtalk-stream>=0.20" httpx``. config.yaml ``platforms.dingtalk``: ``enabled``, group gating
|
|
(``require_mention``, ``free_response_chats``, ``mention_patterns``, ``allowed_users``/``allowed_chats``) and
|
|
``extra.client_id`` / ``extra.client_secret`` (or DINGTALK_CLIENT_ID / DINGTALK_CLIENT_SECRET)."""
|
|
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import re
|
|
import time
|
|
import traceback
|
|
import uuid
|
|
from datetime import datetime, timezone
|
|
from typing import Any, Dict, List, Optional, Set
|
|
|
|
# Optional SDKs: catch broad Exception, not just ImportError — their transitive cryptography
|
|
# dependency can raise AttributeError on version skew; a broken optional SDK must degrade gracefully.
|
|
try:
|
|
import dingtalk_stream
|
|
from dingtalk_stream import ChatbotMessage
|
|
from dingtalk_stream.frames import CallbackMessage, AckMessage
|
|
|
|
DINGTALK_STREAM_AVAILABLE = True
|
|
except Exception: # noqa: BLE001
|
|
DINGTALK_STREAM_AVAILABLE = False
|
|
dingtalk_stream = ChatbotMessage = CallbackMessage = None # type: ignore[assignment]
|
|
AckMessage = type("AckMessage", (), {"STATUS_OK": 200, "STATUS_SYSTEM_EXCEPTION": 500}) # type: ignore[assignment]
|
|
|
|
try:
|
|
import httpx
|
|
|
|
HTTPX_AVAILABLE = True
|
|
except ImportError:
|
|
HTTPX_AVAILABLE = False
|
|
httpx = None # type: ignore[assignment]
|
|
|
|
try:
|
|
from alibabacloud_dingtalk.card_1_0 import client as dingtalk_card_client, models as dingtalk_card_models
|
|
from alibabacloud_dingtalk.robot_1_0 import client as dingtalk_robot_client, models as dingtalk_robot_models
|
|
from alibabacloud_tea_openapi import models as open_api_models
|
|
from alibabacloud_tea_util import models as tea_util_models
|
|
|
|
CARD_SDK_AVAILABLE = True
|
|
except Exception:
|
|
CARD_SDK_AVAILABLE = False
|
|
dingtalk_card_client = dingtalk_card_models = dingtalk_robot_client = dingtalk_robot_models = None
|
|
open_api_models = tea_util_models = None
|
|
|
|
from gateway.config import Platform, PlatformConfig
|
|
from gateway.platforms.helpers import MessageDeduplicator, compile_mention_patterns
|
|
from agent.i18n import t
|
|
from gateway.platforms.base import BasePlatformAdapter, SendResult
|
|
from gateway.platforms.event import MessageEvent
|
|
from gateway.platforms._shared import (
|
|
apply_yaml_bridge as _apply_yaml_bridge, decode_json_list_literal as _decode_json_list_literal,
|
|
extra_or_secret as _extra_or_secret, get_scoped_secret as _get_scoped_secret, send_error
|
|
)
|
|
from plugins.platforms.dingtalk.inbound import collect_download_codes, extract_media, extract_text
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
MAX_MESSAGE_LENGTH = 20000
|
|
RECONNECT_BACKOFF = [2, 5, 10, 30, 60]
|
|
RECONNECT_CIRCUIT_BREAKER_TRIPS = 5 # identical errors escaping start() before the breaker trips
|
|
RECONNECT_CIRCUIT_BREAKER_DELAY = 300 # seconds between attempts while tripped (matches the runner's cap)
|
|
_SDK_LOG_REPEAT_WINDOW = 300.0 # identical dingtalk_stream.client records are collapsed within this window
|
|
|
|
|
|
def _is_sdk_incompat(exc: BaseException | None) -> bool:
|
|
"""True for #24851: ``websockets.connect`` is not an async CM for this dingtalk-stream.
|
|
|
|
The SDK may surface it as the bare TypeError, or as an AttributeError (its ``except``
|
|
clause touches the unloaded ``websockets.exceptions``) chained on that TypeError.
|
|
"""
|
|
for _ in range(4):
|
|
if exc is None:
|
|
return False
|
|
if isinstance(exc, TypeError) and "asynchronous context manager" in str(exc):
|
|
return True
|
|
exc = exc.__cause__ or exc.__context__
|
|
return False
|
|
|
|
|
|
class _SdkLogGuard(logging.Filter):
|
|
"""Collapse repeated dingtalk_stream.client records; never raises on bad format args.
|
|
|
|
dingtalk-stream 0.24.3 logs ``logger.exception('unknown exception', e)`` every 3 s from its
|
|
retry loop — a malformed call that also triggers stdlib "--- Logging error ---" tracebacks.
|
|
"""
|
|
|
|
def __init__(self, on_exception=None, window: float = _SDK_LOG_REPEAT_WINDOW):
|
|
super().__init__()
|
|
self._on_exception, self._window = on_exception, window
|
|
self._seen: Dict[tuple, list] = {} # key -> [last_emitted_monotonic, suppressed_count]
|
|
|
|
def filter(self, record: logging.LogRecord) -> bool:
|
|
try:
|
|
try:
|
|
msg = record.getMessage()
|
|
except Exception:
|
|
args = record.args if isinstance(record.args, tuple) else (record.args,)
|
|
msg = " ".join(str(x) for x in (record.msg, *args))
|
|
record.msg, record.args = msg, ()
|
|
exc = record.exc_info[1] if record.exc_info else None
|
|
if exc is not None and self._on_exception is not None:
|
|
self._on_exception(exc)
|
|
key = (record.levelno, msg[:500], type(exc).__name__ if exc is not None else None)
|
|
now = time.monotonic()
|
|
entry = self._seen.get(key)
|
|
if entry is not None and now - entry[0] < self._window:
|
|
entry[1] += 1
|
|
return False
|
|
if entry is not None and entry[1]:
|
|
record.msg, record.args = f"{msg} (suppressed {entry[1]} identical repeats)", ()
|
|
if len(self._seen) >= 256:
|
|
self._seen.clear()
|
|
self._seen[key] = [now, 0]
|
|
except Exception:
|
|
pass # a logging filter must never break the caller
|
|
return True
|
|
_SESSION_WEBHOOKS_MAX = 500
|
|
_DINGTALK_WEBHOOK_RE = re.compile(r'^https://(?:api|oapi)\.dingtalk\.com/')
|
|
_TRUTHY = {"true", "1", "yes", "on"}
|
|
_EMOTION_ID = "2659900"
|
|
_EMOTION_BG = "im_bg_1"
|
|
# recall? -> (TextEmotion model, Request model, Headers model, robot SDK method), resolved on ``dingtalk_robot_models`` at call time.
|
|
_EMOTION_SDK = {recall: (f"Robot{v}EmotionRequestTextEmotion", f"Robot{v}EmotionRequest", f"Robot{v}EmotionHeaders", f"robot_{v.lower()}_emotion_with_options_async")
|
|
for recall, v in ((True, "Recall"), (False, "Reply"))}
|
|
_NUMBERED_RE = re.compile(r"^\d+\.\s")
|
|
_NO_LOCAL_UPLOAD = "DingTalk session webhook replies do not support local %s. Only markdown/text replies are supported without OpenAPI %s."
|
|
|
|
|
|
def _csv_set(raw: Any) -> Set[str]:
|
|
"""Split a list, JSON-list string or comma-separated string into a set of stripped, non-empty items."""
|
|
raw = _decode_json_list_literal(raw)
|
|
parts = raw if isinstance(raw, list) else str(raw).split(",")
|
|
return {str(part).strip() for part in parts if str(part).strip()}
|
|
|
|
|
|
def dingtalk_deps_present() -> bool:
|
|
"""PASSIVE registry ``check_fn`` — must never install; credentials are gated separately.
|
|
|
|
Registry ``check_fn`` — called from status displays and config loading, so it must never install
|
|
anything. The ACTIVE lazy-installer (``check_dingtalk_requirements``) is registered as
|
|
``ensure_deps_fn`` and runs from ``create_adapter()`` when this returns False (#79812).
|
|
"""
|
|
return DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE
|
|
|
|
|
|
def ensure_dingtalk_deps() -> bool:
|
|
"""ACTIVE deps-only installer (registry ``ensure_deps_fn``); rebinds module globals. Deliberately does NOT
|
|
check credentials: an ``extra``-configured platform would otherwise be vetoed before ever installing (deadlock).
|
|
|
|
Lazy-installs dingtalk-stream/httpx and rebinds module globals. Deliberately does NOT check credentials
|
|
— ``ensure_deps_fn``'s contract is deps-only ("Returns True once deps are importable"); credentials are
|
|
gated by ``is_connected``/``validate_config``. Otherwise a platform configured via
|
|
``PlatformConfig.extra`` (which ``_is_connected`` accepts) would pass enablement, reach
|
|
``create_adapter()``, and have the installer veto on env-var grounds before ever installing —
|
|
re-creating the #79812 deadlock for extra-configured setups.
|
|
"""
|
|
global DINGTALK_STREAM_AVAILABLE, dingtalk_stream, ChatbotMessage, CallbackMessage, AckMessage, HTTPX_AVAILABLE, httpx
|
|
if DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE:
|
|
return True
|
|
try:
|
|
from pm.extras import ensure_import
|
|
ensure_import("dingtalk")
|
|
import dingtalk_stream as _ds, httpx as _httpx # noqa: E401
|
|
from dingtalk_stream import ChatbotMessage as _CM
|
|
from dingtalk_stream.frames import CallbackMessage as _CBM, AckMessage as _AM
|
|
except Exception:
|
|
return False
|
|
dingtalk_stream, ChatbotMessage, CallbackMessage, AckMessage, httpx = _ds, _CM, _CBM, _AM, _httpx
|
|
DINGTALK_STREAM_AVAILABLE = HTTPX_AVAILABLE = True
|
|
return True
|
|
|
|
|
|
def _credentials(extra: Optional[dict]) -> tuple:
|
|
"""(client_id, client_secret) from PlatformConfig.extra first, then env / scoped secret."""
|
|
extra = extra or {}
|
|
# client_id goes through the same scoped reader as the secret: os.environ holds the DEFAULT
|
|
# profile's app id under multiplex, and pairing it with a secondary's secret authenticates as the wrong app.
|
|
return (extra.get("client_id") or _get_scoped_secret("DINGTALK_CLIENT_ID", ""),
|
|
extra.get("client_secret") or _get_scoped_secret("DINGTALK_CLIENT_SECRET", ""))
|
|
|
|
|
|
def check_dingtalk_requirements() -> bool:
|
|
"""Combined deps (lazy-installed) + credentials check for setup/status callers."""
|
|
return ensure_dingtalk_deps() and all(_credentials(None))
|
|
|
|
|
|
class DingTalkAdapter(BasePlatformAdapter):
|
|
"""Stream Mode adapter: the SDK keeps a long-lived WebSocket and messages arrive via a ChatbotHandler
|
|
callback; replies go through the message's session_webhook (httpx) or, with ``card_template_id``, AI Cards."""
|
|
|
|
MAX_MESSAGE_LENGTH = MAX_MESSAGE_LENGTH
|
|
|
|
@property
|
|
def SUPPORTS_MESSAGE_EDITING(self) -> bool: # noqa: N802
|
|
"""Edits only exist with AI Cards; the gateway gates streaming cursor/edit on this."""
|
|
return bool(self._card_template_id and self._card_sdk)
|
|
|
|
REQUIRES_EDIT_FINALIZE = SUPPORTS_MESSAGE_EDITING # AI Cards need an explicit ``finalize=True`` edit to close the streaming indicator
|
|
|
|
def __init__(self, config: PlatformConfig):
|
|
super().__init__(config, Platform.DINGTALK)
|
|
extra = config.extra or {}
|
|
self._client_id, self._client_secret = _credentials(extra)
|
|
# Group-chat gating; mention state is the SDK's structured ``is_in_at_list``, not text parsing.
|
|
self._mention_patterns: List[re.Pattern] = self._compile_mention_patterns()
|
|
self._allowed_users: Set[str] = {item.lower() for item in self._csv_setting("allowed_users", "DINGTALK_ALLOWED_USERS")}
|
|
self._stream_client = self._stream_task = self._http_client = self._card_sdk = self._robot_sdk = None
|
|
self._robot_code: str = extra.get("robot_code") or self._client_id
|
|
self._dedup = MessageDeduplicator(max_size=1000)
|
|
self._session_webhooks: Dict[str, tuple[str, int]] = {} # chat_id -> (webhook, expired_time_ms)
|
|
self._message_contexts: Dict[str, Any] = {} # chat_id -> last inbound ChatbotMessage (per-chat: no clobber)
|
|
self._card_template_id: Optional[str] = extra.get("card_template_id")
|
|
self._done_emoji_fired: Set[str] = set() # chats whose Done reaction fired this turn; reset per inbound
|
|
# Open streaming cards: chat_id -> {out_track_id: last_content}. ``edit_message(finalize=False)``
|
|
# re-opens a finalized card, so we track them and auto-close as siblings on the next ``send()``.
|
|
self._streaming_cards: Dict[str, Dict[str, str]] = {}
|
|
self._bg_tasks: Set[asyncio.Task] = set() # fire-and-forget emoji tasks, kept referenced (GC) + cancellable
|
|
|
|
async def connect(self, *, is_reconnect: bool = False) -> bool:
|
|
"""Connect to DingTalk via Stream Mode."""
|
|
for ok, problem in ((DINGTALK_STREAM_AVAILABLE, "dingtalk-stream not installed. Run: pip install 'dingtalk-stream>=0.20'"),
|
|
(HTTPX_AVAILABLE, "httpx not installed. Run: pip install httpx"),
|
|
(self._client_id and self._client_secret, "DINGTALK_CLIENT_ID and DINGTALK_CLIENT_SECRET required")):
|
|
if not ok:
|
|
logger.warning("[%s] " + problem, self.name)
|
|
return False
|
|
try:
|
|
from gateway.platforms._http_client_limits import platform_httpx_limits # tighter keepalive: idle CLOSE_WAIT drains promptly
|
|
self._http_client = httpx.AsyncClient(timeout=30.0, limits=platform_httpx_limits())
|
|
self._stream_client = dingtalk_stream.DingTalkStreamClient(dingtalk_stream.Credential(self._client_id, self._client_secret))
|
|
if CARD_SDK_AVAILABLE:
|
|
sdk_config = open_api_models.Config()
|
|
sdk_config.protocol, sdk_config.region_id = "https", "central"
|
|
if self._card_template_id:
|
|
self._card_sdk = dingtalk_card_client.Client(sdk_config)
|
|
self._robot_sdk = dingtalk_robot_client.Client(sdk_config) # needed for media download even without cards
|
|
if self._card_template_id:
|
|
logger.info("[%s] Card SDK initialized with template: %s", self.name, self._card_template_id)
|
|
else:
|
|
logger.info("[%s] Robot SDK initialized (media download)", self.name)
|
|
self._stream_client.register_callback_handler(dingtalk_stream.ChatbotMessage.TOPIC, _IncomingHandler(self, asyncio.get_running_loop()))
|
|
self._stream_task = asyncio.create_task(self._run_stream())
|
|
self._mark_connected()
|
|
logger.info("[%s] Connected via Stream Mode", self.name)
|
|
self._wire_plugin_handlers(self._stream_client) # plugin-registered native handlers
|
|
return True
|
|
except Exception as e:
|
|
logger.error("[%s] Failed to connect: %s", self.name, e)
|
|
return False
|
|
|
|
async def _run_stream(self) -> None:
|
|
"""Run the SDK stream client with auto-reconnection.
|
|
|
|
dingtalk-stream's ``start()`` runs its own catch-all retry loop, so most
|
|
errors never reach us: ``_SdkLogGuard`` collapses that loop's repeated
|
|
log records, and a dingtalk-stream/websockets incompatibility (#24851)
|
|
is handed to the gateway's reconnect watcher via ``_set_fatal_error``
|
|
instead of retrying forever. For errors that do escape ``start()``,
|
|
exponential backoff (RECONNECT_BACKOFF) applies; after
|
|
RECONNECT_CIRCUIT_BREAKER_TRIPS identical errors in a row the breaker
|
|
trips and stays tripped (silent, RECONNECT_CIRCUIT_BREAKER_DELAY between
|
|
attempts) until the error type changes.
|
|
"""
|
|
self._sdk_loop_task = asyncio.current_task()
|
|
sdk_logger = getattr(self._stream_client, "logger", None)
|
|
if not isinstance(sdk_logger, logging.Logger):
|
|
sdk_logger = logging.getLogger("dingtalk_stream.client")
|
|
guard = _SdkLogGuard(self._on_sdk_error)
|
|
sdk_logger.addFilter(guard)
|
|
try:
|
|
await self._run_stream_loop()
|
|
finally:
|
|
sdk_logger.removeFilter(guard)
|
|
|
|
async def _run_stream_loop(self) -> None:
|
|
backoff_idx = 0
|
|
consecutive_same_error = 0
|
|
last_error_type: type | None = None
|
|
while self._running:
|
|
try:
|
|
logger.debug("[%s] Starting stream client...", self.name)
|
|
await self._stream_client.start()
|
|
except asyncio.CancelledError:
|
|
if getattr(self, "_fatal_error_code", None) == "dingtalk_stream_error":
|
|
await self._notify_fatal_error()
|
|
return
|
|
except Exception as e:
|
|
if not self._running:
|
|
return
|
|
if _is_sdk_incompat(e):
|
|
self._on_sdk_error(e, cancel=False)
|
|
await self._notify_fatal_error()
|
|
return
|
|
error_type = type(e)
|
|
if error_type is last_error_type:
|
|
consecutive_same_error += 1
|
|
else:
|
|
consecutive_same_error = 1
|
|
last_error_type = error_type
|
|
if consecutive_same_error <= RECONNECT_CIRCUIT_BREAKER_TRIPS:
|
|
logger.warning("[%s] Stream client error: %s", self.name, e)
|
|
elif consecutive_same_error == RECONNECT_CIRCUIT_BREAKER_TRIPS + 1:
|
|
logger.error(
|
|
"[%s] Stream client error repeated %d times: %s — circuit breaker tripped; "
|
|
"retrying every %ds silently until the error changes.",
|
|
self.name, consecutive_same_error, e, RECONNECT_CIRCUIT_BREAKER_DELAY,
|
|
)
|
|
if not self._running:
|
|
return
|
|
if consecutive_same_error > RECONNECT_CIRCUIT_BREAKER_TRIPS:
|
|
await asyncio.sleep(RECONNECT_CIRCUIT_BREAKER_DELAY)
|
|
else:
|
|
delay = RECONNECT_BACKOFF[min(backoff_idx, len(RECONNECT_BACKOFF) - 1)]
|
|
logger.info("[%s] Reconnecting in %ds...", self.name, delay)
|
|
await asyncio.sleep(delay)
|
|
backoff_idx += 1
|
|
|
|
def _on_sdk_error(self, exc: BaseException, *, cancel: bool = True) -> None:
|
|
"""Called (sync, possibly from the SDK logger) with an SDK exception; hands off on incompat."""
|
|
if not _is_sdk_incompat(exc) or getattr(self, "_fatal_error_code", None) == "dingtalk_stream_error":
|
|
return
|
|
msg = (f"dingtalk-stream cannot open its websocket with the installed websockets package ({exc}). "
|
|
"Hermes pins dingtalk-stream==0.24.3 with websockets==15.0.1; reinstall the dingtalk extra "
|
|
"so those versions are used (e.g. `pip install 'hermes-agent[dingtalk]'`).")
|
|
logger.error("[%s] %s", self.name, msg)
|
|
# Not retryable: only a reinstall + restart fixes it, and connect() returns True before the
|
|
# socket exists, so a gateway reconnect would re-fail every watcher tick forever.
|
|
self._set_fatal_error("dingtalk_stream_error", msg, retryable=False)
|
|
task = getattr(self, "_sdk_loop_task", None)
|
|
if cancel and task is not None and not task.done():
|
|
task.cancel() # SDK's own retry loop never exits; lands on its next await
|
|
|
|
async def _quiet(self, coro, debug_fmt: str = "", *args) -> None:
|
|
"""Await *coro*, swallowing any exception (logged at debug as ``debug_fmt % (name, *args, exc)`` when given)."""
|
|
try:
|
|
await coro
|
|
except Exception as e:
|
|
if debug_fmt:
|
|
logger.debug(debug_fmt, self.name, *args, e)
|
|
|
|
async def disconnect(self) -> None:
|
|
"""Disconnect from DingTalk."""
|
|
self._running = False
|
|
self._mark_disconnected()
|
|
# Close the websocket first so the stream task sees the disconnect instead of awaiting frames that never arrive.
|
|
websocket = getattr(self._stream_client, "websocket", None) if self._stream_client else None
|
|
if websocket is not None:
|
|
await self._quiet(websocket.close(), "[%s] websocket close during disconnect failed: %s")
|
|
if self._stream_task:
|
|
if hasattr(self._stream_client, "close"):
|
|
await self._quiet(asyncio.to_thread(self._stream_client.close)) # sync close() may block on I/O
|
|
self._stream_task.cancel()
|
|
try:
|
|
await asyncio.wait_for(self._stream_task, timeout=5.0)
|
|
except (asyncio.CancelledError, asyncio.TimeoutError):
|
|
logger.debug("[%s] stream task did not exit cleanly during disconnect", self.name)
|
|
self._stream_task = None
|
|
for task in list(self._bg_tasks):
|
|
task.cancel()
|
|
if self._bg_tasks:
|
|
await asyncio.gather(*self._bg_tasks, return_exceptions=True)
|
|
# Finalize open streaming cards BEFORE the HTTP client closes so they don't stay stuck
|
|
# in streaming state after a gateway restart. Outer try guards the token fetch.
|
|
for _chat_id in list(self._streaming_cards):
|
|
await self._quiet(self._close_streaming_siblings(_chat_id), "[%s] Failed to finalize streaming card on disconnect for %s: %s", _chat_id)
|
|
if self._http_client:
|
|
await self._http_client.aclose()
|
|
self._http_client = self._stream_client = None
|
|
for store in (self._session_webhooks, self._message_contexts, self._streaming_cards, self._done_emoji_fired, self._dedup, self._bg_tasks):
|
|
store.clear()
|
|
logger.info("[%s] Disconnected", self.name)
|
|
|
|
def _csv_setting(self, key: str, env_name: str) -> Set[str]:
|
|
"""List/CSV setting from config.extra[key], falling back to the env var."""
|
|
return _csv_set(_extra_or_secret(self.config.extra, key, env_name, blank_is_unset=False))
|
|
|
|
def _dingtalk_require_mention(self) -> bool:
|
|
"""Whether group chats require an explicit bot trigger."""
|
|
configured = _extra_or_secret(self.config.extra, "require_mention", "DINGTALK_REQUIRE_MENTION", "false", blank_is_unset=False)
|
|
return configured.lower() in _TRUTHY if isinstance(configured, str) else bool(configured)
|
|
|
|
def _dingtalk_allowed_chats(self) -> Set[str]:
|
|
"""Group chat whitelist; non-empty = hard gate even when @mentioned. DMs never filtered."""
|
|
return self._csv_setting("allowed_chats", "DINGTALK_ALLOWED_CHATS")
|
|
|
|
def _compile_mention_patterns(self) -> List[re.Pattern]:
|
|
"""Compile optional regex wake-word patterns (config list, or env as JSON / lines / CSV)."""
|
|
patterns = (self.config.extra or {}).get("mention_patterns")
|
|
if patterns is None and (raw := str(_get_scoped_secret("DINGTALK_MENTION_PATTERNS", "") or "").strip()):
|
|
try:
|
|
patterns = json.loads(raw)
|
|
except Exception:
|
|
patterns = [part.strip() for part in raw.splitlines() if part.strip()]
|
|
if not patterns:
|
|
patterns = [part.strip() for part in raw.split(",") if part.strip()]
|
|
if patterns is None: # return before touching ``self.name`` on the no-patterns path (historical parity)
|
|
return []
|
|
return compile_mention_patterns(patterns, log_prefix=self.name, platform_label="dingtalk", display_label="DingTalk", logger_=logger)
|
|
|
|
def _is_user_allowed(self, sender_id: str, sender_staff_id: str) -> bool:
|
|
if not self._allowed_users or "*" in self._allowed_users:
|
|
return True
|
|
return bool(({(sender_id or "").lower(), (sender_staff_id or "").lower()} - {""}) & self._allowed_users)
|
|
|
|
def _message_matches_mention_patterns(self, text: str) -> bool:
|
|
return bool(text and self._mention_patterns) and any(p.search(text) for p in self._mention_patterns)
|
|
|
|
def _should_process_message(self, message: "ChatbotMessage", text: str, is_group: bool, chat_id: str) -> bool:
|
|
"""Group trigger rules (DMs always pass; ``allowed_users`` is enforced earlier): ``allowed_chats`` is a hard
|
|
gate, then any of free_response_chats / require_mention off / @mentioned (SDK ``is_in_at_list``) / wake-word."""
|
|
if not is_group:
|
|
return True
|
|
allowed = self._dingtalk_allowed_chats()
|
|
if allowed and chat_id and chat_id not in allowed:
|
|
return False
|
|
return (
|
|
bool(chat_id and chat_id in self._csv_setting("free_response_chats", "DINGTALK_FREE_RESPONSE_CHATS"))
|
|
or not self._dingtalk_require_mention()
|
|
or bool(getattr(message, "is_in_at_list", False))
|
|
or self._message_matches_mention_patterns(text)
|
|
)
|
|
|
|
def _spawn_bg(self, coro) -> None:
|
|
"""Start a fire-and-forget coroutine and track it for cleanup."""
|
|
self._bg_tasks.add(task := asyncio.create_task(coro))
|
|
task.add_done_callback(self._bg_tasks.discard)
|
|
|
|
async def _close_streaming_siblings(self, chat_id: str) -> None:
|
|
"""Finalize open streaming cards for this chat at the start of every ``send()`` — the gateway has no "turn end" signal, so this is what closes lingering tool-progress cards."""
|
|
cards = self._streaming_cards.pop(chat_id, None)
|
|
token = await self._get_access_token() if cards else None
|
|
for out_track_id, last_content in list(cards.items()) if token else ():
|
|
try:
|
|
await self._stream_card_content(out_track_id, token, last_content, finalize=True)
|
|
logger.debug("[%s] AI Card sibling closed: %s", self.name, out_track_id)
|
|
except Exception as e:
|
|
logger.debug("[%s] Sibling close failed for %s: %s", self.name, out_track_id, e)
|
|
|
|
def _fire_done_reaction(self, chat_id: str) -> None:
|
|
"""Swap 🤔Thinking → 🥳Done on the original user message; idempotent per chat_id."""
|
|
if chat_id in self._done_emoji_fired:
|
|
return
|
|
self._done_emoji_fired.add(chat_id)
|
|
msg = self._message_contexts.get(chat_id)
|
|
msg_id, conversation_id = (getattr(msg, "message_id", None) or "", getattr(msg, "conversation_id", None) or "") if msg else ("", "")
|
|
if not (msg_id and conversation_id):
|
|
return
|
|
async def _swap() -> None:
|
|
await self._send_emotion(msg_id, conversation_id, t("platform.dingtalk.emotion.thinking"), recall=True)
|
|
await self._send_emotion(msg_id, conversation_id, t("platform.dingtalk.emotion.done"), recall=False)
|
|
self._spawn_bg(_swap())
|
|
|
|
async def _on_message(self, message: "ChatbotMessage") -> None:
|
|
"""Process an incoming DingTalk chatbot message."""
|
|
msg_id = getattr(message, "message_id", None) or uuid.uuid4().hex
|
|
if self._dedup.is_duplicate(msg_id):
|
|
return logger.debug("[%s] Duplicate message %s, skipping", self.name, msg_id)
|
|
conversation_id, sender_id, sender_nick, sender_staff_id = (getattr(message, k, "") or "" for k in ("conversation_id", "sender_id", "sender_nick", "sender_staff_id"))
|
|
is_group = str(getattr(message, "conversation_type", "1")) == "2"
|
|
sender_nick = sender_nick or sender_id
|
|
chat_id = conversation_id or sender_id
|
|
if not self._is_user_allowed(sender_id, sender_staff_id):
|
|
return logger.debug("[%s] Dropping message from non-allowlisted user staff_id=%s sender_id=%s", self.name, sender_staff_id, sender_id)
|
|
if not self._should_process_message(message, self._extract_text(message) or "", is_group, chat_id): # wake-word gate needs text early
|
|
return logger.debug("[%s] Dropping group message that failed mention gate message_id=%s chat_id=%s", self.name, msg_id, chat_id)
|
|
# Per-chat context; reset the Done marker so this message gets its own Thinking→Done cycle.
|
|
if chat_id:
|
|
self._message_contexts[chat_id] = message
|
|
self._done_emoji_fired.discard(chat_id)
|
|
session_webhook = getattr(message, "session_webhook", None) or ""
|
|
if session_webhook and chat_id and _DINGTALK_WEBHOOK_RE.match(session_webhook):
|
|
if len(self._session_webhooks) >= _SESSION_WEBHOOKS_MAX:
|
|
self._session_webhooks.pop(next(iter(self._session_webhooks))) # evict oldest (dict is non-empty here)
|
|
self._session_webhooks[chat_id] = (session_webhook, getattr(message, "session_webhook_expired_time", 0) or 0)
|
|
await self._resolve_media_codes(message) # download codes -> URLs so vision tools can use them
|
|
text = self._extract_text(message)
|
|
msg_type, media_urls, media_types = self._extract_media(message)
|
|
if not text and not media_urls:
|
|
return logger.debug("[%s] Empty message, skipping", self.name)
|
|
source = self.build_source(chat_id=chat_id, chat_name=getattr(message, "conversation_title", None), chat_type="group" if is_group else "dm",
|
|
user_id=sender_id, user_name=sender_nick, user_id_alt=sender_staff_id if sender_staff_id else None,
|
|
message_id=msg_id)
|
|
create_at = getattr(message, "create_at", None)
|
|
try:
|
|
timestamp = datetime.fromtimestamp(int(create_at) / 1000, tz=timezone.utc) if create_at else datetime.now(tz=timezone.utc)
|
|
except (ValueError, OSError, TypeError):
|
|
timestamp = datetime.now(tz=timezone.utc)
|
|
logger.debug("[%s] Message from %s in %s: %s", self.name, sender_nick, chat_id[:20] if chat_id else "?", text[:80] if text else "(media)")
|
|
await self.handle_message(MessageEvent(text=text, message_type=msg_type, source=source, message_id=msg_id, raw_message=message,
|
|
media_urls=media_urls, media_types=media_types, timestamp=timestamp))
|
|
|
|
_extract_text = staticmethod(extract_text)
|
|
|
|
def _extract_media(self, message: "ChatbotMessage"):
|
|
return extract_media(message)
|
|
|
|
async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult:
|
|
"""Send a reply via AI Card (when configured) or DingTalk session webhook markdown."""
|
|
metadata = metadata or {}
|
|
logger.debug("[%s] send() chat_id=%s card_enabled=%s", self.name, chat_id, bool(self._card_template_id and self._card_sdk))
|
|
session_webhook = metadata.get("session_webhook") or (self._get_valid_webhook(chat_id) or ("",))[0]
|
|
if not session_webhook:
|
|
logger.warning("[%s] No valid session_webhook for chat_id=%s", self.name, chat_id)
|
|
return SendResult(success=False, error="No valid session_webhook available. Reply must follow an incoming message.")
|
|
if not self._http_client:
|
|
return SendResult(success=False, error="HTTP client not initialized")
|
|
current_message = self._message_contexts.get(chat_id)
|
|
# ``reply_to`` is only set by base.py:_send_with_retry for the FINAL reply to an inbound message;
|
|
# tool-progress, commentary and stream first-sends leave it None. It decides (1) finalize-on-create
|
|
# (intermediate cards stay open so edits don't flicker) and (2) whether to fire the Done reaction.
|
|
is_final_reply = reply_to is not None
|
|
if self._card_template_id and current_message and self._card_sdk:
|
|
await self._close_streaming_siblings(chat_id) # close lingering tool-progress cards before creating a new one
|
|
result = await self._create_and_stream_card(chat_id, current_message, content, finalize=is_final_reply)
|
|
if result and result.success:
|
|
if is_final_reply:
|
|
self._fire_done_reaction(chat_id)
|
|
else: # keep open + track so the next send() auto-closes it, or edit_message(finalize=True) does
|
|
self._streaming_cards.setdefault(chat_id, {})[result.message_id] = content
|
|
return result
|
|
logger.warning("[%s] AI Card send failed, falling back to webhook", self.name)
|
|
logger.debug("[%s] Sending via webhook", self.name)
|
|
payload = {"msgtype": "markdown", "markdown": {"title": "Hermes", "text": self._normalize_markdown(content[: self.MAX_MESSAGE_LENGTH])}}
|
|
try:
|
|
resp = await self._http_client.post(session_webhook, json=payload, timeout=15.0)
|
|
if resp.status_code < 300:
|
|
if is_final_reply:
|
|
self._fire_done_reaction(chat_id)
|
|
return SendResult(success=True, message_id=uuid.uuid4().hex[:12])
|
|
logger.warning("[%s] Send failed HTTP %d: %s", self.name, resp.status_code, resp.text[:200])
|
|
return SendResult(success=False, error=f"HTTP {resp.status_code}: {resp.text[:200]}")
|
|
except httpx.TimeoutException:
|
|
return SendResult(success=False, error="Timeout sending message to DingTalk")
|
|
except Exception as e:
|
|
logger.error("[%s] Send error: %s", self.name, e)
|
|
return SendResult(success=False, error=str(e))
|
|
|
|
async def send_typing(self, chat_id: str, metadata=None) -> None:
|
|
"""DingTalk does not support typing indicators."""
|
|
|
|
async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None, metadata=None) -> SendResult:
|
|
"""Render a remote image inline via markdown (session webhook has no native attachments)."""
|
|
image_block = f""
|
|
return await self.send(chat_id=chat_id, content=f"{caption}\n\n{image_block}" if caption else image_block, reply_to=reply_to, metadata=metadata)
|
|
|
|
async def send_image_file(self, chat_id: str, image_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, metadata=None, **kwargs) -> SendResult:
|
|
"""Webhook replies cannot upload local images."""
|
|
return SendResult(success=False, error=_NO_LOCAL_UPLOAD % ("image uploads", "media upload"))
|
|
|
|
async def send_document(self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None, reply_to=None, metadata=None, **kwargs) -> SendResult:
|
|
"""Webhook replies cannot upload local files."""
|
|
return SendResult(success=False, error=_NO_LOCAL_UPLOAD % ("file attachments", "message send"))
|
|
|
|
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
|
|
"""Return basic info about a DingTalk conversation."""
|
|
return {"name": chat_id, "type": "group" if "group" in chat_id.lower() else "dm"}
|
|
|
|
def _get_valid_webhook(self, chat_id: str) -> Optional[tuple[str, int]]:
|
|
"""Get a non-expired session webhook for chat_id (5-minute safety margin)."""
|
|
info = self._session_webhooks.get(chat_id)
|
|
expired_time_ms = info[1] if info else 0
|
|
if expired_time_ms and expired_time_ms > 0 and int(datetime.now(tz=timezone.utc).timestamp() * 1000) + 5 * 60 * 1000 >= expired_time_ms:
|
|
self._session_webhooks.pop(chat_id, None)
|
|
return None
|
|
return info or None
|
|
|
|
async def _create_and_stream_card(self, chat_id: str, message: Any, content: str, *, finalize: bool = True) -> Optional[SendResult]:
|
|
"""Create, deliver and stream an AI Card; ``finalize=False`` leaves it open for ``edit_message`` by out_track_id."""
|
|
try:
|
|
token = await self._get_access_token()
|
|
if not token:
|
|
return None
|
|
out_track_id, models = f"hermes_{uuid.uuid4().hex[:12]}", dingtalk_card_models
|
|
is_group = str(getattr(message, "conversation_type", "1")) == "2"
|
|
sender_staff_id = getattr(message, "sender_staff_id", "") or ""
|
|
create_request = models.CreateCardRequest(
|
|
card_template_id=self._card_template_id, out_track_id=out_track_id, callback_type="STREAM",
|
|
card_data=models.CreateCardRequestCardData(card_param_map={"content": ""}),
|
|
im_group_open_space_model=models.CreateCardRequestImGroupOpenSpaceModel(support_forward=True),
|
|
im_robot_open_space_model=models.CreateCardRequestImRobotOpenSpaceModel(support_forward=True))
|
|
await self._sdk_call(self._card_sdk.create_card_with_options_async, create_request, models.CreateCardHeaders, token)
|
|
if is_group:
|
|
open_space_id = f"dtv1.card//IM_GROUP.{getattr(message, 'conversation_id', '') or ''}"
|
|
deliver_model = {"im_group_open_deliver_model": models.DeliverCardRequestImGroupOpenDeliverModel(robot_code=self._robot_code)}
|
|
elif sender_staff_id:
|
|
open_space_id = f"dtv1.card//IM_ROBOT.{sender_staff_id}"
|
|
deliver_model = {"im_robot_open_deliver_model": models.DeliverCardRequestImRobotOpenDeliverModel(space_type="IM_ROBOT")}
|
|
else:
|
|
return logger.warning("[%s] AI Card skipped: missing sender_staff_id for DM", self.name)
|
|
deliver_request = models.DeliverCardRequest(out_track_id=out_track_id, user_id_type=1, open_space_id=open_space_id, **deliver_model)
|
|
await self._sdk_call(self._card_sdk.deliver_card_with_options_async, deliver_request, models.DeliverCardHeaders, token)
|
|
await self._stream_card_content(out_track_id, token, content, finalize=finalize)
|
|
logger.info("[%s] AI Card %s: %s", self.name, "created+finalized" if finalize else "created (streaming)", out_track_id)
|
|
return SendResult(success=True, message_id=out_track_id)
|
|
except Exception as e:
|
|
logger.warning("[%s] AI Card create failed: %s\n%s", self.name, e, traceback.format_exc())
|
|
return None
|
|
|
|
async def edit_message(self, chat_id: str, message_id: str, content: str, *, finalize: bool = False) -> SendResult:
|
|
"""Stream updated content to an AI Card; ``message_id`` is the creating ``send()``'s out_track_id (callers track their own ids so parallel flows on one chat don't interfere)."""
|
|
if not self.SUPPORTS_MESSAGE_EDITING:
|
|
return SendResult(success=False, error="AI Cards are not configured for message editing")
|
|
token = await self._get_access_token() if message_id else None
|
|
if not token:
|
|
return SendResult(success=False, error="message_id required" if not message_id else "No access token")
|
|
try:
|
|
await self._stream_card_content(message_id, token, content, finalize=finalize)
|
|
if finalize: # canonical "response ended" signal from the stream consumer's final edit
|
|
self._streaming_cards.get(chat_id, {}).pop(message_id, None)
|
|
if not self._streaming_cards.get(chat_id):
|
|
self._streaming_cards.pop(chat_id, None)
|
|
logger.debug("[%s] AI Card finalized (edit): %s", self.name, message_id)
|
|
self._fire_done_reaction(chat_id)
|
|
else: # non-final edit reopens the card into streaming state — track for sibling close
|
|
self._streaming_cards.setdefault(chat_id, {})[message_id] = content
|
|
return SendResult(success=True, message_id=message_id)
|
|
except Exception as e:
|
|
logger.warning("[%s] Card edit failed: %s", self.name, e)
|
|
return SendResult(success=False, error=str(e))
|
|
|
|
@staticmethod
|
|
async def _sdk_call(method, request, headers_cls, token: str):
|
|
"""``await method(request, headers_cls(token), RuntimeOptions())`` — the alibabacloud SDK call shape."""
|
|
return await method(request, headers_cls(x_acs_dingtalk_access_token=token), tea_util_models.RuntimeOptions())
|
|
|
|
async def _stream_card_content(self, out_track_id: str, token: str, content: str, finalize: bool = False) -> None:
|
|
"""Stream content to an existing AI Card."""
|
|
stream_request = dingtalk_card_models.StreamingUpdateRequest(
|
|
out_track_id=out_track_id, guid=str(uuid.uuid4()), key="content", content=content[: self.MAX_MESSAGE_LENGTH],
|
|
is_full=True, is_finalize=finalize, is_error=False,
|
|
)
|
|
await self._sdk_call(self._card_sdk.streaming_update_with_options_async, stream_request, dingtalk_card_models.StreamingUpdateHeaders, token)
|
|
|
|
async def _get_access_token(self) -> Optional[str]:
|
|
"""Get access token via the SDK's cached (sync, requests-based) getter."""
|
|
if not self._stream_client:
|
|
return None
|
|
try:
|
|
return await asyncio.to_thread(self._stream_client.get_access_token)
|
|
except Exception as e:
|
|
logger.error("[%s] Failed to get access token: %s", self.name, e)
|
|
return None
|
|
|
|
async def _send_emotion(self, open_msg_id: str, open_conversation_id: str, emoji_name: str, *, recall: bool = False) -> None:
|
|
"""Add (or recall) an emoji reaction on a message."""
|
|
if not self._robot_sdk or not open_msg_id or not open_conversation_id:
|
|
return
|
|
action = "recall" if recall else "reply"
|
|
try:
|
|
token = await self._get_access_token()
|
|
if not token:
|
|
return
|
|
text_emotion_cls, request_cls, headers_cls, sdk_method = _EMOTION_SDK[recall]
|
|
text_emotion = getattr(dingtalk_robot_models, text_emotion_cls)(emotion_id=_EMOTION_ID, emotion_name=emoji_name, text=emoji_name, background_id=_EMOTION_BG)
|
|
request = getattr(dingtalk_robot_models, request_cls)(robot_code=self._robot_code, open_msg_id=open_msg_id, open_conversation_id=open_conversation_id,
|
|
emotion_type=2, emotion_name=emoji_name, text_emotion=text_emotion)
|
|
await self._sdk_call(getattr(self._robot_sdk, sdk_method), request, getattr(dingtalk_robot_models, headers_cls), token)
|
|
logger.info("[%s] _send_emotion: %s %s on msg=%s", self.name, action, emoji_name, open_msg_id[:24])
|
|
except Exception:
|
|
logger.debug("[%s] _send_emotion %s failed", self.name, action, exc_info=True)
|
|
|
|
async def _resolve_media_codes(self, message: "ChatbotMessage") -> None:
|
|
"""Resolve download codes in the message to real URLs (in place, in parallel)."""
|
|
token = await self._get_access_token()
|
|
if not token:
|
|
return
|
|
robot_code = getattr(message, "robot_code", None) or self._client_id
|
|
pairs = [(getattr(obj, key, None) if hasattr(obj, key) else obj.get(key), obj, key) for obj, key in collect_download_codes(message)]
|
|
tasks = [self._fetch_download_url(code, robot_code, token, obj, key) for code, obj, key in pairs if code]
|
|
if tasks:
|
|
await asyncio.gather(*tasks, return_exceptions=True)
|
|
|
|
async def _fetch_download_url(self, code: str, robot_code: str, token: str, obj, key: str) -> None:
|
|
"""Fetch the download URL for one code via the robot SDK and write it back to ``obj[key]``."""
|
|
if not self._robot_sdk:
|
|
return logger.warning("[%s] Robot SDK not initialized, cannot resolve media code", self.name)
|
|
try:
|
|
response = await self._sdk_call(self._robot_sdk.robot_message_file_download_with_options_async,
|
|
dingtalk_robot_models.RobotMessageFileDownloadRequest(download_code=code, robot_code=robot_code),
|
|
dingtalk_robot_models.RobotMessageFileDownloadHeaders, token)
|
|
body = response.body if response else None
|
|
url = getattr(body, "download_url", None) if body else None
|
|
if not body:
|
|
logger.warning("[%s] Failed to download media: empty response for code %s", self.name, code)
|
|
elif url and hasattr(obj, key):
|
|
setattr(obj, key, url)
|
|
elif url and isinstance(obj, dict):
|
|
obj[key] = url
|
|
except Exception as e:
|
|
logger.error("[%s] Error resolving media code %s: %s", self.name, code, e)
|
|
|
|
@staticmethod
|
|
def _normalize_markdown(text: str) -> str:
|
|
"""Work around DingTalk renderer quirks: blank line before numbered lists, dedent ``` fences."""
|
|
lines = text.split("\n")
|
|
out = []
|
|
for i, line in enumerate(lines):
|
|
prev = lines[i - 1].strip() if i > 0 else ""
|
|
if prev and _NUMBERED_RE.match(line.strip()) and not _NUMBERED_RE.match(prev):
|
|
out.append("")
|
|
out.append(line.lstrip() if line.strip().startswith("```") else line)
|
|
return "\n".join(out)
|
|
|
|
|
|
class _IncomingHandler(dingtalk_stream.ChatbotHandler if DINGTALK_STREAM_AVAILABLE else object):
|
|
"""ChatbotHandler forwarding to the adapter (SDK >= 0.20: async ``process()`` gets a CallbackMessage ``.data`` dict)."""
|
|
|
|
def __init__(self, adapter: DingTalkAdapter, loop: Optional[asyncio.AbstractEventLoop] = None):
|
|
if DINGTALK_STREAM_AVAILABLE:
|
|
super().__init__()
|
|
self._adapter, self._loop = adapter, loop
|
|
|
|
def pre_start(self) -> None:
|
|
"""No-op hook the SDK calls on every handler before opening the WebSocket (missing → AttributeError)."""
|
|
return
|
|
|
|
async def process(self, message: "CallbackMessage"):
|
|
"""Convert to ChatbotMessage, dispatch as a background task, ACK immediately (blocking would stall SDK heartbeats)."""
|
|
try:
|
|
data = json.loads(message.data) if isinstance(message.data, str) else message.data
|
|
chatbot_msg = ChatbotMessage.from_dict(data)
|
|
data = data if isinstance(data, dict) else {} # backfill fields from_dict() may not map (names vary across SDK versions)
|
|
webhook = data.get("sessionWebhook") or data.get("session_webhook") or ""
|
|
if webhook and not getattr(chatbot_msg, "session_webhook", None):
|
|
chatbot_msg.session_webhook = webhook
|
|
if not getattr(chatbot_msg, "is_in_at_list", False) and data.get("isInAtList"):
|
|
chatbot_msg.is_in_at_list = True
|
|
msg_id, conversation_id = getattr(chatbot_msg, "message_id", None) or "", getattr(chatbot_msg, "conversation_id", None) or ""
|
|
if msg_id and conversation_id:
|
|
self._adapter._spawn_bg(self._adapter._send_emotion(msg_id, conversation_id, t("platform.dingtalk.emotion.thinking"), recall=False))
|
|
asyncio.create_task(self._safe_on_message(chatbot_msg)) # surfaces exceptions in logs instead of losing them
|
|
except Exception:
|
|
logger.exception("[%s] Error preparing incoming message", self._adapter.name)
|
|
return AckMessage.STATUS_SYSTEM_EXCEPTION, "error"
|
|
return AckMessage.STATUS_OK, "OK"
|
|
|
|
async def _safe_on_message(self, chatbot_msg: "ChatbotMessage") -> None:
|
|
try:
|
|
await self._adapter._on_message(chatbot_msg)
|
|
except Exception:
|
|
logger.exception("[%s] Error processing incoming message", self._adapter.name)
|
|
|
|
|
|
async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False):
|
|
"""Out-of-process delivery (standalone_sender_fn) via the static robot webhook (DINGTALK_WEBHOOK_URL / extra
|
|
``webhook_url``) — per-session webhooks aren't available to cron jobs."""
|
|
try:
|
|
import httpx
|
|
except ImportError:
|
|
return send_error("httpx not installed")
|
|
# Scoped: the webhook URL carries the robot's access_token and IS the delivery target — a raw
|
|
# environ read would post a secondary profile's cron output to the default profile's robot.
|
|
webhook_url = (getattr(pconfig, "extra", {}) or {}).get("webhook_url") or _get_scoped_secret("DINGTALK_WEBHOOK_URL", "")
|
|
if not webhook_url:
|
|
return send_error("DingTalk not configured. Set DINGTALK_WEBHOOK_URL env var or webhook_url in dingtalk platform extra config.")
|
|
try:
|
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
|
resp = await client.post(webhook_url, json={"msgtype": "text", "text": {"content": message}})
|
|
resp.raise_for_status()
|
|
data = resp.json()
|
|
if data.get("errcode", 0) != 0:
|
|
return send_error(f"DingTalk API error: {data.get('errmsg', 'unknown')}")
|
|
return {"success": True, "platform": "dingtalk", "chat_id": chat_id}
|
|
except Exception as e:
|
|
try: # send_message_tool._error redacts access_token from webhook URLs (lazy import avoids a circular)
|
|
from tools.send_message_tool import _error as _redact_error
|
|
return _redact_error(f"DingTalk send failed: {e}")
|
|
except Exception:
|
|
return send_error(f"DingTalk send failed: {e}")
|
|
|
|
|
|
def interactive_setup() -> None:
|
|
"""Configure DingTalk — QR scan (recommended) or manual credential entry."""
|
|
from hermes_cli.config import save_env_value
|
|
from hermes_cli.setup import prompt_choice
|
|
from hermes_cli.cli_output import prompt, print_header, print_success, print_warning
|
|
from hermes_cli.setup_platforms import declines_reconfigure
|
|
print_header("DingTalk")
|
|
if declines_reconfigure("DingTalk", "Reconfigure DingTalk?", "DINGTALK_CLIENT_ID"):
|
|
return
|
|
choices = ["QR Code Scan (Recommended, auto-obtain Client ID and Client Secret)", "Manual Input (Client ID and Client Secret)"]
|
|
result = None
|
|
if prompt_choice("Choose setup method", choices, default=0) == 0:
|
|
try:
|
|
from hermes_cli.dingtalk_auth import dingtalk_qr_auth
|
|
result = dingtalk_qr_auth()
|
|
if result is None:
|
|
print_warning("QR auth incomplete, falling back to manual input.")
|
|
except ImportError as exc:
|
|
print_warning(f"QR auth module failed to load ({exc}), falling back to manual input.")
|
|
if result is not None:
|
|
for key, value in zip(("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"), result):
|
|
save_env_value(key, value)
|
|
return print_success("DingTalk configured via QR scan!")
|
|
_manual_credential_entry(prompt, save_env_value, print_success)
|
|
|
|
|
|
def _manual_credential_entry(prompt, save_env_value, print_success) -> None:
|
|
client_id = prompt("DingTalk Client ID (app key)")
|
|
if not client_id:
|
|
return
|
|
save_env_value("DINGTALK_CLIENT_ID", client_id)
|
|
if client_secret := prompt("DingTalk Client Secret", password=True):
|
|
save_env_value("DINGTALK_CLIENT_SECRET", client_secret)
|
|
print_success("DingTalk credentials saved")
|
|
|
|
|
|
def _nested_allowed_users(yaml_cfg: dict, dingtalk_cfg: dict):
|
|
"""Allowlist from ``extra.allowed_users``: this block's own extra first, then ``gateway.platforms.dingtalk.extra`` and ``platforms.dingtalk.extra``."""
|
|
_gw = yaml_cfg.get("gateway")
|
|
containers = (_gw.get("platforms") if isinstance(_gw, dict) else None, yaml_cfg.get("platforms"))
|
|
for holder in (dingtalk_cfg, *(c.get("dingtalk") if isinstance(c, dict) else None for c in containers)):
|
|
_extra = holder.get("extra") if isinstance(holder, dict) else None
|
|
if isinstance(_extra, dict) and _extra.get("allowed_users") is not None:
|
|
return _extra.get("allowed_users")
|
|
return None
|
|
|
|
|
|
_YAML_BRIDGE = ( # (yaml key, env var, kind) for apply_yaml_bridge
|
|
("require_mention", "DINGTALK_REQUIRE_MENTION", "lower"), ("mention_patterns", "DINGTALK_MENTION_PATTERNS", "json"),
|
|
("free_response_chats", "DINGTALK_FREE_RESPONSE_CHATS", "csv"), ("allowed_chats", "DINGTALK_ALLOWED_CHATS", "csv"),
|
|
("allowed_users", "DINGTALK_ALLOWED_USERS", "csv"),
|
|
)
|
|
|
|
|
|
def _apply_yaml_config(yaml_cfg: dict, dingtalk_cfg: dict) -> dict | None:
|
|
"""``apply_yaml_config_fn`` (#24849): config.yaml dingtalk: keys → DINGTALK_* env (env wins; skipped under a
|
|
multiplexed secondary profile's scope) + ``PlatformConfig.extra``. The docs put the allowlist at
|
|
``gateway.platforms.dingtalk.extra.allowed_users`` but gateway authz only consults DINGTALK_ALLOWED_USERS,
|
|
so nested-only allowlists are bridged too."""
|
|
cfg = dict(dingtalk_cfg)
|
|
if cfg.get("allowed_users") is None:
|
|
cfg["allowed_users"] = _nested_allowed_users(yaml_cfg, dingtalk_cfg)
|
|
return _apply_yaml_bridge(cfg, _YAML_BRIDGE)
|
|
|
|
|
|
|
|
def _is_connected(config) -> bool:
|
|
"""Connected when client_id + client_secret are present (PlatformConfig.extra first, then env)."""
|
|
return all(_credentials(getattr(config, "extra", {})))
|
|
|
|
|
|
|
|
def register(ctx) -> None:
|
|
"""Plugin entry point — called by the Hermes plugin system."""
|
|
ctx.register_platform(
|
|
name="dingtalk", label="DingTalk", adapter_factory=DingTalkAdapter, check_fn=dingtalk_deps_present,
|
|
ensure_deps_fn=ensure_dingtalk_deps, is_connected=_is_connected, validate_config=_is_connected,
|
|
required_env=["DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"], install_hint="pip install 'dingtalk-stream>=0.20' httpx",
|
|
setup_fn=interactive_setup, apply_yaml_config_fn=_apply_yaml_config, allowed_users_env="DINGTALK_ALLOWED_USERS",
|
|
allow_all_env="DINGTALK_ALLOW_ALL_USERS", cron_deliver_env_var="DINGTALK_HOME_CHANNEL",
|
|
standalone_sender_fn=_standalone_send, emoji="🐳", allow_update_command=True,
|
|
)
|