channel-plugin.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. /**
  2. * ChannelPlugin — multi-channel plugin architecture type definitions.
  3. *
  4. * Replaces the BaseChannelPlugin inheritance model with a composition-based
  5. * adapter pattern. Each channel platform implements ChannelPlugin with
  6. * 4 required + 6 optional adapters.
  7. *
  8. * Design references:
  9. * - Composition over inheritance
  10. * - Dual-layer separation: channel messages via adapters, complex ops via CLI
  11. * - OpenClaw ChannelPlugin patterns (flat adapter composition)
  12. */
  13. import type { ChannelPlatform } from './channel-route.js';
  14. import type { ChatType } from './channel-context.js';
  15. import type { AskQuestionnaireRequest, AskQuestionnaireReplyPayload } from './questionnaire.js';
  16. // ============================================================================
  17. // Core Types
  18. // ============================================================================
  19. /**
  20. * Unified parsed event from any channel platform.
  21. * Produced by ChannelInboundAdapter.parseEvent() from raw platform events.
  22. */
  23. export interface ChannelParsedEvent {
  24. /** Event type discriminator */
  25. kind: 'message' | 'card_action' | 'reaction';
  26. /** Source platform */
  27. platform: ChannelPlatform;
  28. /** Chat/conversation type */
  29. chatType: ChatType;
  30. /** Chat/conversation unique ID */
  31. chatId: string;
  32. /** Platform message ID */
  33. messageId: string;
  34. /** Sender user ID */
  35. senderId: string;
  36. /** Sender display name (optional, for logging) */
  37. senderName?: string;
  38. /**
  39. * Client/user language tag reported by the platform (e.g. 'en' / 'zh-hans').
  40. * Filled best-effort by the inbound adapter; consumed to localize outbound
  41. * copy. Absent → outbound falls back to the channel default locale.
  42. */
  43. locale?: string;
  44. /** Extracted text content */
  45. text: string;
  46. /** Whether the bot was @mentioned */
  47. hasMention: boolean;
  48. /** Attached files/images/audio */
  49. attachments: ChannelAttachment[];
  50. /** Original unprocessed platform event */
  51. rawEvent: unknown;
  52. /** Event timestamp (Unix ms) */
  53. timestamp: number;
  54. /**
  55. * Parent message ID when this message is a reply.
  56. * Used to fetch the original message for context injection.
  57. */
  58. parentMessageId?: string;
  59. /**
  60. * Quoted message content when this message is a reply.
  61. * Populated by the inbound adapter's fetchParentMessage().
  62. */
  63. quotedMessage?: {
  64. /** Extracted text content of the quoted message */
  65. text: string;
  66. /** Sender display name (if available) */
  67. senderName?: string;
  68. };
  69. }
  70. /** Attachment descriptor from inbound messages. */
  71. export interface ChannelAttachment {
  72. /** Attachment type */
  73. type: 'image' | 'file' | 'audio' | 'video';
  74. /** Platform-specific resource key */
  75. key: string;
  76. /** Platform message ID that owns this resource, if different from the event message. */
  77. sourceMessageId?: string;
  78. /** Original filename (if known) */
  79. name?: string;
  80. /** MIME type (if known) */
  81. mimeType?: string;
  82. /** File size in bytes (if known) */
  83. size?: number;
  84. }
  85. /**
  86. * Context passed to outbound adapters for sending messages.
  87. * Constructed from ChannelContext by ChannelPluginRunner.
  88. */
  89. export interface ChannelOutboundContext {
  90. /** Target chat/conversation ID */
  91. chatId: string;
  92. /** Message ID to reply to (for threading) */
  93. replyToMessageId?: string;
  94. /** Thread/topic ID (platform-specific) */
  95. threadId?: string;
  96. /** Agent session ID (for state correlation) */
  97. sessionId?: string;
  98. /** Agent display name */
  99. agentName?: string;
  100. /** Channel client instance name */
  101. clientName: string;
  102. }
  103. /** Result of a send operation. */
  104. export interface ChannelSendResult {
  105. /** Whether the send was successful */
  106. success: boolean;
  107. /** Platform message ID of the sent message */
  108. messageId?: string;
  109. /** Error message if failed */
  110. error?: string;
  111. }
  112. /** Media payload for sending media messages. */
  113. export interface ChannelMediaPayload {
  114. /** Media type */
  115. type: 'image' | 'file' | 'audio' | 'video';
  116. /** File path or URL */
  117. source: string;
  118. /** MIME type */
  119. mimeType?: string;
  120. /** Caption text */
  121. caption?: string;
  122. }
  123. /** Tool call step for rich reply card rendering. */
  124. export interface ChannelToolStep {
  125. /** Tool name */
  126. name: string;
  127. /** Human-readable detail (file path, URL, command, etc.) */
  128. detail?: string;
  129. /** Tool call status */
  130. status: 'running' | 'finished' | 'failed';
  131. /** Tool call ID */
  132. callId: string;
  133. /** Raw tool arguments (JSON string) */
  134. args?: string;
  135. }
  136. /** Permission request for approval flow. */
  137. export interface ChannelPermissionRequest {
  138. /** Unique request ID */
  139. requestId: string;
  140. /** Agent session ID */
  141. sessionId: string;
  142. /** Agent name */
  143. agentName: string;
  144. /** Human-readable description of what is being requested */
  145. description: string;
  146. /** Tool name that triggered the request */
  147. toolName?: string;
  148. /** Tool arguments (JSON) */
  149. toolArgs?: string;
  150. /** AI-generated tool description (only present for tools that provide it, e.g. bash) */
  151. toolDescription?: string;
  152. /** Human-readable tool input (command, file path, etc.) */
  153. toolInput?: string;
  154. }
  155. /** User's decision on a permission request. */
  156. export interface ChannelPermissionDecision {
  157. /** Request ID being decided */
  158. requestId: string;
  159. /** User's decision */
  160. action: 'allow' | 'deny' | 'allow-always';
  161. /** User ID who made the decision */
  162. userId: string;
  163. }
  164. /** Connection probe result. */
  165. export interface ChannelProbeResult {
  166. /** Whether the connection is healthy */
  167. healthy: boolean;
  168. /** Bot display name (if retrieved) */
  169. botName?: string;
  170. /** Bot platform ID (e.g., open_id for Feishu) */
  171. botId?: string;
  172. /** Auth status */
  173. authStatus: 'valid' | 'expired' | 'unknown' | 'ok' | 'failed';
  174. /** Error details if unhealthy */
  175. error?: string;
  176. }
  177. // ============================================================================
  178. // Account Configuration
  179. // ============================================================================
  180. /** Platform-agnostic account configuration. */
  181. export interface ChannelAccountConfig {
  182. /** Account instance name (e.g., "main-bot", "test-bot") */
  183. name: string;
  184. /** Whether this account is enabled */
  185. enabled: boolean;
  186. /** Platform identifier */
  187. platform: ChannelPlatform;
  188. /** Platform-specific credentials */
  189. credentials: Record<string, string>;
  190. /** Connection mode */
  191. mode?: string;
  192. /** Additional platform-specific options */
  193. options?: Record<string, unknown>;
  194. }
  195. // ============================================================================
  196. // Capability Declaration
  197. // ============================================================================
  198. /**
  199. * Static capability declaration for a channel platform.
  200. * ChannelPluginRunner uses this to decide behavior paths instead of
  201. * platform-specific if/else checks.
  202. */
  203. export interface ChannelCapabilities {
  204. /** Supported chat types */
  205. chatTypes: ChatType[];
  206. /** Supports interactive card messages */
  207. interactiveCards: boolean;
  208. /** Supports in-place card content update (streaming) */
  209. streamingUpdate: boolean;
  210. /** Supports emoji reactions */
  211. reactions: boolean;
  212. /** Supports editing sent messages */
  213. editMessage: boolean;
  214. /** Supports native threads/topics */
  215. threads: boolean;
  216. /** Supports media messages (images, files) */
  217. media: boolean;
  218. /** Supports audio messages and transcription */
  219. audio: boolean;
  220. /** Supports @mention detection */
  221. mentions: boolean;
  222. /**
  223. * Whether this channel requires the per-sender owner-on-first-DM gate
  224. * in `InboundEventHandler`.
  225. *
  226. * Public bots (Telegram, Feishu) have no platform-level per-bot
  227. * authentication: anyone who knows the bot's @username can DM it, so
  228. * the application layer must restrict each bot to a single owner
  229. * sender. These plugins should leave this at the default `true`.
  230. *
  231. * Bots whose platform enforces per-bot authentication (WeChat iLink
  232. * Bot — bound to a single authed user via QR) authenticate the user
  233. * at the platform level and should set this to `false` to skip the
  234. * owner gate entirely. Skipping the gate also avoids persisting a
  235. * meaningless `wechat:<agentName>` row to `channel-owner.yaml`.
  236. *
  237. * Default: `true` (preserve existing gate behavior for plugins that
  238. * have not yet opted in).
  239. */
  240. requiresOwnerGate?: boolean;
  241. }
  242. /** Plugin metadata for display/registration. */
  243. export interface ChannelMeta {
  244. /** Human-readable platform name */
  245. label: string;
  246. /** Platform description */
  247. description?: string;
  248. /** Platform icon URL or emoji */
  249. icon?: string;
  250. /** Sort order for UI display */
  251. order?: number;
  252. }
  253. // ============================================================================
  254. // Required Adapters (4)
  255. // ============================================================================
  256. /**
  257. * Config Adapter — account configuration management.
  258. * Responsible for listing and validating accounts from the application config.
  259. */
  260. export interface ChannelConfigAdapter {
  261. /**
  262. * List all account configurations for this platform.
  263. * @param cfg - Raw application config object
  264. */
  265. listAccounts(cfg: Record<string, unknown>): ChannelAccountConfig[];
  266. /**
  267. * Validate an account configuration.
  268. * Returns validation result with potential error messages.
  269. */
  270. validateAccount(
  271. account: ChannelAccountConfig,
  272. ): { valid: true } | { valid: false; errors: string[] };
  273. /** Optional JSON schema for platform-specific configuration. */
  274. configSchema?(): Record<string, unknown>;
  275. }
  276. /**
  277. * Gateway Adapter — connection lifecycle management.
  278. * Manages the connection to the channel platform (WebSocket, polling, etc.).
  279. */
  280. export interface ChannelGatewayAdapter {
  281. /**
  282. * Start the connection and begin receiving events.
  283. * Events are delivered via ctx.onRawEvent callback.
  284. */
  285. start(ctx: ChannelGatewayContext): Promise<void>;
  286. /**
  287. * Stop the connection gracefully.
  288. */
  289. stop(ctx: ChannelGatewayContext): Promise<void>;
  290. /**
  291. * Optional health probe — check connection status and credentials.
  292. */
  293. probe?(ctx: ChannelGatewayContext): Promise<ChannelProbeResult>;
  294. }
  295. /** Runtime context provided to the gateway adapter. */
  296. export interface ChannelGatewayContext {
  297. /** Account configuration */
  298. account: ChannelAccountConfig;
  299. /** Client instance name */
  300. clientName: string;
  301. /** Data directory for persistent storage */
  302. dataDir: string;
  303. /** Callback for delivering raw platform events to ChannelPluginRunner */
  304. onRawEvent: (rawEvent: unknown) => Promise<void>;
  305. /** Signal for graceful shutdown */
  306. abortSignal: AbortSignal;
  307. }
  308. /**
  309. * Inbound Adapter — incoming event parsing.
  310. * Converts raw platform events into the unified ChannelParsedEvent format.
  311. */
  312. export interface ChannelInboundAdapter {
  313. /**
  314. * Parse a raw platform event into a unified ChannelParsedEvent.
  315. * Returns null if the event should be ignored (unsupported type, etc.).
  316. *
  317. * May be sync or async — async is required when the adapter needs to fetch
  318. * additional content from the platform (e.g. expanding Feishu merge_forward
  319. * by calling GET /messages/{id}). Existing sync implementations remain valid.
  320. */
  321. parseEvent(
  322. rawEvent: unknown,
  323. ctx: ChannelInboundContext,
  324. ): (ChannelParsedEvent | null) | Promise<ChannelParsedEvent | null>;
  325. /**
  326. * Download an attachment from the platform.
  327. * Returns the local file path of the downloaded file.
  328. */
  329. downloadAttachment?(
  330. event: ChannelParsedEvent,
  331. attachment: ChannelAttachment,
  332. ctx: ChannelInboundContext,
  333. ): Promise<string>;
  334. /**
  335. * Transcribe an audio file to text.
  336. * Returns the transcription text.
  337. */
  338. transcribeAudio?(audioPath: string, ctx: ChannelInboundContext): Promise<string>;
  339. /**
  340. * Fetch the content of a parent message (for reply context).
  341. * Returns the text content and optional sender name, or null if not available.
  342. */
  343. fetchParentMessage?(
  344. parentMessageId: string,
  345. ctx: ChannelInboundContext,
  346. ): Promise<{ text: string; senderName?: string } | null>;
  347. }
  348. /** Context provided to inbound adapter methods. */
  349. export interface ChannelInboundContext {
  350. /** Client instance name */
  351. clientName: string;
  352. /** Account configuration */
  353. account: ChannelAccountConfig;
  354. /** Data directory */
  355. dataDir: string;
  356. /** Bot's platform user ID (for @mention detection) */
  357. botId?: string;
  358. }
  359. /**
  360. * Outbound Adapter — message sending.
  361. * Handles sending messages to the channel platform.
  362. */
  363. export interface ChannelOutboundAdapter {
  364. /**
  365. * Send a text message to a chat.
  366. */
  367. sendText(ctx: ChannelOutboundContext, text: string): Promise<ChannelSendResult>;
  368. /**
  369. * Reply to a specific message (for threading/quoting).
  370. */
  371. replyTo?(
  372. ctx: ChannelOutboundContext,
  373. messageId: string,
  374. text: string,
  375. ): Promise<ChannelSendResult>;
  376. /**
  377. * Send a media message (image, file, audio, video).
  378. */
  379. sendMedia?(ctx: ChannelOutboundContext, media: ChannelMediaPayload): Promise<ChannelSendResult>;
  380. /** Maximum text length for a single message. */
  381. textLimit: number;
  382. /**
  383. * Split text into chunks respecting the platform's message length limit.
  384. * If not provided, ChannelPluginRunner uses a default paragraph-aware splitter.
  385. */
  386. chunkText?(text: string, limit: number): string[];
  387. }
  388. // ============================================================================
  389. // Optional Adapters (6)
  390. // ============================================================================
  391. /**
  392. * RichReply Adapter — interactive card message lifecycle.
  393. * Implements the Thinking -> Working -> Done card state machine.
  394. * Only used when capabilities.interactiveCards is true.
  395. */
  396. export interface ChannelRichReplyAdapter {
  397. /**
  398. * Send an initial queued card/message. Returns the card/message ID.
  399. * Used when a session already has work ahead of this inbound message.
  400. */
  401. sendQueued?(
  402. ctx: ChannelOutboundContext,
  403. userText: string,
  404. queueInfo: ChannelQueueInfo,
  405. ): Promise<string>;
  406. /**
  407. * Update an existing queued card/message to the initial thinking state.
  408. */
  409. updateThinking?(ctx: ChannelOutboundContext, cardMsgId: string, userText: string): Promise<void>;
  410. /**
  411. * Send initial "thinking" card. Returns the card message ID.
  412. */
  413. sendThinking(ctx: ChannelOutboundContext, userText: string): Promise<string>;
  414. /**
  415. * Update the card to "working" state with tool call progress.
  416. */
  417. updateWorking(
  418. ctx: ChannelOutboundContext,
  419. cardMsgId: string,
  420. steps: ChannelToolStep[],
  421. currentStep: string,
  422. elapsed: number,
  423. ): Promise<void>;
  424. /**
  425. * Update the card to "done" state with the final response.
  426. */
  427. updateDone(
  428. ctx: ChannelOutboundContext,
  429. cardMsgId: string,
  430. text: string,
  431. steps: ChannelToolStep[],
  432. ): Promise<void>;
  433. /**
  434. * Update the card to show an error state.
  435. */
  436. updateError?(
  437. ctx: ChannelOutboundContext,
  438. cardMsgId: string,
  439. error: string,
  440. info?: ChannelSessionErrorInfo,
  441. ): Promise<void>;
  442. /**
  443. * Send a standalone error card/message (no prior thinking card needed).
  444. * Used for delayed follow-up failures.
  445. */
  446. sendError?(
  447. ctx: ChannelOutboundContext,
  448. error: string,
  449. info?: ChannelSessionErrorInfo,
  450. ): Promise<string>;
  451. /**
  452. * Send a standalone "done" card (no prior thinking card needed).
  453. * Used for follow-up messages that should appear as cards, not plain text.
  454. */
  455. sendDone?(ctx: ChannelOutboundContext, text: string): Promise<string>;
  456. /**
  457. * Send a standalone "BTW" (peek / side-channel) reply card.
  458. * Carries a BTW tag so users can tell it apart from the main reply.
  459. * Optional — text-only channels fall back to a text prefix.
  460. */
  461. sendPeek?(ctx: ChannelOutboundContext, text: string): Promise<string>;
  462. }
  463. export interface ChannelSessionErrorInfo {
  464. message: string;
  465. errorCode?: number;
  466. actionText?: string;
  467. actionUrl?: string;
  468. }
  469. export interface ChannelQueueInfo {
  470. /** 1-based position among queued messages, excluding the currently running turn. */
  471. position: number;
  472. /** Queued messages before this item. */
  473. queuedAhead: number;
  474. /** Currently running turn ahead of this item, if any. */
  475. activeAhead: number;
  476. /** Total messages/turns ahead from the user's perspective. */
  477. totalAhead: number;
  478. }
  479. /**
  480. * Auth Adapter — read-side access to the current user token.
  481. *
  482. * The platform-specific OAuth/device-code flow that *acquires* the user
  483. * token lives outside this adapter — for Feishu, it is delegated to
  484. * `lark-cli auth login --recommend` driven by the daemon's onboard
  485. * route. The adapter exists so the channel-bridge runtime can read the
  486. * current UAT (refreshing on the fly if needed) without knowing the
  487. * platform-specific store layout.
  488. */
  489. export interface ChannelAuthAdapter {
  490. /**
  491. * Get the current user token, or null if not authenticated.
  492. */
  493. getUserToken(accountId: string): Promise<string | null>;
  494. }
  495. /**
  496. * Actions Adapter — message-level operations.
  497. * Handles reactions, message editing, deletion, etc.
  498. */
  499. export interface ChannelActionsAdapter {
  500. /**
  501. * Add an emoji reaction to a message.
  502. */
  503. addReaction?(ctx: ChannelOutboundContext, messageId: string, emoji: string): Promise<void>;
  504. /**
  505. * Remove an emoji reaction from a message.
  506. */
  507. removeReaction?(ctx: ChannelOutboundContext, messageId: string, emoji: string): Promise<void>;
  508. /**
  509. * Edit a previously sent message.
  510. */
  511. editMessage?(ctx: ChannelOutboundContext, messageId: string, newText: string): Promise<void>;
  512. /**
  513. * Delete a message.
  514. */
  515. deleteMessage?(ctx: ChannelOutboundContext, messageId: string): Promise<void>;
  516. /**
  517. * Start a typing/processing indicator. Returns a cleanup function.
  518. * Called by PluginRunner on inbound message; cleanup called in finally block.
  519. */
  520. startTypingIndicator?(messageId: string): () => void;
  521. }
  522. /**
  523. * Approval Adapter — permission request/approval flow.
  524. * Handles interactive permission cards and user approval decisions.
  525. */
  526. export interface ChannelApprovalAdapter {
  527. /**
  528. * Send a permission request card. Returns the card message ID.
  529. */
  530. sendPermissionAsk(
  531. ctx: ChannelOutboundContext,
  532. request: ChannelPermissionRequest,
  533. ): Promise<string>;
  534. /**
  535. * Embed permission action buttons into a "done" card payload.
  536. */
  537. embedInDoneCard?(cardPayload: unknown, requests: ChannelPermissionRequest[]): unknown;
  538. /**
  539. * Parse a raw event into a permission decision, or null if not a permission action.
  540. */
  541. parsePermissionAction(rawEvent: unknown): ChannelPermissionDecision | null;
  542. }
  543. /**
  544. * Result of parsing a questionnaire card-action submit event. Carries the
  545. * structured reply (already mapped from the card's `form_value`) plus the
  546. * routing context embedded in the submit button's `value` so the handler can
  547. * dispatch the reply to the right session without an extra store lookup.
  548. */
  549. export interface ChannelQuestionnaireSubmit {
  550. requestId: string;
  551. sessionId?: string;
  552. reply: AskQuestionnaireReplyPayload;
  553. }
  554. /**
  555. * Questionnaire Adapter — interactive `ask_user` (V2 questionnaire) flow for
  556. * card-capable channels (Feishu). Mirrors {@link ChannelApprovalAdapter}:
  557. * card-capable channels implement it to render a form card and parse the
  558. * submit callback; text-only channels (WeChat) omit it and the handler falls
  559. * back to a numbered-text round-trip via the outbound adapter.
  560. */
  561. export interface ChannelQuestionnaireAdapter {
  562. /**
  563. * Send a questionnaire form card. Returns the card message ID (empty on
  564. * failure so the handler can retry).
  565. */
  566. sendQuestionnaireAsk(
  567. ctx: ChannelOutboundContext,
  568. request: AskQuestionnaireRequest,
  569. ): Promise<string>;
  570. /**
  571. * Parse a raw card-action submit event into a structured reply, or null
  572. * when the event is not a questionnaire submit.
  573. */
  574. parseQuestionnaireSubmit(rawEvent: unknown): ChannelQuestionnaireSubmit | null;
  575. /**
  576. * Best-effort: update the card to a "submitted" state once the answers
  577. * have been forwarded to the agent.
  578. */
  579. updateCardAsSubmitted?(messageId: string, request: AskQuestionnaireRequest): Promise<void>;
  580. }
  581. /**
  582. * Threading Adapter — thread/topic management.
  583. * Handles platform-specific thread semantics.
  584. */
  585. export interface ChannelThreadingAdapter {
  586. /**
  587. * Resolve the thread ID for a reply.
  588. * Different platforms have different threading models.
  589. */
  590. resolveThreadId?(event: ChannelParsedEvent): string | undefined;
  591. /**
  592. * Create a new thread from a message.
  593. */
  594. createThread?(ctx: ChannelOutboundContext, messageId: string, title?: string): Promise<string>;
  595. /**
  596. * Send a message into an existing thread.
  597. */
  598. sendToThread?(
  599. ctx: ChannelOutboundContext,
  600. threadId: string,
  601. text: string,
  602. ): Promise<ChannelSendResult>;
  603. }
  604. /**
  605. * Directory Adapter — user/group directory queries.
  606. * Provides lookup capabilities for platform users and groups.
  607. */
  608. export interface ChannelDirectoryAdapter {
  609. /**
  610. * Get the bot's own identity on the platform.
  611. */
  612. self?(ctx: ChannelInboundContext): Promise<ChannelDirectoryEntry | null>;
  613. /**
  614. * List available peer users (DM targets).
  615. */
  616. listPeers?(ctx: ChannelInboundContext): Promise<ChannelDirectoryEntry[]>;
  617. /**
  618. * List available groups/channels.
  619. */
  620. listGroups?(ctx: ChannelInboundContext): Promise<ChannelDirectoryEntry[]>;
  621. /**
  622. * List members of a specific group.
  623. */
  624. listGroupMembers?(ctx: ChannelInboundContext, groupId: string): Promise<ChannelDirectoryEntry[]>;
  625. }
  626. /** Directory entry representing a user or group. */
  627. export interface ChannelDirectoryEntry {
  628. /** Platform user/group ID */
  629. id: string;
  630. /** Display name */
  631. name: string;
  632. /** Entry type */
  633. type: 'user' | 'group' | 'bot';
  634. /** Avatar URL */
  635. avatarUrl?: string;
  636. }
  637. // ============================================================================
  638. // Plugin Main Contract
  639. // ============================================================================
  640. /**
  641. * ChannelPlugin — the main plugin interface for a channel platform.
  642. *
  643. * Each channel platform (Feishu, Telegram, Slack, etc.) implements this
  644. * interface with 4 required adapters and any applicable optional adapters.
  645. *
  646. * ChannelPluginRunner consumes this interface to drive message dispatch,
  647. * using capabilities + adapter presence to determine behavior paths.
  648. * No platform-specific logic exists in the Runner.
  649. */
  650. export interface ChannelPlugin {
  651. /** Platform identifier (unique across all plugins) */
  652. readonly id: ChannelPlatform;
  653. /** Plugin metadata for display */
  654. readonly meta: ChannelMeta;
  655. /** Static capability declaration */
  656. readonly capabilities: ChannelCapabilities;
  657. // --- Required Adapters ---
  658. /** Account configuration management */
  659. readonly config: ChannelConfigAdapter;
  660. /** Connection lifecycle (WebSocket, polling, etc.) */
  661. readonly gateway: ChannelGatewayAdapter;
  662. /** Incoming event parsing */
  663. readonly inbound: ChannelInboundAdapter;
  664. /** Message sending */
  665. readonly outbound: ChannelOutboundAdapter;
  666. // --- Optional Adapters ---
  667. /** Interactive card message lifecycle (Thinking -> Working -> Done) */
  668. readonly richReply?: ChannelRichReplyAdapter;
  669. /** User authentication flow */
  670. readonly auth?: ChannelAuthAdapter;
  671. /** Message-level operations (reactions, edit, delete) */
  672. readonly actions?: ChannelActionsAdapter;
  673. /** Permission request/approval flow */
  674. readonly approval?: ChannelApprovalAdapter;
  675. /** Interactive questionnaire (ask_user / V2) flow for card-capable channels */
  676. readonly questionnaire?: ChannelQuestionnaireAdapter;
  677. /** Thread/topic management */
  678. readonly threading?: ChannelThreadingAdapter;
  679. /** User/group directory queries */
  680. readonly directory?: ChannelDirectoryAdapter;
  681. }