Agentskillz Logo

larksuite/cli / lark-event

lark-event

Установки
422,235
Автор
larksuite/cli
Источник
github.com/larksuite/cli

Скилл для подписки на события Lark/Feishu в реальном времени: сообщения, реакции, изменения в чатах, статусы согласований, задачи, встречи, заметки и другие события. Позволяет запускать длительные подписчики с потоковой выдачей NDJSON, фильтрацией через jq и контролем времени или количества событий. Удобен для создания ботов и обработки вебхуков.

Установить скилл

npx skills add https://github.com/larksuite/cli --skill lark-event

Аудит безопасности

Gen Agent Trust Hub

pass

The skill provides instructions for consuming real-time events from Lark/Feishu using a local CLI tool. While the logic is functional and safe, it introduces an inherent attack surface for indirect prompt injection by ingesting untrusted chat message content into the agent's context.

Audited: 5/27/2026, 3:07:00 AM

Socket

pass

No alerts

Audited: 5/27/2026, 3:07:16 AM

Snyk

warn

Risk: MEDIUM · 1 issue

Audited: 5/27/2026, 3:05:50 AM

ZeroLeaks

pass

Score: 93/100 · 2 sections analyzed

Audited: 4/16/2026, 2:52:28 AM

Промпт скилла

Lark Events

Prerequisite: Read ../lark-shared/SKILL.md first for authentication, --as user/bot switching, Permission denied handling, and safety rules.

Core commands

CommandPurpose
lark-cli event list [--json]List all subscribable EventKeys
lark-cli event schema <EventKey> [--json]Show an EventKey's params and output schema
lark-cli event consume <EventKey> [flags]Blocking consume; events → stdout NDJSON
lark-cli event status [--json] [--fail-on-orphan]Inspect the local bus daemon status
lark-cli event stop [--all] [--force]Stop the bus daemon

Common flags

FlagDescription
--param key=value / -pBusiness params (repeatable; comma-separated for multi-value). Unknown keys fail with valid names listed inline
--jq <expr>jq expression to filter / transform each event; empty output skips the event
--max-events NExit after N events. Default 0 = unlimited
--timeout DExit after duration D (e.g. 30s, 2m). Default 0 = no timeout. Whichever of --max-events / --timeout fires first wins
--output-dir <dir>Write each event as a file (relative paths only; prevents traversal)
--quietSuppress ready/exit markers and per-event stderr diagnostics, including drop warnings. This can hide event loss. AI should not use this — it removes readiness and integrity signals
--as user|bot|autoIdentity for the session (see lark-shared)

Examples

# Default: stream every event for the key (no filter, no projection)
lark-cli event consume im.message.receive_v1 --as bot

# List every EventKey of one domain (the authoritative, always-current catalog)
lark-cli event list --domain vc --json

# Grab one sample event to inspect payload shape
lark-cli event consume im.message.receive_v1 --max-events 1 --timeout 30s --as bot

# Run for 10 minutes then auto-exit
lark-cli event consume im.message.receive_v1 --timeout 10m --as bot

# Consume multiple EventKeys concurrently (one shape per process, no dispatcher)
lark-cli event consume im.message.receive_v1          --as bot > receive.ndjson &
lark-cli event consume im.message.reaction.created_v1 --as bot > reaction.ndjson &
wait

Call flow

  1. lark-cli event list --json → pick a legal key. --domain <d> narrows to one domain; the domains are application, approval, board, card, im, minutes, task, vc. An unknown domain fails with the valid set listed in the hint.
  2. lark-cli event schema <key> --json → read resolved_output_schema + jq_root_path to determine field paths
  3. lark-cli event consume <key> [--jq '<expr>'] → consume

Subprocess contract

Ready marker

event consume's stderr emits a fixed line [event] ready event_key=<key>. Parent processes should block on stderr until this line appears, then start reading stdout. Do not fall back to sleep.

stdin EOF = graceful exit

event consume treats stdin close as a shutdown signal (wired for AI subprocess callers). Bounded runs are exempt: when --max-events or --timeout is set (> 0), stdin EOF is ignored and the run exits only via its own bound, timeout, or SIGTERM. For unbounded runs, < /dev/null / nohup / systemd's default StandardInput=null will cause an immediate graceful exit (stderr reason: signal). To keep an unbounded run alive:

  • Feed stdin a source that never EOFs: < <(tail -f /dev/null)
  • Or run bounded: --max-events N / --timeout D

Exit codes & reason

On exit, the last stderr line is [event] exited — received N event(s) in Xs (reason: ...).

exit codereasonTrigger
0reason: limit--max-events reached
0reason: timeout--timeout reached
0reason: signalCtrl+C / SIGTERM / stdin EOF (stdin EOF applies to unbounded runs only)
1JSON error envelope on stderrLark API business failure during pre-consume setup (for example subscription create/delete)
2JSON error envelope on stderr (no exited line)Validation failure (unknown EventKey, bad --param / --jq, another bus already connected)
3JSON error envelope on stderrAuth failure (missing token, missing scopes)
4 / 5JSON error envelope on stderrNetwork / internal failure (bus startup, handshake, file I/O)

Startup and runtime failures emit a structured JSON envelope on stderr: {"ok":false,"error":{"type","subtype","param","message","hint",...}} (the envelope may also carry top-level identity / _notice siblings). Parse error.type / error.subtype to branch (e.g. missing_scope carries a missing_scopes list), error.param to find the offending flag, and error.hint for the recovery action — do not regex-match message text.

Orchestrators should treat reason: limit/timeout/signal (all exit 0) as "business completion" and non-zero as "failure".

Never kill -9

Avoid kill -9 on consume processes for EventKeys whose PreConsume registers a server-side subscription and unsubscribes on exit (minutes, vc, board keys): kill -9 skips the OAPI unsubscribe and leaks the server-side subscription (symptoms: "subscription already exists" on restart, duplicate event delivery). Keys whose subscription is a durable relation with no cleanup (task, approval keys) do not leak this way, but SIGTERM or closing stdin remains the right shutdown for every key.

One consume, one EventKey (multi-key = multi-shell)

The command takes exactly one positional argument; k1,k2 and wildcards are unsupported. Listening to N keys means N subprocesses — this is intentional:

  • One shape per process stdout; no dispatcher logic required in the AI
  • Fault isolation (one key failing doesn't affect others)
  • Independent --as / --jq / --max-events / --timeout per key

All N consumers share a single bus daemon (UDS local IPC), so the overhead is small

Writing jq via schema

event schema <key> --json is the source of truth for writing --jq. Four things to look at:

(1) Where fields start — see jq_root_path

  • Value "." → fields are at the top level, write .chat_id
  • Value ".event" → fields are inside a V2 envelope, write .event.chat_id

(2) Field list and types — see resolved_output_schema.properties.<name>

Each field carries type / description, and some also have format. Snippet (from event schema im.message.receive_v1 --json):

{
  "chat_id":     {"type":"string", "format":"chat_id",      "description":"Chat ID, prefixed with oc_"},
  "sender_id":   {"type":"string", "format":"open_id",      "description":"Sender open_id, prefixed with ou_"},
  "create_time": {"type":"string", "format":"timestamp_ms", "description":"Send time as ms-epoch string"}
}

(3) Field semantics — see the format tag

Lark-defined semantic tags (not JSON Schema's standard format). Common values: open_id / chat_id / message_id / timestamp_ms / email. Purpose: distinguish "same string type, different meanings" fields so you can reverse-lookup via API or convert formats.

(4) Decoded state — read the field's description

event consume runs Process hooks that may pre-decode some payload fields (flattening V2 envelopes, rendering .content to plain text, etc.) — behavior differs from raw OAPI. Always read the field's description before writing jq, especially for generic field names like content / data / body / payload.

Why it matters: blindly applying fromjson to an already-decoded text field makes jq error on every event and silently drop it — the consumer looks alive but emits nothing, with only a single WARN line buried on stderr. (This is the general behavior: any jq runtime error skips the event with a one-line WARN; the loop does not abort.)

Don't shortcut the schema: when projecting event schema --json with jq, do not strip .description from properties — that's the field that tells you whether a field is already decoded. Dump the full property objects, not just keys.


Aside: --param's valid parameters also live in the schema — the params section lists name / type / required / enum / default / description; section missing = this key accepts no --param.

Topic index

TopicReferenceCoverage
Applicationreferences/lark-event-application.mdCatalog of Application EventKeys, including application.bot.menu_v6 for custom bot menu push events + flattened event_key / operator fields + jq recipe
Approvalreferences/lark-event-approval.mdCatalog of 2 Approval EventKeys (approval.instance.status_changed_v4, approval.task.status_changed_v4) + optional/multi subscription_type pre-registration + user-auth subscription lifecycle + flat output field reference
IMreferences/lark-event-im.mdCatalog of 12 IM EventKeys + shape notes (flat vs V2 envelope) + im.message.receive_v1 field gotchas (sender_id is open_id only; .content is plain text except for interactive cards) + common jq recipes (filter by chat_type / message_type / sender); for card.action.trigger see also ../lark-im/references/lark-im-card-action-reply.md
Taskreferences/lark-event-task.mdCatalog of 1 Task EventKey (task.task.update_user_access_v2) + Native V2 envelope shape + task commit types + user/bot subscription notes
VCreferences/lark-event-vc.mdCatalog of 7 VC EventKeys (meeting lifecycle participant_meeting_started/joined/ended_v1, vc.note.generated_v1, recording recording_started/transcript_generated/ended_v1) + field reference + source type semantics; the live list is always lark-cli event list --domain vc --json
Minutesreferences/lark-event-minutes.mdCatalog of 1 Minutes EventKey (minutes.minute.generated_v1) + field reference + source type semantics (meeting only)
Whiteboardreferences/lark-event-whiteboard.mdCatalog of 1 Board EventKey (board.whiteboard.updated_v1) + per-whiteboard subscription model (requires -p whiteboard_id=<token>) + payload field reference (whiteboard_id / operator_ids triple-id)

Все файлы скилла

Другие скиллы автора

lark-shared

428,016 установок

larksuite/cli

Базовый скилл для работы с lark-cli: управление аутентификацией, выбором идентичности пользователя или бота, настройкой доменов и прав доступа. Обеспечивает корректную обработку ответов, безопасность операций и генерацию QR-кодов для авторизации.

lark-im

427,083 установок

larksuite/cli

Навык для работы с корпоративным мессенджером Lark: отправка и поиск сообщений, управление чатами и группами, работа с вложениями, реакциями, закладками и интерактивными карточками. Поддерживает операции от имени пользователя или бота, включая массовые операции и пагинацию.

lark-wiki

426,048 установок

larksuite/cli

Скилл для работы с корпоративной базой знаний: создаёт и удаляет пространства, управляет их структурой и участниками, перемещает и копирует документы. Помогает быстро находить нужные материалы по ссылке или названию и грамотно организовывать знания.

lark-whiteboard

425,116 установок

larksuite/cli

Скилл для работы с досками в Lark (Feishu): просмотр и экспорт содержимого в изображение, SVG или исходный код, а также создание и редактирование досок по описанию или готовым диаграммам Mermaid, PlantUML и SVG. Упрощает визуализацию и обновление досок прямо из агента.

lark-calendar

423,989 установок

larksuite/cli

Скилл для работы с календарём Lark: просмотр и поиск событий, создание и изменение встреч, управление участниками и переговорными комнатами. Помогает проверять занятость, подбирать удобное время для встречи и бронировать переговорки. Пригодится для планирования расписания и организации совещаний.

lark-mail

422,688 установок

larksuite/cli

Скилл для работы с почтой Lark (飞书): позволяет просматривать, искать и читать письма, создавать черновики, отправлять, отвечать и пересылать сообщения, управлять папками, метками и правилами приёма почты. Включает строгие меры безопасности: содержимое писем считается недоверенным, а отправка и необратимые операции выполняются только после явного подтверждения пользователя.

lark-minutes

422,579 установок

larksuite/cli

Этот навык служит совместимым переходником для старых названий: он перенаправляет все запросы на навык lark-meeting, который выполняет основную работу. Сам по себе он не обрабатывает задачи, а только обеспечивает корректную маршрутизацию.

lark-vc

422,474 установок

larksuite/cli

Скилл lark-vc обеспечивает совместимость со старым названием и перенаправляет все запросы на навык lark-meeting. Он не обрабатывает задачи напрямую, а служит переходным мостом для корректной маршрутизации. Полезен для поддержки старых конфигураций и бе

lark-workflow-meeting-summary

421,487 установок

larksuite/cli

Этот навык собирает заметки с совещаний за заданный период и формирует структурированный отчёт. Он автоматически запрашивает список встреч, получает тексты заметок и стенограмм, обрабатывает случаи отсутствия доступа, а затем выдаёт итог за день или неделю. При необходимости готовый отчёт можно сохранить прямо в облачный документ.

lark-workflow-standup-report

420,796 установок

larksuite/cli

Формирует сводку по расписанию и незавершённым задачам на указанную дату: подтягивает события календаря и список дел, проверяет пересечения и выдаёт итоговый отчёт. Помогает быстро узнать планы на день, неделю или подготовить утреннюю сводку.

lark-openapi-explorer

420,575 установок

larksuite/cli

Этот скилл помогает находить и вызывать原生 API-интерфейсы Lark/Feishu, когда стандартные команды CLI не подходят. Он автоматически просматривает официальную документацию, извлекает спецификации нужных методов и формирует готовые запросы через `lark-cli`. Полезен для доступа к недокументированным или редко используемым функциям платформы.

lark-skill-maker

420,341 установок

larksuite/cli

Этот навык помогает создавать собственные скиллы для lark-cli, превращая операции с API Lark в переиспользуемые команды. Он позволяет исследовать доступные API, проверять параметры и генерировать шаблоны SKILL.md с описанием команд, разрешений и логики их выполнения. Упрощает автоматизацию рутинных задач с Lark, упаковывая их в понятные для ИИ инструкции.

lark-approval

395,582 установок

larksuite/cli

Управление заявками на утверждение в Lark: поиск и просмотр ожидающих и завершённых задач, инициирование новых заявок, а также выполнение действий — одобрение, отклонение, перенаправление, отзыв, напоминание и добавление подписей.

lark-attendance

373,448 установок

larksuite/cli

Помогает запрашивать свои отметки о посещаемости в Lark (Feishu) через командную строку. Автоматически подставляет обязательные параметры, поэтому достаточно указать только нужные данные. Требует предварительной настройки доступа.

lark-okr

359,391 установок

larksuite/cli

Скилл для управления OKR в Lark: просмотр и редактирование циклов, целей, ключевых результатов, связей выравнивания, количественных показателей и записей о прогрессе. Поддерживает массовое создание, изменение весов и порядка, а также корректно различает оценку (score) и фактический прогресс.

lark-vc-agent

310,424 установок

larksuite/cli

Совместимый навык для работы с видео-конференциями Lark. Не обрабатывает запросы сам, а перенаправляет их на основной навык lark-meeting. Нужен, чтобы старые вызовы по имени lark-vc-agent продолжали работать.