Skip to content

IM Gateway & Platforms ​

@iki/im is iKi's decoupled instant messaging gateway shell. It bridges IM platforms (starting with Feishu / Lark) to the same @iki/harness runtime, @iki/system-prompt persona pipeline, and MCP tools—without introducing any IM, role, or tenant concepts into core packages.

Quick Start (Feishu / Lark) ​

Feishu / Lark support uses Node 24+ native fetch and WebSocket with zero third-party SDK dependencies, and supports one-click QR bot setup via OAuth Device Flow:

bash
# 1. Scan the terminal QR code with Feishu (or use `iki connect lark` for Lark)
iki connect feishu

# 2. Start the gateway (automatically runs in ~/.iki/home by default)
iki gateway

Useful flags:

  • iki gateway --personality friendly|pragmatic|none — override the default IM persona tone
  • iki gateway -C /path/to/workspace — explicitly override the default ~/.iki/home workspace
  • iki connect feishu --no-start — save credentials without starting the gateway immediately

Chat Commands ​

Inside any connected IM conversation:

  • /pair <code> — bind an external account to the local owner identity using a single-use, TTL-bounded pair code
  • /new — reset the active thread for the current chat or topic
  • /stop — abort an in-flight turn immediately

Built-In Governance & Safety ​

Every platform connected through @iki/im automatically inherits the gateway's shared runtime protections:

  • Identity & Default-Deny: external accounts are keyed by immutable platform user IDs (never display names). Unlinked users cannot invoke built-in tools or see owner_only MCP servers.
  • Group Hygiene: inbound deduplication, bot-loop suppression (ignoreBots), @bot wake checks, ambient group message buffering (group_buffer.ts), and per-group sliding-window cooldown breakers.
  • Session Routing & Prompt Context: persistent SessionRoute ↔ ikiThreadId mapping (supporting private chats, groups, topics/threads, and optional per-user group isolation), multi-turn history replay, PERSONA.md, and <im_context> via @iki/system-prompt.
  • Output Resilience: fence-safe Markdown chunking respecting maxMessageLength, throttled streaming card edits when the platform supports edit(), and immediate abort when a user withdraws the target message.

Configuration ([im]) ​

Tune gateway defaults in ~/.iki/settings.toml:

toml
[im]
defaultPersonality = "friendly"   # "friendly" | "pragmatic" | "none"
busyPolicy = "queue"              # "queue" | "steer" | "reject"
groupIsolation = "shared"         # "shared" | "per_user"
maxConcurrentTurns = 4
ignoreBots = true
requireMentionInGroups = true
groupMaxTriggersPerWindow = 12
groupWindowMs = 60000
groupCooldownMs = 60000
groupHistoryLimit = 20
pairCodeTtlMs = 300000

Implementing a New IM Platform ​

Adding a new platform (Telegram, Discord, Slack, WeCom, etc.) requires 2 contracts + 1 line of registration. Gateway orchestration, identity linking, policy enforcement, session routing, and CLI commands stay untouched.

1. Implement PlatformAdapter ​

Defined in packages/core/src/types/im.ts. Unlike frameworks that attach send() methods onto inbound event subclasses, iKi separates immutable message data (UnifiedMessage) from transport (PlatformAdapter) so proactive sends (background jobs, scheduled wakeups) work without fabricating an inbound event.

Required members (1 capability descriptor + 3 methods):

MemberResponsibility
instanceId / platformInstance identifier and canonical platform kind (e.g. 'telegram', 'discord')
capabilitiesDeclare streaming ('edit_message' | 'final_only'), streamEditIntervalMs, proactiveSend, threads, typingIndicator, maxMessageLength, markdownDialect
start(sink)Open the transport (WebSocket, long polling, or webhook), normalize incoming messages into UnifiedMessage, and push sink({ kind: 'message', message })
stop()Close connections and timers cleanly so SIGINT exits without hanging
send(route, message)Deliver a message to SessionRoute (supporting replyToMessageId) and return ExternalMessageRef

Optional members (omit if unsupported; the gateway degrades gracefully):

MemberResponsibility
edit?(ref, message)Edit a previously sent message for streaming progress cards; omitted adapters fall back to a single final send()
sendTyping?(route)Emit a typing indicator
getBotDisplayName?()Expose the bot's display name for <im_context> and group @mention stripping

Normalization rules for UnifiedMessage:

  • Always populate sender.id with the platform's immutable user ID—never a mutable nickname.
  • Set route accurately (chatType: 'private' | 'group' | 'channel', plus threadId for topic/thread replies).
  • Detect self-mentions accurately (isMentioningSelf) and strip the bot's own @mention placeholder from plainText.
  • Populate { type: 'reply', messageId, quotedText } in parts when a message quotes an earlier message.

2. Implement PlatformProvider ​

Defined in packages/im/src/registry.ts. It packages onboarding (iki connect <platform>) and adapter construction:

ts
import type { PlatformAdapter } from '@iki/core/types/im';
import type { PlatformInstanceConfig } from '../../instance_store';
import type {
  PlatformAdapterHooks,
  PlatformConnectContext,
  PlatformProvider,
} from '../../registry';

export const myPlatformProvider: PlatformProvider = {
  kind: 'telegram',
  displayName: 'Telegram',
  aliases: ['tg'],
  supportsOneClickSetup: false,

  async connect(ctx: PlatformConnectContext): Promise<PlatformInstanceConfig | null> {
    // Guide onboarding (QR flow, token prompt, OAuth, etc.) and return a generic
    // instance config. Credentials live in `settings` and are saved with 0600 mode.
    const now = new Date().toISOString();
    return {
      instanceId: ctx.instanceId ?? 'telegram-main',
      platform: 'telegram',
      enabled: true,
      settings: { botToken: '...' },
      createdAt: now,
      updatedAt: now,
    };
  },

  createAdapter(
    instance: PlatformInstanceConfig,
    hooks?: PlatformAdapterHooks
  ): PlatformAdapter {
    // Validate `instance.settings` and return your PlatformAdapter.
    // Call `hooks?.onConnected?.({ instanceId, platform, botName, botId })` once ready.
    return createMyAdapter(/* ... */);
  },
};

See the Feishu / Lark reference implementation under packages/im/src/platforms/feishu/ (provider.ts and adapter.ts). Prefer Node 24+ built-ins (fetch, WebSocket, crypto) over third-party SDKs whenever practical.

3. Register the Provider ​

Add a single line in createDefaultPlatformRegistry() inside packages/im/src/registry.ts:

ts
registry.register(myPlatformProvider);

Once registered, iki connect <kind|alias>, iki gateway, ~/.iki/im-instances.json persistence, and all governance rules work automatically.

4. Verify End-to-End ​

Prefer a real end-to-end test driving a local mock platform server against a live iki gateway child process (see tests/integration/e2e/run_gateway_feishu_e2e.mjs):

bash
pnpm run test:e2e:gateway:faux
pnpm run test:e2e:gateway:live
pnpm run ci:quality

Released under AGPL-3.0-only.