К основному содержанию
команда CX Codex

_index · coco-research, email — слэш-команда для Claude Code: почта Outlook

Слэш-команда _index для Claude, которая читает, ищет и разбирает почту Outlook через подкоманды вроде unread, summary и triage.

MIT ★ 328 обновлён 2026-10-29

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/commands/_index.md
Открыть на GitHub

Что делает _index

Команда даёт доступ к почте Outlook прямо из Claude. Читает, ищет, раскладывает письма по папкам проекта. Сначала проверка версии — defaults read com.microsoft.Outlook IsRunningNewOutlook. Ноль или пусто означают Legacy Outlook, и дальше идёт AppleScript. Если вернулась 1, клиент новый: AppleScript в нём не работает, поэтому команда переходит на разбор MIME и HxStore.

Подкоманды: read <name>, unread, search <keywords>, today, this-week, thread <subject>, folders, summary, reply-draft <subject>, save <name/subject> to <folder>, triage и noise. Без аргумента срабатывает unread. save выгружает найденные письма в .txt в папку проекта. summary читает тела и собирает решения, задачи и встречи.

triage помечает прочитанным то, что подошло под правила из ~/.coco/email-noise-rules.yaml. Классификацию делает ~/.coco/email-triage.py, запускается он через python3. Работает это только в Legacy Outlook — в новом письма не пометить, AppleScript там не поддерживается.

Какие задачи решает

  • разобрать непрочитанное, не открывая Outlook
  • найти письмо по слову в теме или теле
  • собрать из почты решения и задачи за день
  • выгрузить переписку в папку проекта текстовыми файлами
  • отсеять рассылки по своим правилам

Примеры запросов агенту

  • Запусти /_index unread и сгруппируй письма по отправителям.
  • /_index summary — вытащи из сегодняшней почты решения и задачи.
  • Сохрани переписку по договору в проект: /_index save договор to docs/mail.

Как установить _index

Вручную: положить файлы

.claude/commands/_index.md

Вызов — /_index. Для всех проектов — ~/.claude/commands/

Вопросы о _index

Как установить _index в Claude Code?

Файл команды кладётся в проект по пути .claude/commands/_index.md. Дальше её зовут с подкомандой: /_index today, /_index unread.

Что делает _index?

Читает и ищет письма Outlook, показывает непрочитанное и переписку по теме, делает сводку дня, сохраняет письма в файлы и готовит черновик ответа.

Почему triage не помечает письма прочитанными?

Он работает только в Legacy Outlook. В новом клиенте AppleScript не поддерживается, поэтому пометить письмо прочитанным из команды нельзя.

Исходный текст

_index.md · MIT
---
description: "Read, search, and manage Outlook emails. Auto-detects Legacy Outlook (AppleScript) vs New Outlook (MIME/HxStore extraction). Subcommands: read, unread, search, today, thread, save, summary, reply-draft."
allowed-tools:
  - Bash
  - Read
  - Write
  - Edit
  - Glob
  - Grep
  - Agent
  - AskUserQuestion
---

# /email — Outlook Email Commands

You manage Outlook email access. Parse the user's argument to determine which subcommand to run.

## Preflight: Detect Outlook variant (REQUIRED — run first)

Outlook for Mac has two incompatible variants. Detect which one is running before doing anything:

```bash
defaults read com.microsoft.Outlook IsRunningNewOutlook 2>/dev/null || echo 0
```

- Output `0` or unset → **Legacy Outlook** → use the AppleScript templates below.
- Output `1` → **New Outlook** → AppleScript is NOT supported (it will silently fail or error). Use **New Outlook (MIME) Mode** below instead. Do NOT attempt AppleScript.

If an AppleScript call errors with "Microsoft Outlook got an error" or the app is unscriptable, treat it as New Outlook and switch to MIME mode rather than retrying.

## CRITICAL: AppleScript Sender Pattern

The `sender` property in Legacy Outlook returns a **record**, not an object. Always access it like this:
```applescript
set s to sender of msg
set sName to name of s
set sAddr to address of s
```
NEVER use `name of sender of msg` directly — it will error.

## Subcommands

- **`read <name>`** — Show latest emails from a specific person
- **`unread`** — Show unread emails (count + top 20)
- **`search <keywords>`** — Search emails by subject/body keywords
- **`today`** — Show all emails received today
- **`this-week`** — Show emails from this week grouped by day
- **`thread <subject>`** — Show full email thread by subject
- **`save <name/subject> to <folder>`** — Save matching emails to a project folder
- **`summary`** — AI summary of today's/unread emails — key decisions, action items
- **`reply-draft <subject>`** — Draft a reply to a specific email
- **`folders`** — List all mail folders with message counts
- **`triage`** — Scan unread, auto-mark known noise (per rules file), show the rest
- **`noise`** — Show/add noise rules (`noise add auto|propose <field>=<value> [reason]`)

If no subcommand given, default to `unread`.

---

## AppleScript Templates

### Base: Read messages with sender info
```applescript
tell application "Microsoft Outlook"
    set allMsgs to messages 1 thru {LIMIT} of {FOLDER}
    repeat with msg in allMsgs
        try
            set s to sender of msg
            set sName to name of s
            set sAddr to address of s
            set subj to subject of msg
            set msgDate to time received of msg
            set isRead to is read of msg
            -- filter logic here
        end try
    end repeat
end tell
```

### For reading body content
```applescript
set bodyText to plain text content of msg
```

### For checking recipients (sent items)
```applescript
set recipList to to recipients of msg
repeat with r in recipList
    set recipAddr to address of r
end repeat
```

### Folder references
- Inbox: `inbox` or `mail folder "Inbox" of default account`
- Sent: `mail folder "Sent Items" of default account`
- Archive: `mail folder "Archive" of default account`
- Deleted: `mail folder "Deleted Items" of default account`
- All folders: `mail folders of default account`

---

## Subcommand Details

### `read <name>`
1. Search inbox (first 1000 messages) for sender name/address containing `<name>`
2. Show up to 10 most recent matches as a table: Status | Date | From | Subject
3. Ask if user wants to read the full body of any specific email
4. If user says yes, fetch `plain text content of msg` and display

### `unread`
1. Count unread: iterate messages and count where `is read of msg` is false
2. Show first 20 unread messages as table: Date | From | Subject
3. Group by sender if many from same person
4. Offer to mark as read or read full content

### `search <keywords>`
1. Search inbox (first 2000 messages) — check `subject of msg` for keyword match
2. Also optionally search body (`plain text content`) for deeper matches (warn: slower)
3. Show results as table: Date | From | Subject
4. Limit to 20 results

### `today`
1. Get today's date
2. Iterate inbox messages, stop when `time received of msg` is before today
3. Show all today's emails as table grouped by hour
4. Include read/unread status

### `this-week`
1. Get date 7 days ago
2. Iterate inbox, collect all messages from this week
3. Group by day, show count per day + subjects
4. Limit to 50 most recent

### `thread <subject>`
1. Search inbox + sent items for messages where subject contains `<subject>`
2. Sort by date
3. Show full thread chronologically with sender and body excerpts

### `save <query> to <folder>`
1. Search for emails matching `<query>` (by sender name or subject keyword)
2. For each match, save to the specified project folder as `.txt` files:
   ```
   Subject: ...
   From: ...
   Date: ...
   ============================================================

   [body content]
   ```
3. Report how many saved
4. This triggers the cron's file detection → auto-update pipeline

### `summary`
1. Get today's emails (or unread if specified)
2. Read the body of each
3. Generate an AI summary:
   - Key decisions made
   - Action items for you
   - Meetings scheduled
   - FYIs / newsletters (skip detail)
4. Group by project relevance if possible

### `reply-draft <subject>`
1. Find the email by subject
2. Read its full content
3. Ask user what they want to say in reply
4. Draft a professional reply
5. Show the draft — user can copy/paste into Outlook

### `folders`
1. List all mail folders with message counts
2. Show as table: Folder | Messages | Unread

### `triage` (Legacy Outlook only — needs mark-as-read)
Mechanically de-noises the inbox using the **curated rules file**, never your own judgment.

1. **Dump** the first 200 inbox messages as TSV (`idx \t U|R \t sender_addr \t subject`):
   ```applescript
   tell application "Microsoft Outlook"
       set out to {}
       set i to 0
       set msgs to messages 1 thru 200 of inbox
       repeat with m in msgs
           try
               set i to i + 1
               set s to sender of m
               set flag to "R"
               if (is read of m) is false then set flag to "U"
               set end of out to ((i as text) & "	" & flag & "	" & (address of s) & "	" & (subject of m))
           end try
       end repeat
       set AppleScript's text item delimiters to linefeed
       set t to out as text
       set AppleScript's text item delimiters to ""
       return t
   end tell
   ```
2. **Classify** by piping that dump into the shared classifier (deterministic, rule-driven):
   ```bash
   <dump> | python3 ~/.coco/email-triage.py
   ```
   It emits `AUTO` / `PROPOSE` / `PROTECT` lines + a `#SUMMARY`. See `~/.coco/email-noise-rules.yaml`.
3. **Auto-mark** every `AUTO` line read. Mark by matching first UNREAD message whose `address of sender` + `subject` equal the line's (robust against index drift); do NOT trust the raw index across calls:
   ```applescript
   -- for each (addr, subj) to mark:
   repeat with m in (messages 1 thru 200 of inbox)
       try
           if (is read of m) is false and (address of sender of m) is "ADDR" and (subject of m) is "SUBJ" then
               set is read of m to true
               exit repeat
           end if
       end try
   end repeat
   ```
4. **Show** the `PROPOSE` lines as a table (Date | From | Subject | rule_id) — these are candidates, NOT marked. Ask which to mark, and offer to promote a rule to `auto` if trusted.
5. **Report**: N auto-marked (grouped by rule), N proposed, N protected, remaining unread count.

NEVER mark anything not emitted as `AUTO`. If a message matched a noise rule but is `PROTECT`, surface it explicitly — it stays unread.

### `noise` — manage the rules
- **`noise`** (no args): print the current rules grouped by tier (`auto` / `propose`) + `protect`, with id, match, reason.
- **`noise add <tier> <field>=<value> [reason: ...]`**: append a rule to `~/.coco/email-noise-rules.yaml`.
  - `<tier>` ∈ `auto` | `propose`. Default new rules to **propose** unless the user says auto.
  - `<field>` ∈ `sender_equals` | `sender_contains` | `sender_regex` | `subject_startswith` | `subject_contains`.
  - Generate a kebab-case `id`, set `added:` to today's date, write `reason:`.
  - After writing, re-read the file to confirm it parses (it's the source of truth).
- **`noise protect <field>=<value>`**: add a protect entry (sender or subject) — always-keep override.

**Rules file** = `~/.coco/email-noise-rules.yaml` (schema documented in-file). It is **manually curated and continuous**: start rules in `propose`, promote to `auto` only once trusted, delete anything wrong. The classifier `~/.coco/email-triage.py` only ever does what the file says — it cannot invent noise.

---

## New Outlook (MIME) Mode

New Outlook stores mail in a proprietary binary index (`HxStore.hxd`) with no AppleScript or local API. There is **no clean full-inbox read** — extract best-effort from the on-disk caches below, in priority order.

**Paths** (under `~/Library/Group Containers/UBF8T346G9.Office/Outlook/Outlook 15 Profiles/Main Profile/Files/S0/4/`):
- `MimeFiles/` — full RFC822 messages (cleanest, but **often empty** — not every install populates it).
- `Attachments/0/*.eml` — received/forwarded messages saved as clean RFC822 `.eml` (reliable when present).
- `HxStore.hxd` (one level up, in `Main Profile/`) — the real store; binary, no per-message delimiters. `strings` + grep yields sender/subject fragments only (last resort, messy).

**Approach** (covers `read`, `search`, `today`, `this-week`, `thread`, `summary`, `save`):
```bash
P="$HOME/Library/Group Containers/UBF8T346G9.Office/Outlook/Outlook 15 Profiles/Main Profile/Files/S0/4"
# Tiers 1+2: clean RFC822 from MimeFiles + .eml attachments, most-recent first.
# Use find (not a glob) so it is portable across bash/zsh and survives an empty MimeFiles dir.
{ find "$P/MimeFiles" -type f -print0 2>/dev/null; find "$P/Attachments/0" -maxdepth 1 -name '*.eml' -print0 2>/dev/null; } \
  | xargs -0 ls -t 2>/dev/null | head -200 | while IFS= read -r f; do
  subj=$(grep -a -m1 -i '^Subject:' "$f"); [ -z "$subj" ] && continue
  from=$(grep -a -m1 -i '^From:' "$f"); date=$(grep -a -m1 -i '^Date:' "$f")
  printf '%s\t%s\t%s\t%s\n' "$date" "$from" "$subj" "$f"
done
# Tier 3 (only if the above returns nothing): subject/sender awareness from the binary store
#   strings "$P/../../HxStore.hxd" | grep -aiE '^(Subject|From):' | head -50
```
- Filter by sender (`read <name>`), keyword (`search`), or date (`today`/`this-week`). Body/`summary`: parse the matched file. `save <query> to <folder>`: copy the matched file into the target folder.

**Limitations on New Outlook (state honestly — do not guess):**
- This is **partial, not the full inbox**: `MimeFiles/` is frequently empty, and `.eml` attachments only cover received/forwarded messages. For complete access, use Legacy Outlook or the Microsoft Graph API — say so rather than implying full coverage.
- `unread` count / read state, `folders`, mark-as-read, and sending a `reply-draft` need the app API — unavailable. For `reply-draft`, still draft text for copy/paste.
- `HxStore.hxd` is binary; never present its raw `strings` dump as if it were clean email — use it only for awareness.

---

## Performance Notes

- AppleScript iteration is O(n) — searching 7000+ messages is slow
- Default search depth: 500 messages for quick commands, 2000 for `search`
- Always stop early when enough results found (exit repeat)
- For `today` and `this-week`, stop when date is older than target (messages are date-sorted)
- Use `messages 1 thru N` not `every message` to avoid loading entire mailbox

## Error Handling

- If Outlook is not running: `tell application "Microsoft Outlook" to activate` then retry
- If sender access fails: fall back to subject-only display
- If body is empty: try `content of msg` as fallback
- Timeout: 120 seconds per AppleScript call

© coco-research · MIT · coco-research/coco

Похожие слэш-команды

Все слэш-команды по теме «Заметки, задачи и проекты» →

Сначала — _index от других авторов.

_index coco-research Команда _index маршрутизирует вызовы /team по четырёхслойной кросс-функциональной команде для разработки, тестов, документации и релизов. CX Codex +1 ★ 328звёзд репо Apple Mail mgcrea MCP-сервер для macOS подключает локальное приложение Apple Mail к ИИ-агентам. Позволяет искать письма, читать цепочки и работать с почтой без передачи паролей IMAP во внешнюю сеть. CX Codex +1 ★ 6звёзд репо apple-mail rbouschery Управляет Apple Mail на macOS через AppleScript: читает, ищет, отправляет и удаляет письма скриптами. Разбор входящих идёт без открытия почтового клиента. CX Codex +1 1 400установок email-pair Alireza Rezvani Плагин email-pair организует разбор почты в связке из двух скиллов: интервью для настройки базы знаний и регулярная сортировка входящих. Никогда не отправляет письма автоматически. ★ 30 251звёзд репо iCloud MCP MrGo2 MCP-сервер iCloud MCP подключает ассистента к сервисам Apple: почте, календарю, заметкам и напоминаниям. Помогает управлять личными данными прямо из чата с моделью. CX Codex +1 ★ 84звёзд репо outlook-email официальный OpenAI Плагин outlook-email для Codex и ChatGPT подключает агента к почте Outlook через настроенный коннектор Microsoft Outlook. Агент читает и разбирает письма напрямую из чата. CX Codex GP ChatGPT ★ 8 052звёзд репо outlook anasahmed07 Связывает Claude с классическим клиентом Outlook на Windows: письма, календарь, контакты, задачи и правила. Нужен Windows 10 или 11 и установленный Outlook desktop. ★ 43звёзд репо

Из того же набора82

Весь набор →
arch-index Создаёт проверяемую карту компонентов репозитория в .arch/index.json и ищет расхождения с кодом. Пригодится после рефакторинга или когда нужно понять, какие файлы реализуют компонент. CX Codex +1 ★ 328звёзд репо hyperframes-keyframes Скилл hyperframes-keyframes держит анимацию в композиции HyperFrames перематываемой: собирает кейфреймы для GSAP, CSS, Anime.js и WAAPI и проверяет кадры до рендера. CX Codex +1 ★ 328звёзд репо pmstudio-meeting-notes Скилл pmstudio-meeting-notes превращает транскрипты встреч в структурированные Markdown-заметки. Сверяет участников со справочником стейкхолдеров, фиксирует решения и отмечает влияние на PRD. CX Codex +1 ★ 328звёзд репо hyperframes-cli Скилл hyperframes-cli помогает вести проект HyperFrames от проверки композиции до предпросмотра и рендера. Пригодится и для поиска ошибок сборки или рендера. CX Codex +1 ★ 328звёзд репо brain:wiki Скилл brain:wiki для Claude Code ищет, создаёт и объединяет статьи о людях, системах и командах из распределённой базы знаний. Помогает получить сводку по сущности или найти информацию о решениях и связях. CX Codex +1 ★ 328звёзд репо hyperframes Точка входа для сборки видео, анимаций и моушн-графики в Claude: ведёт от идеи или брифа до готовой HTML-композиции HyperFrames. CX Codex +1 ★ 328звёзд репо code-verification Скилл code-verification запускает механическую проверку кода из семи категорий после правок ИИ. Находит ошибки TDZ, несовпадения импортов, утечки моков и антипаттерны React. CX Codex +1 ★ 328звёзд репо openai-agents Помогает проектировать агентов на OpenAI Agents SDK, настраивать передачу контекста и избегать типичных сбоев библиотек. CX Codex +1 ★ 328звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой