adapter.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import type {
  2. AskQuestionnaireReplyPayload,
  3. AskQuestionnaireRequest,
  4. } from '@mavis/shared/questionnaire';
  5. import type { OutboundMediaRef } from '@mavis/shared';
  6. import type { ChannelPlatform } from './route-api.js';
  7. import type { LocalChannelContext } from './infra.js';
  8. import type { ChannelInboundAttachmentRef, ChannelInboundEnvelope } from './envelope.js';
  9. import type {
  10. ChannelPermissionBehavior,
  11. ChannelRenderablePermission,
  12. LocalChannelPermissionPending,
  13. } from './permission-bridge.js';
  14. import type {
  15. ChannelQuestionnairePending,
  16. ChannelRenderableQuestionnaire,
  17. } from './questionnaire-bridge.js';
  18. import type { QuestionnaireReplyOutcome } from '../questionnaire/reply-outcome.js';
  19. /**
  20. * Unified platform adapter contract for the local-runtime channel layer.
  21. *
  22. * Every concrete IM platform (Telegram / Feishu / WeChat / mock) is expected to
  23. * eventually expose a `LocalChannelPlatformAdapter`. The adapter owns the
  24. * platform-specific edges — credential binding, inbound normalization, outbound
  25. * delivery, and attachment resolution — so the runner and infra layers stay
  26. * platform-agnostic.
  27. *
  28. * This file is intentionally type-only: it defines the contract that MR-B/C/D
  29. * implement against. No platform SDK is imported here.
  30. *
  31. * Media is modelled with the canonical `OutboundMediaRef` from `@mavis/shared`
  32. * (the same value object the UI's DeliverAssetsCard and `parseMediaTags`
  33. * produce) so the IM outbound surface never drifts from the UI on what counts
  34. * as a deliverable asset. The interactive `ask_user` round-trip rides as an
  35. * optional `questionnaire` field on `ChannelOutboundMessageInput` — only
  36. * adapters that can render structured interactive UI (Feishu card today) act
  37. * on it; the others ignore it and the platform-agnostic
  38. * {@link LocalChannelQuestionnaireBridge} owns the lifecycle / submit decode.
  39. */
  40. /**
  41. * Platform-agnostic questionnaire payload that an outbound channel message can
  42. * carry. Re-uses {@link AskQuestionnaireRequest} verbatim — the same value
  43. * object the UI composer renders — so the runtime never has to translate
  44. * between two questionnaire shapes. Adapters that render structured UI
  45. * (Feishu card) consume this; adapters that only render text (Telegram /
  46. * WeChat) either format a numbered fallback or ignore the payload.
  47. */
  48. export type ChannelQuestionnaire = AskQuestionnaireRequest;
  49. /**
  50. * Outbound message input handed to an adapter (or to a
  51. * `LocalMultiChannelClient.sendMessage` shim). `text` stays required so the
  52. * text-only path is identical to the legacy `sendText` call; `media` carries
  53. * the structured refs `parseMediaTags` extracted from the reply; the optional
  54. * `questionnaire` payload, when set, asks the adapter to render the
  55. * interactive form (card on Feishu, numbered text elsewhere) instead of (or
  56. * alongside) the plain text body. Adapters MUST treat all three of `text`,
  57. * `media`, `questionnaire` as additive when more than one is present.
  58. */
  59. export interface ChannelOutboundMessageInput {
  60. ctx: LocalChannelContext;
  61. text: string;
  62. media?: OutboundMediaRef[];
  63. questionnaire?: ChannelQuestionnaire;
  64. sessionId?: string;
  65. queueItemId?: string;
  66. /**
  67. * Internal execution-failure detail. Before any IM send, the shared
  68. * outbound boundary replaces it with a localized safe reply and removes
  69. * this field. It is not a transport delivery failure.
  70. */
  71. error?: string;
  72. }
  73. export interface ChannelOutboundResult {
  74. id: string;
  75. status: 'sent' | 'error';
  76. error?: string;
  77. }
  78. export interface ChannelBindInput {
  79. agentName: string;
  80. clientName?: string;
  81. credentials: Record<string, unknown>;
  82. }
  83. export interface ChannelBindResult {
  84. ok: boolean;
  85. clientName: string;
  86. error?: string;
  87. code?: string;
  88. }
  89. export interface ChannelUnbindInput {
  90. agentName: string;
  91. clientName?: string;
  92. }
  93. export interface ChannelUnbindResult {
  94. ok: boolean;
  95. }
  96. export interface ChannelStatusInput {
  97. agentName?: string;
  98. }
  99. export interface ChannelStatusResult {
  100. configured: boolean;
  101. connected: boolean;
  102. clientName: string;
  103. detail?: Record<string, unknown>;
  104. }
  105. export interface PlatformInboundInput {
  106. clientName: string;
  107. raw: unknown;
  108. }
  109. export interface ChannelAttachmentDownloadInput {
  110. clientName: string;
  111. ref: ChannelInboundAttachmentRef;
  112. /** Inbound message id (Feishu resource API needs it; Telegram ignores). */
  113. messageId?: string;
  114. /** Stable session/chat scope for the on-disk path. */
  115. sessionId?: string;
  116. }
  117. /**
  118. * Result of {@link LocalChannelPlatformAdapter.downloadAttachmentToLocal}.
  119. * Distinct from {@link ChannelInboundAttachmentRef} — `filePath` is
  120. * absolute and the optional `error` marker lets callers degrade gracefully
  121. * when one of several attachments fails to download.
  122. */
  123. export interface ChannelInboundAttachment {
  124. type: 'image' | 'file';
  125. filePath: string;
  126. fileName: string;
  127. mimeType: string;
  128. error?: string;
  129. }
  130. export type ChannelQuestionnaireReplyHandlingResult =
  131. | { ctx: LocalChannelContext; reply: AskQuestionnaireReplyPayload }
  132. | { handled: true }
  133. | null;
  134. /**
  135. * The unified platform adapter contract. Required methods cover the inbound →
  136. * dispatch → outbound core loop; `downloadAttachment` is optional because not
  137. * every platform message carries resolvable media.
  138. */
  139. export interface LocalChannelPlatformAdapter {
  140. readonly platform: ChannelPlatform;
  141. readonly clientName: string;
  142. bind(input: ChannelBindInput): Promise<ChannelBindResult>;
  143. unbind(input: ChannelUnbindInput): Promise<ChannelUnbindResult>;
  144. status(input?: ChannelStatusInput): Promise<ChannelStatusResult>;
  145. normalizeInbound(input: PlatformInboundInput): Promise<ChannelInboundEnvelope>;
  146. sendMessage(input: ChannelOutboundMessageInput): Promise<ChannelOutboundResult>;
  147. downloadAttachment?(input: ChannelAttachmentDownloadInput): Promise<ChannelInboundAttachmentRef>;
  148. /**
  149. * Resolve an inbound attachment ref to a local file on disk. Optional —
  150. * adapters that wire this method enable multimodal inbound through the
  151. * unified `/channel-bridge/{platform}/inbound` routes. Implementations
  152. * are expected to write under `<dataDir>/tmp/im-attachments/<platform>/...`
  153. * and return an absolute path so the runner can hand it to the agent.
  154. *
  155. * Distinct from {@link downloadAttachment}, which only enriches the ref
  156. * with `mimeType` / `name`. New code should prefer this method.
  157. */
  158. downloadAttachmentToLocal?(
  159. input: ChannelAttachmentDownloadInput,
  160. ): Promise<ChannelInboundAttachment>;
  161. /**
  162. * Render a pending permission ask into this platform's conversation.
  163. * Optional: an adapter that has not wired permission cards yet simply
  164. * omits it, and the core `LocalChannelPermissionBridge` degrades to
  165. * "permission card visible in UI only" without error. Returns the
  166. * platform message id so the inbound side can correlate the reply.
  167. *
  168. * Used by MR-D2 core. Per-platform implementations land in MR-D3
  169. * (Telegram inline keyboard) / MR-D4 (Feishu interactive card).
  170. */
  171. renderPermission?(input: {
  172. ctx: LocalChannelContext;
  173. renderable: ChannelRenderablePermission;
  174. }): Promise<{ outboundMessageId?: string }>;
  175. renderQuestionnaire?(input: {
  176. ctx: LocalChannelContext;
  177. renderable: ChannelRenderableQuestionnaire;
  178. }): Promise<{ outboundMessageId?: string }>;
  179. /**
  180. * @deprecated Use {@link tryHandleQuestionnaireReply} instead. This
  181. * variant requires the caller to know which `pending` matches the
  182. * inbound, which forces every caller to enumerate pending state — the
  183. * adapter is in a better position to track that itself.
  184. */
  185. parseQuestionnaireReply?(input: {
  186. raw: unknown;
  187. pending: ChannelQuestionnairePending;
  188. }): Promise<AskQuestionnaireReplyPayload | null>;
  189. /**
  190. * Attempt to interpret an inbound chat event as a reply to a
  191. * previously-rendered questionnaire. The adapter owns its own
  192. * `pendingByChat` bookkeeping (recorded in `renderQuestionnaire`), so
  193. * the runner does not need to know which platform encoding (numbered
  194. * text, inline keyboard, card form) was used.
  195. *
  196. * Returns `{ ctx, reply }` when a complete reply is ready — the runner
  197. * then forwards to the questionnaire bridge instead of dispatching the
  198. * inbound as a plain user message. Returns `{ handled: true }` when the
  199. * adapter has consumed an intermediate platform interaction (for example
  200. * Telegram advancing to the next inline-keyboard step) but there is not
  201. * yet a complete reply to submit. Returns `null` when the inbound is
  202. * unrelated (normal chat), and the runner continues with its usual flow.
  203. *
  204. * Inputs are intentionally flexible:
  205. * - `ctx` — the channel context the runner has already parsed from
  206. * the inbound (chatId is the key into pendingByChat).
  207. * - `text` — the inbound text body (numbered-text reply for WeChat).
  208. * - `raw` — the raw platform event (Bot API `callback_query`, Feishu
  209. * `card.action.trigger`). Adapters that need wire-level access
  210. * read this; pure-text adapters can ignore it.
  211. *
  212. * Implementations MUST consume duplicates for a reply already marked
  213. * in-flight. The runner settles the pending entry through
  214. * {@link settleQuestionnaireReply}; a retryable outcome restores it.
  215. */
  216. tryHandleQuestionnaireReply?(input: {
  217. ctx: LocalChannelContext;
  218. text?: string;
  219. raw?: unknown;
  220. }): Promise<ChannelQuestionnaireReplyHandlingResult>;
  221. /**
  222. * Commit or roll back the adapter-owned pending entry after the host reply
  223. * route finishes. A settle failure is handled by the runner and must never
  224. * turn an already-handled inbound into a normal Agent turn.
  225. */
  226. settleQuestionnaireReply?(input: {
  227. ctx: LocalChannelContext;
  228. requestId: string;
  229. outcome: QuestionnaireReplyOutcome;
  230. }): Promise<void>;
  231. /**
  232. * Start a "The other party is typing" / chat-action indicator for the turn. Called by the
  233. * channel runner immediately before `runQueuedTurn`. Optional — adapters
  234. * that do not implement typing simply omit the method and the runner
  235. * skips the indicator. Implementations MUST be best-effort: every
  236. * failure must be swallowed; typing must never surface to the turn.
  237. */
  238. notifyTurnStart?(ctx: LocalChannelContext): Promise<void>;
  239. /**
  240. * Stop the typing indicator armed by {@link notifyTurnStart}. Called by
  241. * the channel runner after `sendCollected` returns, on both success and
  242. * error paths. Same best-effort contract.
  243. */
  244. notifyTurnEnd?(ctx: LocalChannelContext): Promise<void>;
  245. /**
  246. * Stop any background work this adapter owns (long-poll loops, WS
  247. * connections, monitor timers). Called by `host.shutdown()` on
  248. * graceful Node exit so AbortControllers unwind cleanly before the
  249. * process terminates. Implementations MUST be idempotent — a host
  250. * may call this multiple times during shutdown sequencing.
  251. *
  252. * Optional because not every adapter has background work (the legacy
  253. * mock adapter for tests does not). Implementations should NOT throw —
  254. * a noisy shutdown path that throws can prevent other adapters from
  255. * being torn down.
  256. */
  257. shutdown?(): void | Promise<void>;
  258. /**
  259. * Attempt to parse a platform callback as a reply to the given pending
  260. * permission ask. Returns the decoded decision behavior, or `null` when
  261. * the inbound is a normal message that should flow to `handleInbound`
  262. * instead. The bridge maps the behavior to the daemon's
  263. * `allowOnce / allowAlways / deny` vocabulary at the route boundary.
  264. */
  265. parsePermissionReply?(input: {
  266. raw: unknown;
  267. pending: LocalChannelPermissionPending;
  268. }): Promise<{ behavior: ChannelPermissionBehavior } | null>;
  269. }