From 8bdd871887d73234c3a3ed9ca2e1e3751cb5f7a9 Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Sun, 15 Nov 2026 15:14:52 -0600 Subject: [PATCH 1/2] chore: pre-install the Slack skills for coding agents Adds the 9 skills from slackapi/slack-skills-plugin with npx skills add --copy, for Claude Code (.claude/skills) and agents that read .agents/skills, with a skills-lock.json. Marks them generated so GitHub collapses them in diffs, and keeps them out of the formatter so they stay identical to the plugin. --- .agents/skills/block-kit/SKILL.md | 284 ++++++++++ .../references/agent-progress-design.md | 162 ++++++ .../block-kit/references/common-patterns.md | 485 ++++++++++++++++++ .../references/data-display-design.md | 111 ++++ .../block-kit/references/design-principles.md | 195 +++++++ .../block-kit/references/home-tab-design.md | 88 ++++ .../block-kit/references/human-in-the-loop.md | 223 ++++++++ .../block-kit/references/modal-design.md | 150 ++++++ .agents/skills/create-slack-app/SKILL.md | 274 ++++++++++ .agents/skills/deploy-slack-app/SKILL.md | 200 ++++++++ .../references/deploy-heroku.sh | 186 +++++++ .../references/deploy-railway.sh | 130 +++++ .../deploy-slack-app/references/heroku.md | 129 +++++ .../deploy-slack-app/references/railway.md | 96 ++++ .agents/skills/slack-api/SKILL.md | 207 ++++++++ .agents/skills/slack-cli/SKILL.md | 253 +++++++++ .agents/skills/slack-docs/SKILL.md | 145 ++++++ .agents/skills/slack-messaging/SKILL.md | 84 +++ .agents/skills/slack-search/SKILL.md | 123 +++++ .agents/skills/test-slack-app/SKILL.md | 111 ++++ .gitattributes | 21 + skills-lock.json | 68 +++ 22 files changed, 3725 insertions(+) create mode 100644 .agents/skills/block-kit/SKILL.md create mode 100644 .agents/skills/block-kit/references/agent-progress-design.md create mode 100644 .agents/skills/block-kit/references/common-patterns.md create mode 100644 .agents/skills/block-kit/references/data-display-design.md create mode 100644 .agents/skills/block-kit/references/design-principles.md create mode 100644 .agents/skills/block-kit/references/home-tab-design.md create mode 100644 .agents/skills/block-kit/references/human-in-the-loop.md create mode 100644 .agents/skills/block-kit/references/modal-design.md create mode 100644 .agents/skills/create-slack-app/SKILL.md create mode 100644 .agents/skills/deploy-slack-app/SKILL.md create mode 100755 .agents/skills/deploy-slack-app/references/deploy-heroku.sh create mode 100755 .agents/skills/deploy-slack-app/references/deploy-railway.sh create mode 100644 .agents/skills/deploy-slack-app/references/heroku.md create mode 100644 .agents/skills/deploy-slack-app/references/railway.md create mode 100644 .agents/skills/slack-api/SKILL.md create mode 100644 .agents/skills/slack-cli/SKILL.md create mode 100644 .agents/skills/slack-docs/SKILL.md create mode 100644 .agents/skills/slack-messaging/SKILL.md create mode 100644 .agents/skills/slack-search/SKILL.md create mode 100644 .agents/skills/test-slack-app/SKILL.md create mode 100644 .gitattributes create mode 100644 skills-lock.json diff --git a/.agents/skills/block-kit/SKILL.md b/.agents/skills/block-kit/SKILL.md new file mode 100644 index 0000000..6696d55 --- /dev/null +++ b/.agents/skills/block-kit/SKILL.md @@ -0,0 +1,284 @@ +--- +name: block-kit +description: 'Use when a developer wants to build or validate Block Kit layouts for Slack messages, modals, or Home tabs: message layouts, modals/forms/dialogs, Home tab interfaces, interactive buttons or menus, or modifying existing Block Kit JSON. Also trigger on any Slack UI component (sections, actions, inputs, headers, alerts, tables, carousels), the words "blocks" or "Block Kit Builder", a request to preview rendered blocks, or pasted JSON like "type": "section". Validates via the blocks.validate API method.' +argument-hint: "[message | modal | home-tab]" +--- + +# Block Kit + +Help the developer build a rich Block Kit layout. If `$0` is exactly `message`, `modal`, or `home-tab`, treat it as the target surface. Otherwise (including if it's empty or any other value), ignore it and determine the surface in Step 1. + +This skill walks through surface selection, layout planning, JSON generation, and validation. Block types, elements, and fields come from the live docs (see **Source of Truth** below) — discover them and read each component's schema there, never from memory. + +> **Common Block Kit mistakes (and why):** A few errors recur often enough to flag up front. Most others are caught by `blocks.validate` in Step 5, so lean on validation rather than memorizing rules. +> +> - **`"type": "text"` is not a thing.** Text is a composition object: `{ "type": "plain_text", "text": "..." }` or `{ "type": "mrkdwn", "text": "..." }`. +> - **`markdown` is a _block_ type, not a text type.** A `markdown` block holds standard markdown; text objects inside other blocks use `mrkdwn` (see **mrkdwn vs. the `markdown` block** in Step 4). Slack's `mrkdwn` is `*bold*` / `_italic_` / `~strike~`, not `**bold**`. +> - **Messages need a top-level `text` fallback.** `blocks.validate` won't flag a missing one, but notifications and screen readers display it instead of the blocks — so summarize what the layout conveys rather than leaving it empty. + +--- + +## Source of Truth: the Live Docs + +Every block, element, and composition object is documented on `docs.slack.dev`. Append `.md` to any reference URL to fetch it as markdown with WebFetch (no auth required). + +- **Master index**: the authoritative list of every block, block element, and composition object, each linking to its own page: `https://docs.slack.dev/reference/block-kit.md`. WebFetch it to confirm a type exists and to get the link to its page. +- **Per-component pages** carry the full field schema (a fields table with required/optional flags and constraints, plus JSON examples): + - Blocks: `https://docs.slack.dev/reference/block-kit/blocks/-block.md` + - Block elements: `https://docs.slack.dev/reference/block-kit/block-elements/-element.md` + - Composition objects: `https://docs.slack.dev/reference/block-kit/composition-objects/.md` +- **The slug is not always the type name.** For example `datepicker` maps to `date-picker-element.md`, and every `*_select` menu (`static_select`, `users_select`, `multi_channels_select`, and so on) is documented on `select-menu-element.md`. When unsure of a slug, follow the link from the master index rather than building the URL by hand. +- **Surface payload structure** lives in the surface guides: messages at `https://docs.slack.dev/messaging/formatting-message-text.md`, modals at `https://docs.slack.dev/surfaces/modals.md`, and Home tabs at `https://docs.slack.dev/surfaces/app-home.md`. + +Never use a block type, element, or field you have not seen on a live page. + +--- + +## Fast Path (for clear, specific requests) + +If the developer's request is specific enough to determine both the target surface and the desired layout, collapse Steps 1-4 into a single pass: + +1. Determine the surface from `$0` or context +2. Fetch only the doc pages for the blocks and elements mentioned +3. Generate the JSON directly +4. Proceed to Step 5 (validation) + +**Fast-path indicators** (skip the full workflow): + +- Developer provides existing JSON to modify → use Modification Mode instead +- Developer names specific block types: "add an actions block with two buttons" +- Developer describes a well-known pattern: "approval message", "feedback form", "settings modal" +- Developer provides a complete description in one message with enough detail to build + +**Full-workflow indicators** (use Steps 1-7): + +- Vague requests: "make something cool", "build a dashboard" +- Exploratory: "what can Block Kit do?", "show me my options" +- Complex layouts: 10+ blocks, nested modals, conditional logic +- Developer asks for help deciding what to build + +--- + +## Modification Mode + +If the developer provides existing Block Kit JSON (pasted inline, in a file, or referenced from code), enter Modification Mode instead of the full creation workflow: + +1. **Parse the existing structure:** + - List each block by index, type, and a short description of its content + - Infer the surface: `"type": "modal"` = modal, `"type": "home"` = home tab, bare `blocks` array = message + +2. **Ask what changes they want:** + - Add blocks (where in the sequence?) + - Remove blocks (which ones?) + - Modify blocks (which block, what change?) + - Reorder blocks + +3. **Apply changes while preserving:** + - All existing `block_id` values (these are referenced in app interaction handlers) + - All existing `action_id` values (these map to event listeners) + - Existing styles, text content, and structure for unchanged blocks + +4. **Validate the modified JSON**: proceed to Step 5 (validation) + +**Detection:** If the developer's message contains a JSON array starting with `[{"type":` or a view object with `"blocks":`, enter Modification Mode automatically. If they say "edit", "update", "modify", or "change" in reference to existing blocks, ask them to provide the current JSON. + +--- + +## Step 1: Determine the Target Surface + +If `$0` is provided and matches one of `message`, `modal`, or `home-tab`, use it directly. + +Otherwise, ask the developer using AskUserQuestion: + +- **Message**: Conversational content posted to a channel or DM. Max 50 blocks. +- **Modal**: A dialog or form opened by a user action. Max 100 blocks. +- **Home tab**: A persistent, per-user dashboard in the App Home. Max 100 blocks. + +Once the surface is determined, use the correct payload structure for it: + +- **Message**: a `{ "text": "Fallback text", "blocks": [...] }` object posted via `chat.postMessage` (and friends). The `text` field is the notification/accessibility fallback. For message text formatting (mrkdwn, mentions, dates), see `https://docs.slack.dev/messaging/formatting-message-text.md`. +- **Modal**: a view object (`{ "type": "modal", "title": ..., "blocks": [...] }`). For the full view object structure, lifecycle, and the rule that `submit` is required when the view contains any `input` block, see `https://docs.slack.dev/surfaces/modals.md`. +- **Home tab**: a view object (`{ "type": "home", "blocks": [...] }`) published via `views.publish`. For structure and behavior, see `https://docs.slack.dev/surfaces/app-home.md`. + +--- + +## Step 2: Understand What to Build + +Ask the developer to describe what they want their layout to look like or accomplish. + +If they need inspiration, suggest examples — several map directly onto a ready-made template in `references/common-patterns.md` (named in parentheses), which you can start from in Step 3: + +- "A feedback form with a text input and a category selector" (Simple Form Modal) +- "A deploy-failure notification with a description and next-step buttons" (Notification Alert), or "an approval request with Approve/Reject buttons" (Approval Message) +- "A dashboard home tab with a welcome header, key metrics in fields, and quick-action buttons" (Dashboard Home Tab) +- "A settings modal with dropdowns, checkboxes, and a time picker" (Settings Modal with Multiple Input Types) +- "A table of sprint tasks with status and points" (Data Table) +- "A deploy summary with bold text, a link, and a bullet list" (Rich Text Section) +- "A row-level '⋯' menu for edit/duplicate/delete actions" (Row Actions with Overflow Menu) +- "A product card with an image, price, and Add to Cart button" (Card Preview) + +Get enough detail to plan the layout before generating any JSON. + +--- + +## Step 3: Plan the Block Layout + +Based on the developer's description: + +1. **Fetch only what you need** from the live docs: + - WebFetch the master index (`https://docs.slack.dev/reference/block-kit.md`) to confirm the block and element types you plan to use exist and to grab links to their pages. + - Consult `references/design-principles.md` for design appropriateness — which block fits the shape of the content (table vs. stacked sections, card vs. loose blocks), emphasis, reading order, and accessibility. It is guidance on building layouts that read well, not on validity. Depending on the layout, also consult: + - `references/modal-design.md` for modals and forms: titles and submit labels, input labels and hints, multi-step flows, validation errors, and loading or success states. + - `references/home-tab-design.md` for Home tabs: what goes at the top, empty and first-run states, keeping the view current, different views per role, and review surfaces for agents. + - `references/data-display-design.md` for numbers and records: choosing between `section` fields, `table`, `data_table`, and `data_visualization` charts, and presenting each clearly. + - `references/agent-progress-design.md` for showing an agent's work with `plan` and `task_card` blocks or streamed task updates. + - `references/human-in-the-loop.md` for approval gates, approving several proposed actions in one message, clarifying choices, and edit-before-send. + - Check `references/common-patterns.md` if the request matches a common pattern; start from the template instead of building from scratch. + - Defer reading individual component pages until Step 4, when you build each block's fields. +2. Propose a numbered block outline. For example: + + ```text + 1. header: "Weekly Report" + 2. section: Summary text with a datepicker accessory + 3. divider + 4. section: Status fields (Name, Role, Team) + 5. actions: "Approve Report" button (primary) and "Reject" button (unstyled) + ``` + +3. Present the outline to the developer and ask for approval or changes before generating JSON. + +**Surface constraints to check:** + +- Block count limit: 50 for messages, 100 for modals/home tabs +- Modal-specific: if using `input` blocks, the modal payload must include a `submit` field +- Table: only one `table` block per message +- Charts: at most two `data_visualization` blocks per message +- Alert: the `alert` block is available only in modals. In messages, state severity in words in a `header` or `section`. +- Surface compatibility (whether a block is valid on the chosen surface) and element compatibility (whether an element is allowed inside a given block) are not always spelled out on a component's doc page. Check `references/design-principles.md`'s surface and limits table for these. **`blocks.validate` in Step 5 does not enforce them** — it checks block and element shape only, and will return `ok: true` for a block on the wrong surface or over a count limit. Don't treat a pass there as confirmation of surface or count compliance. + +--- + +## Step 4: Generate the Block Kit JSON + +Once the layout is approved, build each block from its live doc page, fetching each page's fields table (required vs optional, constraints) and JSON example with WebFetch. The URL patterns are in **Source of Truth** above; the one slug to remember is that every `*_select` menu (`static_select`, `users_select`, `multi_channels_select`, …) lives on `select-menu-element.md`. Fetch pages as you need them and reuse what you have already fetched — don't re-fetch the same page for every block of the same type. Then build the payload block-by-block and wrap it in the surface structure from Step 1. + +**Guidelines:** + +- Use descriptive `action_id` values (e.g., `"approve_report_btn"` not `"action_1"`) — they identify the element in your interaction handlers +- Include `block_id` values where the developer will need them for interaction handling +- For modals, include `title`, `submit`, `close`, and `callback_id`; for home tabs, the `type: "home"` wrapper +- Use `mrkdwn` text for rich formatting, `plain_text` where required (headers, labels, modal title) + +**mrkdwn vs. the `markdown` block:** `section` and `context` blocks format text with Slack's `mrkdwn` (`*bold*`, not `**bold**`). The separate `markdown` block (messages only) renders standard markdown and is for AI/LLM-generated or long-form content that is already in standard markdown. `references/design-principles.md`, **Text: rich_text, mrkdwn, and the markdown block**, explains when to use each, including `rich_text` for formatted text you build in code. + +**Accessibility** is easy to skip and hard to retrofit, so build it in now. Apply `references/design-principles.md`, **Accessibility and fallback**, as you write each block: it covers the `text` fallback, `alt_text`, color and emoji, button labels, and text equivalents for tables and charts. + +Present the complete payload to the developer in the Step 1 surface structure. + +--- + +## Step 5: Validate + +**Always validate.** `blocks.validate` is a public Web API method, so no auth token is required. + +The authoritative reference for this method (its parameters, auth requirements, and response/error shape) is the live doc. WebFetch it before relying on any detail here: `https://docs.slack.dev/reference/methods/blocks.validate.md`. It documents the accepted parameters (`blocks` for a message's blocks array, `view` for a modal/home-tab view, `message` for a full message payload; send exactly one) and the response shape. + +### 5a. Build the validation request + +Prefer the Slack CLI when it's available, since it reuses the slack-cli skill's CLI detection and needs no token wrangling. If the CLI isn't installed, fall back to curl. Both call the same public method and return the same response, so Step 5b applies either way. + +**Path A: Slack CLI (preferred).** + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public CLI is installed and resolve its command (`SLACK_CMD`). Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. + +If the CLI is available, use the `slack-cli` skill, **Step 4: Calling Web API Methods (`slack api`)**, to invoke it. That step covers the `SLACK_CMD api key=value …` syntax. Run `SLACK_CMD api --help` first to confirm the syntax **and the flag that skips authentication**. `blocks.validate` needs no token, so call it without authentication. Don't hard-code that flag from memory; read it from the help output so this stays correct if it's ever renamed. Pass the payload as a positional `key=value` argument: `blocks=` for messages, or `view=` for modals and home tabs. + +**Path B: curl (fallback, when the CLI isn't installed).** + +POST to the endpoint with the **Bash tool**. The API uses form-urlencoded encoding, so pass the JSON directly as the parameter value. + +**For messages**, send the `blocks` array as a form-encoded parameter: + +```bash +curl -s -X POST 'https://slack.com/api/blocks.validate' \ + -d 'blocks=[ ... the blocks array ... ]' +``` + +**For modals and home tabs**, send the complete view object in the `view` field: + +```bash +curl -s -X POST 'https://slack.com/api/blocks.validate' \ + -d 'view={ "type": "modal", "title": ..., "blocks": [...] }' +``` + +### 5b. Handle the response + +**Success:** + +```json +{ "ok": true } +``` + +Tell the developer their blocks are valid. + +**Failure:** + +```json +{ + "ok": false, + "error": "invalid_blocks", + "errors": [ + { + "code": "missing_field", + "message": "missing required field: type", + "field": "type", + "pointer": "/0" + } + ] +} +``` + +When validation fails: + +1. Read each error. `pointer` is a JSON pointer to the offending node (e.g., `/0` = first block, `/2/elements/1` = second element of the third block, `/0/text/type` = the `type` field of the first block's text object). `message` describes the problem, and `constraint` (when present) names the rule that failed and its expected values. +2. Fix the JSON. For the authoritative meaning of an error code and the field requirements behind it, consult the live method doc (`https://docs.slack.dev/reference/methods/blocks.validate.md`) and the relevant block/element/composition-object page you fetched in Steps 3-4. +3. Re-validate. Repeat until `"ok": true`. + +--- + +## Step 6: Deliver the Final Output + +Present the validated payload, then help the developer put it to use. + +### Send it + +Building the payload is this skill's job; sending it (`chat.postMessage`, `views.open`, `views.publish`, and the token/scope handling around them) belongs to the Web API layer. To call the right method — via the Slack CLI, raw curl, or a Bolt SDK — use the `slack-api` skill, **Step 4: Call the Method (Manage)**, passing this payload as the method's `blocks` argument (messages) or `view` argument (modals and home tabs). That skill matches the argument names to the SDK or HTTP call so we don't duplicate them here. + +### Preview it + +Help the developer view their layout with the **Block Kit Builder**. Prefer the Slack CLI if it is installed. The CLI automatically loads the blocks, saving the developer from copying and pasting. If the CLI is not available, provide the standard Builder link instead. + +**Path A: Slack CLI (preferred).** + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public CLI is installed and resolve its command (`SLACK_CMD`). Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. + +If the CLI is available, run `SLACK_CMD blocks preview --help` to see how to pass the blocks and open the preview. The command loads the blocks into the Block Kit Builder in the developer's browser. + +Because you run the CLI non-interactively, this command also needs a `--team` flag. Resolve the team ID with the `slack-cli` skill, **Step 2: Command Discovery via Help**, whose "Resolving `--app` and `--team` values" guidance covers running `SLACK_CMD auth list`; Any authenticated workspace works for a preview, if several are available, pick one and mention which you used rather than blocking on the choice. + +**Path B: Block Kit Builder link (fallback, when the CLI isn't installed).** + +Offer the Block Kit Builder link so the developer can paste the JSON in and tweak visually: `https://app.slack.com/block-kit-builder`. Builder needs an object (`{ "blocks": [...] }` or a full view object), not a bare array. + +--- + +## Step 7: Iterate + +Ask whether the developer wants to add, modify, remove, or reorder blocks, or build a layout for a different surface. If they want to change the layout you just produced, re-enter **Modification Mode** (it preserves their `block_id`/`action_id` values); for a fresh layout, loop back to Step 3. + +--- + +## Notes + +- **Scope:** this skill owns building and validating the Block Kit payload — choosing the surface, composing the JSON from the live docs, and confirming it with `blocks.validate`. Sending it lives in the Web API layer (the `slack-api` skill), and CLI detection/auth in the `slack-cli` skill. +- **`blocks.validate` needs no auth** — it's a public method, so it works without a token whether you call it via the CLI or curl. Always validate before finalizing (Step 5). diff --git a/.agents/skills/block-kit/references/agent-progress-design.md b/.agents/skills/block-kit/references/agent-progress-design.md new file mode 100644 index 0000000..0f8a0c6 --- /dev/null +++ b/.agents/skills/block-kit/references/agent-progress-design.md @@ -0,0 +1,162 @@ +# Agent Progress Design: Plans and Task Cards + +Guidance on showing an agent's work while it happens, using `plan` and `task_card` blocks, and +their streaming equivalents, the `task_update` and `plan_update` chunks. This covers +_appropriateness_: when to show steps, how to word them, and how they should change over time. +For field schemas, see the `plan`, `task_card`, and `url_source` element pages. For the streaming +API, see `https://docs.slack.dev/reference/methods/chat.startStream.md` and Slack's agent design +guide, `https://docs.slack.dev/concepts/agent-design.md`. Apply these principles unless the +developer explicitly asks otherwise. + +Both blocks are **messages only**. A `plan` holds up to 50 task cards, and each `task_id` in a +plan must be unique. + +## Pick the lightest progress signal that works + +Progress UI is for the user, not a log of everything the agent did. Use only as much as the work +needs: + +| The work is… | Show | +|---|---| +| a message that needs no answer (thanks, a passing mention, people talking to each other) | nothing, or a single emoji reaction | +| quick (a few seconds) or a single lookup | a status only (`agents.sessions.setStatus`, such as "Searching your workspace…") | +| a few steps, with the steps mixed into the answer | `task_update` chunks in the default `timeline` display mode: individual task cards between the streamed text | +| multi-step work where the agent is making decisions | a `plan`: `task_display_mode: "plan"` when streaming, or a `plan` block you update with `chat.update` | + +- **Use a plan for decisions, not data fetching.** Slack's guidance is to save plans for + multi-step work where the agent chooses what to do next. Three lookups and an answer don't need + a plan. +- **Make the plan secondary to the answer.** The plan explains how the agent got there; the + answer is what the user came for. Put the answer after the plan and make it able to stand on its + own. +- **Acknowledge right away, before any progress UI.** Set a status, or add a working reaction + such as 👀 to the user's message and remove it when the reply lands. Then the user knows the + agent saw the message, even if it decides to stay quiet. +- **If you react instead of replying, give each emoji one meaning** (👍 "got it", ✅ "done", + ❤️ "thanks") and use only those. A reaction is a reply, so it should be as clear as one. + +## Streaming vs. a posted message + +- **When streaming** (`chat.startStream` → `chat.appendStream` → `chat.stopStream`), send + progress as `task_update` chunks. Choose `task_display_mode` when you start the stream: + `timeline` (the default) for cards interleaved with the streamed text, or `plan` for one grouped + plan. Send a `task_update` with the same `id` to change a task's status, and a `plan_update` + chunk to retitle the plan. Each `task_update` and `plan_update` chunk is limited to 256 + characters, so keep `details` and `output` short. +- **Send a task's `details` once.** On an update with the same `id`, Slack adds the new `details` + to the earlier text instead of replacing it, with no separator. Send details either while the + task is in progress or when it completes, not both, and never send placeholder text you'll want + to replace. +- **Open the stream when there's something to show**, not when the run starts. If the agent ends + up staying quiet or only reacting, nothing is posted, so there's no empty message to clean up. +- **Send stream updates one at a time, in order, and wait for them all before + `chat.stopStream`.** If updates are fired off without waiting, a task's final `complete` can + arrive after the stream stops, which leaves that task spinning forever. +- **When not streaming**, post a message with a `plan` block and update it in place with + `chat.update` as each task changes. Don't post a new message per step, and don't call + `chat.update` more than about once every 3 seconds. Collect several changes into one update. +- **Don't build a progress view from text** ("Step 3 done ✅" lines in a `section`). The plan and + task card blocks already provide status icons, structure, and accessibility. + +## Give each piece of text one job + +A plan has three layers of text. Keep each one to its job so the plan reads at a glance: + +| Layer | Says | While working | When done | On failure | +|---|---|---|---|---| +| plan title | where the run is overall | what the agent is doing now: "Searching Linear" | the outcome: "Worked for 12s" | "Error" or "Stopped" | +| task title | the action | present tense: "Searching Linear issues" | past tense: "Searched Linear issues" | "Couldn't search Linear issues" | +| task details / output | the facts | the subject: "#incidents, last 7 days" | the result: "3 matches: INC-41, INC-44, …" | the reason: "Linear needs a reconnect" | + +- **Task titles name the action, not the subject.** Keep the subject (a query, a channel, a file + name) in the details, so titles stay short and the same tool always reads the same way. +- **Keep each title to one short phrase.** Slack's guidance is that a step should be one short + phrase; a paragraph of reasoning is too much. +- **Name the system in plain language, not the API**: "Checking your calendar", not "Calling + `events.list`". This also shows the user what the agent can access. For tools from a connected + app, put the app's name in front of the details: "Todoist · 3 tasks due today". +- **Lead with the verb and object**: "Drafting the reply to Priya", "Creating a Linear issue". +- **Make write actions obvious.** A task that creates, sends, or deletes something should say so + in its title ("Sending summary to #eng"). Read-only lookups can be grouped or kept low-key. +- **Never show raw tool output.** Turn results into a human line: a count and a few names ("12 + messages", "3 files: plan.md, notes.md, …"). Never show JSON, and if there's nothing useful to + say, say nothing rather than "Done". +- **Show retries as retries.** If the agent calls the same tool again after an error, title it + "Retrying: Searching Linear issues", or add "attempt 2" to the details, so it doesn't look like a + duplicate step. + +## Status, details, output, and sources + +- **Status reflects what's actually happening.** Set a task to `in_progress` only when the agent + starts it, then switch it to `complete` or `error`. Don't mark everything complete at the end; + the point is to show live progress. +- **Show the whole plan up front when the steps are known in advance.** Tasks that haven't + started can use `pending` in plan display mode. The plan guide documents it, but the + `task_card` page lists only `in_progress`, `complete`, and `error`, so check the live page. + When the agent decides steps as it goes, add tasks as they start rather than inventing a plan it + might not follow. +- **`details` is what the task did; `output` is what it found.** Keep both to a line or two of + `rich_text`: details "Searched #incidents for the last 7 days", output "Found 3 related + incidents". The full answer goes in the message body, not in a task's output. +- **Attach `sources` to the task that used them** (`url_source` elements). This keeps + attribution next to the step it supports, so you don't need a separate citation list for those + steps. +- **Use `hide_title`** only when the task's details already say everything the title would. + +## Voice + +- **Keep one voice everywhere**, either first person ("I found 3 issues") or neutral ("Found 3 + issues"), across status, task titles, errors, and recaps. Slack's own AI uses the neutral voice. + Don't give the agent feelings or a gender, and skip casual apologies. + +## When something goes wrong + +- **Mark the failing task `error`, not the whole plan.** Leave completed tasks `complete` so the + user can see how far the agent got. +- **Say what failed and why in that task's `output`**, in plain language: "No access to the + Project Beta board". +- **Name the cause and the fix** rather than "Something went wrong." Tell apart a credential the + user must fix ("Todoist needs a reconnect", with a Reconnect button), a temporary limit ("Rate + limited, try again in a minute"), and a bug on your side ("Something broke on my end. I've + logged it, please try again"). +- **Set the plan title to "Error"** when the run ends with a failed step, so the outcome is + visible even when the plan is collapsed. +- **Follow the plan with recovery options**: two or three next steps as buttons (Retry, Change Request, Ask an Admin), not a dead end. See `human-in-the-loop.md` for how to structure those + choices. +- **Clear the status when the agent stops**, even on failure, so the thread isn't left showing + "thinking" forever. Set `agents.sessions.setStatus` to `active`, or to `suspended` if the user + has to do something before the agent can continue, such as when the reply ends with a + clarifying question. + +## Stopping and interruptions + +- **Honor the Stop button.** When the user stops a run (the `agent_session_stopped` event), + cancel the work, end the stream with the plan title "Stopped", and post one short line: "Okay, + I stopped." Leave completed tasks as they are, so the user can see what was already done. +- **If the user sends a new message mid-run, start over quietly.** When newer messages change the + request, abandon the current run without a "stopped" note and respond to the thread as it is + now. The user didn't ask to stop, so there's nothing to acknowledge. +- **Cancel pending approvals with the run.** If a stopped run was waiting on an approval, mark the + approval as cancelled (see `human-in-the-loop.md`) so its buttons don't outlive the run. + +## When the work is done + +- **Set the final plan title to the outcome**, such as "Worked for 12s", so a collapsed plan still + tells the user the run finished and roughly how long it took. +- **End with a short recap**: what happened, with links to anything created or changed, and + anything skipped and why ("Couldn't assign to <@U123>, who isn't on the project"). Keep the + recap shorter than the task took to describe. +- **Add `feedback_buttons`** in a `context_actions` block after the final answer, not inside the + plan. + +## Quick self-review + +1. Does this work need a plan, or would a status or timeline task updates be enough? +2. Does each task title name the action, in plain language, with the facts in the details? +3. Do statuses change live, do write actions stand out, and are retries labeled? +4. Are `details` and `output` short (under 256 characters when streamed), sent once, never raw + JSON, with sources on the task that used them? +5. If a step fails, does the user see what worked, what didn't, and what they can do next? +6. Does the plan title end as the outcome ("Worked for…", "Error", "Stopped"), with no task left + spinning? +7. Is the final answer complete on its own, with the plan clearly secondary? diff --git a/.agents/skills/block-kit/references/common-patterns.md b/.agents/skills/block-kit/references/common-patterns.md new file mode 100644 index 0000000..9e3a8e1 --- /dev/null +++ b/.agents/skills/block-kit/references/common-patterns.md @@ -0,0 +1,485 @@ +# Common Block Kit Patterns + +> Starting scaffolds for frequent use cases — copy one and customize rather than building from scratch. +> They were valid when written, but the live docs (the skill's **Source of Truth**) remain authoritative for field schemas, and Block Kit evolves. Confirm any field you change against the component's doc page, and re-run the customized payload through `blocks.validate` (Step 5) before shipping. +> `[M]` patterns show `{ "blocks": [...] }` — add `channel` and a `text` fallback when calling `chat.postMessage` per Step 1; don't skip `text`, it matters for accessibility. + +--- + +## Approval Message [M] + +A notification with context and Approve/Reject buttons. + +```json +{ + "blocks": [ + { + "type": "header", + "text": { "type": "plain_text", "text": "New approval request" } + }, + { + "type": "section", + "text": { "type": "mrkdwn", "text": "*Requester:* <@U0123456789>\n*Type:* Access request\n*Details:* Production database read access" } + }, + { "type": "divider" }, + { + "type": "actions", + "block_id": "approval_actions", + "elements": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "Approve" }, + "style": "primary", + "action_id": "approve_btn", + "value": "request_123" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "Reject" }, + "style": "danger", + "action_id": "reject_btn", + "value": "request_123" + } + ] + } + ] +} +``` + +**Customization points:** Header text, section fields, button values, adding a confirmation dialog to the Reject button. + +--- + +## Simple Form Modal [V] + +A modal with text input, select menu, and optional checkbox. + +```json +{ + "type": "modal", + "callback_id": "feedback_form", + "title": { "type": "plain_text", "text": "Send feedback" }, + "submit": { "type": "plain_text", "text": "Send Feedback" }, + "close": { "type": "plain_text", "text": "Cancel" }, + "blocks": [ + { + "type": "input", + "block_id": "category_block", + "label": { "type": "plain_text", "text": "Category" }, + "element": { + "type": "static_select", + "action_id": "category_select", + "placeholder": { "type": "plain_text", "text": "Choose a category" }, + "options": [ + { "text": { "type": "plain_text", "text": "Bug report" }, "value": "bug" }, + { "text": { "type": "plain_text", "text": "Feature request" }, "value": "feature" }, + { "text": { "type": "plain_text", "text": "General feedback" }, "value": "general" } + ] + } + }, + { + "type": "input", + "block_id": "description_block", + "label": { "type": "plain_text", "text": "Description" }, + "element": { + "type": "plain_text_input", + "action_id": "description_input", + "multiline": true, + "placeholder": { "type": "plain_text", "text": "Ex. The export button does nothing" } + } + }, + { + "type": "input", + "block_id": "urgency_block", + "label": { "type": "plain_text", "text": "Priority" }, + "element": { + "type": "radio_buttons", + "action_id": "urgency_select", + "options": [ + { "text": { "type": "plain_text", "text": "Low" }, "value": "low" }, + { "text": { "type": "plain_text", "text": "Medium" }, "value": "medium" }, + { "text": { "type": "plain_text", "text": "High" }, "value": "high" } + ] + }, + "optional": true + } + ] +} +``` + +**Customization points:** Title, callback_id, input types, options list, adding/removing input blocks. + +--- + +## Notification Alert [M] + +A notification headline with description, timestamp context, and next actions. The `alert` block is available only in modals, so a message states its severity in words in the `header`. Keep emoji out of headers and buttons; Slack's style uses emoji only in running text. + +```json +{ + "blocks": [ + { + "type": "header", + "text": { "type": "plain_text", "text": "Deployment failed: api-gateway" } + }, + { + "type": "section", + "text": { "type": "mrkdwn", "text": "The deployment to *production* failed during the health check phase.\n\n*Error:* `Connection timeout after 30s`\n*Commit:* `a1b2c3d`" } + }, + { + "type": "context", + "elements": [ + { "type": "mrkdwn", "text": "Triggered by <@U0123456789> · " } + ] + }, + { + "type": "actions", + "elements": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "View Logs" }, + "url": "https://logs.example.com/deploy/456", + "action_id": "view_logs_btn" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "Retry Deploy" }, + "style": "primary", + "action_id": "retry_deploy_btn" + } + ] + } + ] +} +``` + +**Customization points:** Severity word and emoji in the header ("Deployment failed", "Warning: disk at 90%"), description text, action buttons. Also set the message's top-level `text` fallback to the headline, such as "Deployment failed: api-gateway". In a modal, use an `alert` block with a `level` instead of the header. + +--- + +## Dashboard Home Tab [H] + +A welcome dashboard with metrics fields and quick-action buttons. + +```json +{ + "type": "home", + "blocks": [ + { + "type": "header", + "text": { "type": "plain_text", "text": "Welcome to AppName" } + }, + { + "type": "section", + "text": { "type": "mrkdwn", "text": "Here's your overview for today:" } + }, + { + "type": "section", + "fields": [ + { "type": "mrkdwn", "text": "*Open tickets*\n12" }, + { "type": "mrkdwn", "text": "*Resolved today*\n5" }, + { "type": "mrkdwn", "text": "*Average response*\n2.4 hours" }, + { "type": "mrkdwn", "text": "*SLA status*\nOn track :white_check_mark:" } + ] + }, + { "type": "divider" }, + { + "type": "actions", + "elements": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "New Ticket" }, + "style": "primary", + "action_id": "new_ticket_btn" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "My Queue" }, + "action_id": "my_queue_btn" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "Settings" }, + "action_id": "settings_btn" + } + ] + } + ] +} +``` + +**Customization points:** Metrics fields, action buttons, adding image blocks or additional sections. + +--- + +## Confirmation with Dialog [M] + +An action button with a confirmation dialog attached (prevents accidental clicks). + +```json +{ + "blocks": [ + { + "type": "section", + "text": { "type": "mrkdwn", "text": "Are you sure you want to shut down *prod-server-01*?" } + }, + { + "type": "actions", + "elements": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "Shut Down" }, + "style": "danger", + "action_id": "shutdown_btn", + "value": "prod-server-01", + "confirm": { + "title": { "type": "plain_text", "text": "Shut down server" }, + "text": { "type": "plain_text", "text": "This will immediately terminate the server. Active connections will be dropped." }, + "confirm": { "type": "plain_text", "text": "Shut Down" }, + "deny": { "type": "plain_text", "text": "Cancel" }, + "style": "danger" + } + } + ] + } + ] +} +``` + +**Customization points:** Confirmation title/text (title max 100 chars, text max 300 chars, confirm/deny max 30 chars), button style. + +--- + +## Data Table [M] + +A structured table for displaying tabular data. Only one table block per message. + +```json +{ + "blocks": [ + { + "type": "header", + "text": { "type": "plain_text", "text": "Sprint summary" } + }, + { + "type": "table", + "column_settings": [ + { "is_wrapped": true }, + { "align": "center" }, + { "align": "right" } + ], + "rows": [ + [ + { "type": "raw_text", "text": "Name" }, + { "type": "raw_text", "text": "Status" }, + { "type": "raw_text", "text": "Points" } + ], + [ + { "type": "raw_text", "text": "Auth refactor" }, + { "type": "raw_text", "text": "In Progress" }, + { "type": "raw_text", "text": "5" } + ], + [ + { "type": "raw_text", "text": "API docs update" }, + { "type": "raw_text", "text": "Done" }, + { "type": "raw_text", "text": "2" } + ], + [ + { "type": "raw_text", "text": "Bug #1234" }, + { "type": "raw_text", "text": "Blocked" }, + { "type": "raw_text", "text": "3" } + ] + ] + } + ] +} +``` + +**Customization points:** Column settings (alignment: `left`/`center`/`right`, wrapping: `is_wrapped`), row data, cell type (`raw_text` for plain content, `rich_text` for formatted content with links/emoji/mentions). Max 100 rows, max 20 cells per row. First row is the header. Only one table block per message. + +--- + +## Settings Modal with Multiple Input Types [V] + +A modal combining different input types for a settings/preferences form. + +```json +{ + "type": "modal", + "callback_id": "settings_modal", + "title": { "type": "plain_text", "text": "Notification settings" }, + "submit": { "type": "plain_text", "text": "Save" }, + "close": { "type": "plain_text", "text": "Cancel" }, + "blocks": [ + { + "type": "input", + "block_id": "channel_block", + "label": { "type": "plain_text", "text": "Notification channel" }, + "element": { + "type": "conversations_select", + "action_id": "channel_select", + "default_to_current_conversation": true + } + }, + { + "type": "input", + "block_id": "frequency_block", + "label": { "type": "plain_text", "text": "Digest frequency" }, + "element": { + "type": "static_select", + "action_id": "frequency_select", + "options": [ + { "text": { "type": "plain_text", "text": "Real-time" }, "value": "realtime" }, + { "text": { "type": "plain_text", "text": "Hourly" }, "value": "hourly" }, + { "text": { "type": "plain_text", "text": "Daily" }, "value": "daily" } + ], + "initial_option": { "text": { "type": "plain_text", "text": "Daily" }, "value": "daily" } + } + }, + { + "type": "input", + "block_id": "events_block", + "label": { "type": "plain_text", "text": "Notify me about" }, + "element": { + "type": "checkboxes", + "action_id": "events_checkboxes", + "options": [ + { "text": { "type": "plain_text", "text": "New deployments" }, "value": "deploys" }, + { "text": { "type": "plain_text", "text": "Failed builds" }, "value": "failures" }, + { "text": { "type": "plain_text", "text": "PR reviews needed" }, "value": "reviews" } + ] + } + }, + { + "type": "input", + "block_id": "quiet_hours_block", + "label": { "type": "plain_text", "text": "Quiet hours start" }, + "element": { + "type": "timepicker", + "action_id": "quiet_start", + "initial_time": "22:00", + "placeholder": { "type": "plain_text", "text": "Select time" } + }, + "optional": true + } + ] +} +``` + +**Customization points:** Input types, options, initial values, adding `hint` text to inputs, marking fields as `optional`. + +--- + +## Rich Text Section [M] + +Formatted text with bold, links, and a bullet list — the WYSIWYG-composer format, for layouts needing richer inline styling or structure than a `mrkdwn` string offers. + +```json +{ + "blocks": [ + { + "type": "rich_text", + "elements": [ + { + "type": "rich_text_section", + "elements": [ + { "type": "text", "text": "Deploy summary: " }, + { "type": "text", "text": "3 services", "style": { "bold": true } }, + { "type": "text", "text": " updated. See the " }, + { "type": "link", "url": "https://example.com/changelog", "text": "changelog" }, + { "type": "text", "text": " for details." } + ] + }, + { + "type": "rich_text_list", + "style": "bullet", + "elements": [ + { "type": "rich_text_section", "elements": [{ "type": "text", "text": "api-gateway: v2.4.1" }] }, + { "type": "rich_text_section", "elements": [{ "type": "text", "text": "auth-service: v1.9.0" }] } + ] + } + ] + } + ] +} +``` + +**Customization points:** Text styling (`bold`, `italic`, `strike`, `code`) on individual `text` elements, list `style` (`bullet` or `ordered`), adding `rich_text_quote` or `rich_text_preformatted` elements, mixing in `user`/`channel`/`emoji` elements for mentions and reactions inline. + +--- + +## Row Actions with Overflow Menu [M] + +A row-level "⋯" menu for actions that don't need dedicated buttons (edit, duplicate, delete). + +```json +{ + "blocks": [ + { + "type": "actions", + "block_id": "row_actions_block", + "elements": [ + { + "type": "overflow", + "action_id": "row_actions", + "options": [ + { "text": { "type": "plain_text", "text": "Edit" }, "value": "edit" }, + { "text": { "type": "plain_text", "text": "Duplicate" }, "value": "duplicate" }, + { "text": { "type": "plain_text", "text": "Delete" }, "value": "delete" } + ], + "confirm": { + "title": { "type": "plain_text", "text": "Delete item" }, + "text": { "type": "plain_text", "text": "This can't be undone." }, + "confirm": { "type": "plain_text", "text": "Delete" }, + "deny": { "type": "plain_text", "text": "Cancel" }, + "style": "danger" + } + } + ] + } + ] +} +``` + +**Customization points:** Option list (max 5), which option(s) trigger the `confirm` dialog, using `overflow` as a `section` block's `accessory` instead of inside `actions` for a single row's trailing menu. + +--- + +## Card Preview [M] + +An image/thumbnail-driven card — link preview, product card, or similar — with a title, body, and action buttons. + +```json +{ + "blocks": [ + { + "type": "card", + "hero_image": { + "type": "image", + "image_url": "https://example.com/product-photo.png", + "alt_text": "Wireless noise-cancelling headphones, matte black" + }, + "title": { "type": "plain_text", "text": "Noise-Cancelling Headphones" }, + "subtitle": { "type": "plain_text", "text": "$149.99 — In stock" }, + "body": { "type": "mrkdwn", "text": "30-hour battery life, USB-C fast charging, and adaptive noise cancellation." }, + "actions": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "View Product" }, + "url": "https://example.com/products/headphones", + "action_id": "view_product_btn" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "Add to Cart" }, + "style": "primary", + "action_id": "add_to_cart_btn", + "value": "headphones_sku_123" + } + ] + } + ] +} +``` + +**Customization points:** `hero_image` (top image) vs. `icon` (small image beside title/subtitle — mutually exclusive with `slack_icon`), `subtext` for secondary detail below `body`, up to 3 `actions` buttons. At least one of `hero_image`, `title`, `actions`, or `body` is required; `title`/`subtitle` max 150 chars, `body`/`subtext` max 200 chars. diff --git a/.agents/skills/block-kit/references/data-display-design.md b/.agents/skills/block-kit/references/data-display-design.md new file mode 100644 index 0000000..803423d --- /dev/null +++ b/.agents/skills/block-kit/references/data-display-design.md @@ -0,0 +1,111 @@ +# Data Display Design: Fields, Tables, and Charts + +Guidance on presenting numbers and records so a reader understands them quickly. Like +`design-principles.md`, this covers _appropriateness_, not validity. For field schemas, see the +`section`, `table`, `data_table`, and `data_visualization` block pages. Apply these principles +unless the developer explicitly asks otherwise. + +## Pick the format that fits the data + +| The data is… | Use | Surfaces | +|---|---|---| +| one number that matters | a sentence that states it ("Error rate is 2.1%, up from 0.4%") | all | +| progress toward a goal, or fewer than 4 data points | a sentence ("412 of 500 seats filled (82%)") or `section` `fields` | all | +| a few key/value facts about one thing | a `section` with `fields` (up to 10) | all | +| a short set of rows with the same columns | a `table` (up to 100 rows) | messages, App Home | +| many rows, or rows the reader sorts, pages through, or acts on | a `data_table` (up to 200 rows, paginated, sortable, `action_cell` buttons) | messages, App Home | +| a trend over time | a `data_visualization` `line` (or `area` for totals that stack) | messages, App Home | +| a comparison across categories | a `data_visualization` `bar` | messages, App Home | +| shares of a whole | a `data_visualization` `pie`, with no more than about 5 slices | messages, App Home | + +- **Start from the question the reader has.** "Did the deploy work?" needs a sentence, not a + chart. "Which service is slowest this week?" needs a sorted table or a bar chart. +- **Don't show the same data twice** in a table and a chart unless they answer different + questions. Pick one, and link to the full data for anything more. +- **In a modal**, where `table`, `data_table`, and charts aren't available, use `section` `fields` + for key/value data and summarize rows into a few lines. Link out for the full set. + +## Fields + +- **Keep labels short and bold, and values short**: `*Status*\nIn review`. Fields lay out in two + columns, so long values wrap and break the grid. +- **Put the most important pair first.** Readers scan fields top-left to bottom-right. +- **Use an even number of fields** where you can, so the last row isn't half empty. + +## Tables + +- **Lead with the column that identifies the row** (name, ID, title), and set a `data_table`'s + `row_header_column_index` to it so screen readers announce each row by name. +- **Give every `data_table` a `caption`** (required) that says what the table shows: "Open + incidents, sorted by severity". +- **Keep it narrow.** About five columns fit comfortably, especially on mobile. Drop columns the + reader doesn't need to decide anything. +- **Sort rows by what matters**: the worst first, the newest first, the biggest first. Say how it's + sorted in the caption or the lead sentence. +- **Use `raw_number` cells for numbers** so a `data_table` sorts them numerically. Put units in + the header ("Latency (ms)") rather than in every cell. +- **Choose a page size for a `data_table`** that fits the message: the default of 5 rows suits a + digest, and 10–20 suits a report the reader came to look at. +- **Use an `action_cell` for one action per row** ("Open", "Mark Done"), with the row's ID in the + button's `value` and a `fallback` cell for clients that can't show buttons. Buttons in a copy of + the message shared elsewhere are disabled, so don't rely on them as the only way to act. +- **Only one `table` fits in a message, and cell text is capped across the message** (10,000 + characters for `table`, 20,000 for `data_table`). For more, summarize and link out. + +## Charts + +- **Write a title that says what the chart shows.** Keep it to 50 characters or fewer: "Deploys + per day, last 2 weeks". +- **State the takeaway in text.** Put the main point, with its number, in the chart's description + and in the message text: "Deploys doubled after the pipeline change." Notifications, previews, + and screen readers get only the text, and on mobile the reader can't open the expanded view. +- **Name the items that matter.** A chart can't highlight a bar or point, and it drops value labels + when space is tight. Write "3 accounts need attention: Harmony Labs, Acme, Northwind" rather than + leaving the reader to find them. +- **Label both axes, including units.** Use `x_label` and `y_label`: "Latency (ms)". +- **Use one series for one comparison.** A bar chart of 8 services is one series in one color. + Giving each bar its own series adds colors that suggest a difference that isn't there. +- **Keep series to a few.** One to three lines or bar groups are easy to read. Past 6, colors + repeat in a second shade that's hard to tell apart, especially with color vision deficiency. + Series names appear in the legend, so keep them short and distinct. +- **Use color only to tell series apart.** Slack assigns colors automatically, in series order, and + they change in dark mode. Avoid ordering series so a color seems to mean good or bad, and avoid + referring to "the orange line". Say what's good or bad in text, and refer to each series by name. +- **Choose the chart type that fits the data.** + - **Bar** compares values across categories. Keep to about 6 categories with one-word labels + ("Q1", "Legal", "API"), because the card is often narrow. For more categories or longer + labels, use a sorted table. + - **Line** shows a trend over time. Keep to 3 lines with at least 4 points each. + - **Area** shows a total over time and what it's made of. Areas always stack, so use one only + when the series add up to a meaningful total; otherwise, use a line chart. Keep to 3 series. + - **Pie** shows parts of one whole. Keep to 5 segments, largest first, and group the rest into + "Other". For more, use a sorted bar chart. +- **Order categories meaningfully.** Put time left to right. For bars, put the largest first unless + the categories have a natural order. Slack keeps the order you provide. +- **Fit the data to the block.** A series holds at most 20 points, so aggregate a long range + (weekly instead of daily) rather than trimming it. Every series needs a value for every + category, so don't fill a gap with zero. Drop that category from every series and say what's + missing in text. +- **Skip the chart when there's no data.** Say so in a sentence instead: "No deploys this week." +- **Include no more than two charts in a message.** For a dashboard, use the App Home or link to + your product. + +## Numbers and dates in text + +- **Round to what matters**: "2.1%", not "2.0847%". Abbreviate only from 10,000 up, with a capital + K or M ("21K messages"); below that, write the full number ("1,187"). +- **Show change with direction and a baseline**: "up 3 points from last week", not a bare arrow + or a color. +- **Use a `date` element in `rich_text`, or mrkdwn's `` syntax, for timestamps**, so each + reader sees them in their own timezone and format, with relative wording ("today", "3 hours + ago") where it helps. Always include fallback text. +- **Write dates without ordinals**: "Aug 2, 2026", not "Aug 2nd". + +## Quick self-review + +1. Does the format answer the reader's question, and is it supported on this surface? +2. Is the key number or takeaway stated in text, not only in the table or chart? +3. Does every table have the identifying column first, a clear sort, and units in the header? +4. Does every chart have a title, axis labels, and few enough series and categories to read, + with color used only to tell series apart? +5. Are timestamps localized, and are numbers rounded to what matters? diff --git a/.agents/skills/block-kit/references/design-principles.md b/.agents/skills/block-kit/references/design-principles.md new file mode 100644 index 0000000..4236977 --- /dev/null +++ b/.agents/skills/block-kit/references/design-principles.md @@ -0,0 +1,195 @@ +# Block Kit Design Principles + +Guidance on building layouts that read well, not on whether they parse. Validity — required +fields and allowed element nesting — is what `blocks.validate` checks. These principles are about +_appropriateness_: reaching for the block that fits the shape of the content, and arranging it so +a reader takes it in at a glance. Apply them unless the developer explicitly asks otherwise. + +**`blocks.validate` does not enforce which surface a block or how many of it are allowed.** It +checks block and element shape only. It will return `ok: true` for a `table` or `carousel` inside +a modal, an `alert` inside a message, two `table` blocks in one message, or an `input` block in a +modal with no `submit` — all invalid per the surface and limits table below. Treat that table, +not a passing validation, as the source of truth for surface and count limits. + +These principles apply to every surface. Companion references go deeper on specific kinds of +layout: `modal-design.md` (modals and forms), `home-tab-design.md` (App Home), +`data-display-design.md` (fields, tables, and charts), `agent-progress-design.md` (plans and +task cards), and `human-in-the-loop.md` (approvals and choices). + +## Reach for the block that fits the shape of the content + +Don't stack `section` + `divider` text when a purpose-built block fits better, and don't add +structure to content that doesn't need it. Match the block to what the content _is_: + +- **Tabular or comparable rows** (metrics, line items, a leaderboard) belong in a `table`. + Stacked sections force the reader to scan prose; a table aligns columns so values compare at a + glance. When the reader needs to page, sort, or act on rows (more than a screenful, or a button + per row), use a `data_table` instead. +- **A trend, comparison, or share of a whole** (deploys per day, spend by team) belongs in a + `data_visualization` chart, always with the key number stated in text as well. + `data-display-design.md` covers choosing between fields, tables, and charts. +- **One rich entity the message is about** (an alert, an incident, a record, a PR) belongs in a + `card`. A card groups the entity's title, body, and actions into one bounded unit instead of + loose blocks. +- **A browsable set of peer items the reader chooses among** (a catalog, options, search results) + belongs in a `carousel` of cards — horizontal browsing instead of an ever-growing vertical + stack. +- **A status update or an approval** (one subject plus a decision) is well served by a `header` + for the title, a `section` with `fields` for the key/value details, and an `actions` block for + the buttons. +- **Multi-step work an agent is doing** (a plan, a checklist of tool calls) belongs in a `plan` + of `task_card`s, each with a `status` — not a growing wall of "Step 3 done ✅" text. +- **A group of related blocks that belong together** (a record's details, an optional + breakdown) can go in a `container`, with a title and, for secondary detail, `is_collapsible` + so it starts collapsed. It holds up to 10 child blocks, but not `card`, `carousel`, or + `data_table`. +- **A notice about the whole view in a modal** (a validation problem, a success state, a warning + before submitting) belongs in an `alert` block. `alert` is available only in modals, so in a + message state the level in words ("Deploy failed", "Warning:") in a `header` or `section`. +- **A status, a date, or a source inside text** belongs in a `rich_text` inline element: a `tag` + for a status pill ("In progress"), a `date` for a timestamp that shows in each reader's own + timezone and format, and a `citation` for an AI answer's source. +- **A one-line notice with no structure** should stay plain text. Don't add blocks for their own + sake; wrapping a one-line status in a `card` or a table works against the content, not for it. + +Avoid `divider` between every block. Use it only to separate genuinely distinct groups; a +`header` or the edge of a `card` usually does the job better. + +### Know where each block works and how much it holds + +A block that fits the content can still be the wrong choice for the surface, and each block has +limits: + +| Block | Surfaces | Holds at most | +|---|---|---| +| `table` | messages, App Home | 100 rows × 20 cells; 10,000 chars across cells per message | +| `data_table` | messages, App Home | 200 rows + header × 20 columns; 20,000 chars across cells per message | +| `data_visualization` | messages, App Home | 2 per message; 12 series or slices; 20 points per series | +| `carousel` | messages, App Home | 1–10 cards | +| `card` | messages, modals, App Home | 3 actions; title 150 chars, body 200 chars | +| `container` | messages, App Home | 10 child blocks; title 150 chars | +| `alert` | modals only | 200 chars | +| `markdown` | messages only | 12,000 chars across all markdown blocks in the payload | +| `plan` / `context_actions` | messages only | 50 task cards / 5 elements | +| `section` `fields` | all | 10 fields, 2,000 chars each | +| _(whole surface)_ | — | 50 blocks per message; 100 per modal or App Home | + +In a modal, where `table` and `carousel` aren't available, use a `section` with `fields` for key/value +data. For content that would go over these limits, summarize and link out first. For a large +table, a paginated `data_table` comes next. Split content across messages only as a last resort: +a reader can't sort, search, or act on it as one set, and every extra message is another +notification. + +## Emphasis and actions + +- **Emphasize at most one button per message or view**, not per `actions` block. If the layout + has one clear main action, make it `primary` (Approve, Save, Send). Use `danger` only when the + _main_ action is destructive (Delete, Remove). In an Approve/Reject pair, `primary` goes on + Approve and Reject stays unstyled. When the buttons are equal choices (clarifying options, row + actions, filters), leave them all unstyled. If everything is emphasized, nothing is. +- **In a modal, Submit is already the main action.** Don't add a `primary` button inside the + view's blocks to compete with it. +- **Label buttons with specific verbs** ("Approve Request", "Open Incident"), never "Click Here". + The label, not the red or green style, must say what the button does. +- **Keep the visible action set small.** Put two or three actions inline and move advanced or + rare ones into an `overflow` menu. +- **Guard destructive actions with a confirmation dialog** (`confirm`) so an accidental click + can't do irreversible harm. + +## Words and labels + +Match the conventions of Slack's own UI, so an app reads like part of Slack: + +- **Use Title Case for action button labels** ("Approve Request", "View Logs"). **Use sentence + case for everything else**: `header` text, modal titles, input labels, menu and `overflow` + options, links, and `context` text. +- **No end punctuation in headings**: "Deploy failed on prod-3", not "Deploy failed on prod-3." +- **Save commits changes; Done only closes.** Don't label a button that saves "Done", or one that + only closes "Save". + +## Layout and reading order + +- **Order blocks top-to-bottom in reading order:** lead with a `header` for the title, then the + content `section`s, then any `actions`, then a trailing `context` block for footnotes. Don't + bury the title in the middle of the layout. +- **Put the point first.** The first line should say what happened or what's needed ("Deploy + failed on prod-3", "Your approval is needed"). Background comes after that. +- **Put secondary or metadata text in a `context` block, not a `section`**: attribution, + timestamps, status, help links. Separate multiple fragments with " · " (for example, + "Posted by <@U123> · 2 min ago"). + +## Messages that change over time + +- **Update the message in place** (`chat.update`, or `replace_original` via `response_url`) for + progress and state changes. Don't post a new message for each step. +- **When a flow is finished, remove its controls.** Replace the `actions` block with a + `context` line recording the outcome ("Approved by <@U123> · 10:42"), so stale buttons can't be + clicked again. +- **Keep `action_id`s stable** across updates so handlers keep matching. Give an updated message + a **new `block_id`**, so interactions from an older copy can be told apart. + +## Text: rich_text, mrkdwn, and the markdown block + +- **Formatted text you build in code** (lists, quotes, code blocks, mentions, links) belongs in + a `rich_text` block. It is the composer's native format and Slack's preferred one. +- **Short text inside a `section` or `context`** uses Slack `mrkdwn`: `*bold*`, `_italic_`, + `~strike~`, `` `code` ``. This is Slack's syntax, not `**bold**`. +- **Long-form or AI/LLM-generated content that already exists in standard markdown** (headings, + tables, numbered lists, `**bold**`) belongs in a `markdown` block (messages only). Its + `block_id` is not preserved and images render as links. Use it for body content, not for + anything you'll need to find again or update. Don't translate LLM markdown into mrkdwn by hand. + +## AI and agent output + +- **Show work in progress as structure:** use a `plan` / `task_card` for steps, and switch each + card's `status` to `complete` or `error` as the work happens. When streaming, send steps as + `task_update` chunks instead. `agent-progress-design.md` covers when to use a plan, how to word + steps, and how to handle failures. +- **When streaming, send the rest of the layout in the final call** (`chat.stopStream`), so + partly built blocks don't render mid-stream. +- **Collect feedback with `feedback_buttons`** inside a `context_actions` block at the end of the + response, instead of hand-rolled thumbs-up and thumbs-down buttons. +- **Cite sources where the claim is made.** In `rich_text`, use a `citation` element for each + source. In mrkdwn, use inline links, with a `context` block listing references at the end. +- **Ask before acting.** Put an explicit `confirm` or Approve/Cancel choice on + anything that creates, sends, or deletes on the user's behalf. `human-in-the-loop.md` covers + approval gates, approving several actions in one message, and closing the loop afterwards. + +## Accessibility and fallback + +Accessibility is easy to skip and hard to retrofit, so build it in from the start: + +- **Summarize the layout in a message's top-level `text` fallback.** Notifications and screen + readers show it instead of the blocks. State the point and any action needed ("Deploy failed + on prod-3 — approval needed to roll back"), not a generic "New message". An empty fallback + leaves those readers with nothing, and `blocks.validate` won't warn you. +- **Give images descriptive `alt_text`** (what the image shows, not just "image"). Make sure + image-heavy layouts also carry the key information as text. If an image is purely decorative, + drop it. +- **Never use color as the only signal.** A red `danger` button, an emoji, or an `alert` level + needs words that say the same thing. +- **Use emoji alongside text, never instead of it, and only in running text.** Keep them out of + buttons, menu options, labels, and headers, and don't use them as bullets. Keep them few. +- **Set `accessibility_label` on buttons** whose visible text is ambiguous out of context + ("View", "Open"). +- **Use `header` blocks for logical section headings.** They convey document structure to + assistive tech. They take `plain_text` only, up to 150 chars. +- **Give tables and charts a text equivalent.** A `data_table` needs a `caption`, and + `row_header_column_index` should point at the column that names each row. A chart needs its + main takeaway in text next to it ("Deploys doubled week over week"). +- **Avoid directional references** such as "see above" or "the button on the right". Layouts + reflow on mobile and are read linearly by screen readers. + +## Quick self-review + +Before handing back a layout, check: + +1. Does each block match the shape of its content, and is it supported on this surface? +2. Does the first line (and the `text` fallback) say the point? +3. Is at most one button `primary` in the whole message or view, and are destructive actions + confirmed? +4. Is metadata in `context`, and is the reading order header → content → actions → context? +5. Will this message be updated? If so, how does it look when the flow finishes? +6. Can someone who can't see colors, emoji, or images still understand it? +7. Are buttons in Title Case and everything else in sentence case, with no end punctuation in + headings and no emoji in buttons, labels, or headers? diff --git a/.agents/skills/block-kit/references/home-tab-design.md b/.agents/skills/block-kit/references/home-tab-design.md new file mode 100644 index 0000000..160126e --- /dev/null +++ b/.agents/skills/block-kit/references/home-tab-design.md @@ -0,0 +1,88 @@ +# App Home Design + +Guidance on Home tabs that people return to. Like `design-principles.md`, this covers +_appropriateness_, not validity. For the view object and publishing, see +`https://docs.slack.dev/surfaces/app-home.md`. Apply these principles unless the developer +explicitly asks otherwise. + +A Home tab is one view of up to 100 blocks, published per user with `views.publish`. Unlike a +message, it's persistent and personal: each user sees their own version, and it should be up to +date whenever they open it. + +## Put the most important thing at the top + +- **Lead with what this user needs now**: items waiting on them, today's status, or the one + action they come here for. Slack's guidance is that the most important content and the entry + points to your app's core features belong at the top. +- **Then the rest, in sections**, each with a `header`: recent activity, settings, help. + Separate genuinely different sections with a `divider`, not every block. +- **Don't open with a welcome banner** after the first visit. Returning users came for the + content, not the introduction. + +## Keep actions few + +- **Limit the visible calls to action.** Put the main one or two actions in an `actions` block + near the top, give each row its own button for its action ("Open", "Read"), and move rare + actions into an `overflow` menu. +- **Put settings behind a button** that opens a modal (see `modal-design.md`), rather than laying + out every setting on the Home tab. Show admin-only settings only to admins. +- **Open details in a modal** rather than expanding the Home tab. A "Read" or "Open" button that + opens a modal keeps the Home tab short. + +## Empty and first-run states + +- **Teach by example in empty states.** Instead of "No routines", say what it would look like and + how to start: `_None yet. Ask me for one: "every weekday at 8am, tell me what needs me today."_` +- **Onboard on the first visit.** Use the `app_home_opened` event to detect a new user and show a + short setup: what the app does, the one thing to try first, a button to start, and a way to + dismiss it. Replace it with the normal Home tab once they've done it. +- **Welcome back long-absent users** with what changed or what's waiting, not the full + onboarding again. + +## Keep it current + +- **Publish on `app_home_opened`** so the view is fresh when the user looks, and publish again + when the user's data changes (an item resolved, a setting saved). +- **Show freshness where it matters**: "Updated 2 min ago" in a `context` block at the top, using + a `date` element or `` so it's localized. +- **Make status rows self-explanatory**: name, state, and the last outcome. For example, + `*Daily digest* · paused` and `_Last run Tue 8:00 AM: nothing to report_`. +- **Don't show stale controls.** After an action completes, publish a view that reflects it, + rather than leaving a button that does nothing. + +## Different people, different Home tabs + +The Home tab is published per user, so it can, and often should, differ by role. + +- **Show each user only what they're allowed to see.** Decide on the server what each role + (owner, admin, member, guest) gets, and build the view from that. Hiding a button isn't access + control; the action handler must check permissions too. +- **Let owners and admins preview other roles' views**: a "View as Member" button that publishes + the reduced view to them, with a `context` line saying they're previewing and a button back. + +## A review surface for agents + +When an app or agent acts on a user's behalf, the Home tab is where the user checks what it did. + +- **List recent actions and conversations**, newest first, each with who, where, when, and a + short excerpt, and a button to read the full record in a modal. +- **Show pending items** (approvals waiting, failed runs) above the history, with a direct action + for each. +- **Give users a place to manage trust**: revoke an "Always Allow", reconnect an app, or pause a + routine. + +## Long content + +- **Split long text across `section` blocks** under the 3,000-character limit per text field. In a + modal, also stay under the 100-block view limit, and add a `context` line such as "File + continues beyond what this view can show" with a link to the full content. +- **Link out rather than paging inside the Home tab.** A short, current summary plus a link beats + a long view the user has to scroll through. + +## Quick self-review + +1. Is the most important content for this user at the top, with at most one or two main actions? +2. What does a brand-new user see, and what does the view show when a section is empty? +3. Is the view published on open and whenever the data changes, with no stale controls? +4. Does each role see only what it should, with permissions checked in the handlers? +5. If the app acts on users' behalf, can they review and manage what it did here? diff --git a/.agents/skills/block-kit/references/human-in-the-loop.md b/.agents/skills/block-kit/references/human-in-the-loop.md new file mode 100644 index 0000000..8d256c2 --- /dev/null +++ b/.agents/skills/block-kit/references/human-in-the-loop.md @@ -0,0 +1,223 @@ +# Human-in-the-Loop Design: Approvals, Choices, and Review + +Guidance on Block Kit layouts where a person has to decide before an app or agent continues: +approval gates, sets of proposed actions to approve together, clarifying choices, and +edit-before-send. As in `design-principles.md`, this covers _appropriateness_, not validity. For +the underlying guidance, see Slack's agent design guide +(`https://docs.slack.dev/concepts/agent-design.md`, "Confirmation and control") and governance +guide (`https://docs.slack.dev/ai/agent-governance.md`). Apply these principles unless the +developer explicitly asks otherwise. + +## Decide when to ask + +- **Ask before anything that creates, sends, deletes, or spends**, and before acting as the user + in a way other people will see. Reads and drafts don't need a gate. +- **Ask when the request is ambiguous** and more than one reasonable path exists. Offer the paths + as choices; don't guess. +- **Don't ask about everything.** Confirming every step teaches users to click through without + reading. Save gates for actions that matter, and let users stop being asked about a class of + action once they trust it (see **Earn trust over time** below). +- **Match the gate to the stakes.** A reversible, low-impact action can go ahead and offer Undo + afterwards. An irreversible or high-impact one needs approval first, and possibly a `confirm` + dialog on top. +- **Write the policy down as lists, not case-by-case judgment.** An agent's gate is easiest to + trust when it's predictable: + - **Always ask** for destructive actions (delete, cancel, archive, revoke, forget) and for + outbound actions that reach other people (send, post, share, invite, forward). + - **Never ask** for cheap, reversible, or self-scoped actions (add a reaction, pin a message, + save a note to the user's own memory, create a draft). + - **For tools you don't know in advance**, such as tools from a connected MCP server, check the + tool name for the same verbs (`gmail_send_email`, `calendar_event_delete`), and ask when one + appears. + +## Pick the pattern + +| The decision is… | Use | +|---|---| +| go / don't go on one action | **Approval gate**: a preview, then Approve / Edit / Cancel | +| several proposed actions at once | **Approval set**: one message that lists every item, with a way to choose which to approve | +| which of a few paths to take | **Clarifying choice**: one button per option, each with a line of context | +| the content itself, before it's sent | **Edit before send**: a modal pre-filled with the draft | +| a sign-off from someone else | **Request to an approver**: a message to the approver, with the outcome sent back to the requester | + +### Approval gate + +- **Preview exactly what will happen**, so approval is an informed choice: the message that will be + posted, the issue that will be filed, the recipients. Use a `section` with `fields` for + key/value details, a `card` for a single entity, or a `rich_text` quote for draft text. +- **State the action and its scope in the first line**: "Send this summary to #eng (212 members)?". Not "Ready to proceed?" or "Confirm this action". +- **Describe the target by name, not by ID**: "Delete the canvas Q3 planning", not "Delete + `F0123ABC`". Let each tool supply its own preview text when it knows the human-readable names, + and fall back to a generic description built from the arguments only when it doesn't. +- **Use specific verbs on the buttons**: "Send Summary", "Edit", "Cancel". Mark only the + approving button `primary`. If the main action is destructive, mark it `danger` and add a + `confirm` dialog. Leave Reject or Cancel unstyled: declining is the safe choice, and a red + button suggests it's the dangerous one. +- **Offer a way to change it, not just yes or no.** An Edit button that opens a pre-filled modal + (see **Edit before send**) prevents a reject-and-retry loop. + +### Approval set + +When an agent proposes several actions ("Create these 5 issues", "Send these 3 replies"), put them +in one message rather than one message per item. Slack's guidance is to batch related +notifications. + +- **List every item with enough detail to judge it**, one item per line: a `section` per item + with the key details in `fields` for a handful of items, or a `table` for many items with the + same columns. +- **Let the user choose which items to approve.** Two layouts work well: + - **Select, then approve once** (best for 2–10 items): a `checkboxes` element with one option per + item, every item checked by default (`initial_options`), followed by an `actions` block with + "Approve Selected" (`primary`) and "Cancel". Each checkbox change sends its own `block_actions` + payload, which the handler can just acknowledge. Read the final selection from `state.values` + in the button's payload. + - **Decide per item**: a `section` per item with an `overflow` accessory (Approve, Skip, Edit), + or a `data_table` with an `action_cell` button per row, plus "Approve All Remaining" at the + end. Update the item's line in place as each decision comes in. +- **Show the totals in the button and the fallback**: "Approve 4 of 5", and `text` "5 issues + ready to create, approval needed". +- **After the decision, replace the controls with a record** of what was approved and what was + skipped (see **Close the loop** below), so the message records exactly what was approved. + +A minimal "select, then approve once" layout: + +```json +{ + "text": "3 Linear issues ready to create, approval needed", + "blocks": [ + { + "type": "section", + "text": { "type": "mrkdwn", "text": "*I found 3 action items in this thread.* Choose which to create as Linear issues in *Platform*:" } + }, + { + "type": "actions", + "block_id": "issue_selection", + "elements": [ + { + "type": "checkboxes", + "action_id": "selected_issues", + "options": [ + { "text": { "type": "mrkdwn", "text": "*Fix flaky deploy health check*" }, "description": { "type": "plain_text", "text": "Assignee: Priya · Priority: High" }, "value": "item_1" }, + { "text": { "type": "mrkdwn", "text": "*Add retry to webhook sender*" }, "description": { "type": "plain_text", "text": "Assignee: Sam · Priority: Medium" }, "value": "item_2" }, + { "text": { "type": "mrkdwn", "text": "*Update the runbook link*" }, "description": { "type": "plain_text", "text": "Unassigned · Priority: Low" }, "value": "item_3" } + ], + "initial_options": [ + { "text": { "type": "mrkdwn", "text": "*Fix flaky deploy health check*" }, "description": { "type": "plain_text", "text": "Assignee: Priya · Priority: High" }, "value": "item_1" }, + { "text": { "type": "mrkdwn", "text": "*Add retry to webhook sender*" }, "description": { "type": "plain_text", "text": "Assignee: Sam · Priority: Medium" }, "value": "item_2" }, + { "text": { "type": "mrkdwn", "text": "*Update the runbook link*" }, "description": { "type": "plain_text", "text": "Unassigned · Priority: Low" }, "value": "item_3" } + ] + } + ] + }, + { + "type": "actions", + "block_id": "issue_decision", + "elements": [ + { "type": "button", "action_id": "create_selected_issues", "text": { "type": "plain_text", "text": "Create Selected Issues" }, "style": "primary", "value": "batch_42" }, + { "type": "button", "action_id": "cancel_issue_batch", "text": { "type": "plain_text", "text": "Cancel" }, "value": "batch_42" } + ] + }, + { + "type": "context", + "elements": [ { "type": "mrkdwn", "text": "Issues will be created as you, <@U0123456789>" } ] + } + ] +} +``` + +### Clarifying choice + +- **Offer two to four concrete options as buttons**, each labeled with what the agent will do: + "Summarize Last Week", "Summarize Since Incident". Add a line of context for each in the + `section` above (or use a `radio_buttons` element when the options need descriptions). +- **Include a way out**: "Something Else" opens a short modal or invites a reply in the thread. +- **Don't emphasize any option** unless one is clearly the recommended default. + +### Edit before send + +- **Open a modal pre-filled with the draft** (`initial_value` on a `plain_text_input` or + `rich_text_input`) from the Edit button. Name the submit label after the action ("Send Summary"), so editing and approving happen in one step. +- **Show the edited version in the message once it's sent**, so the record reflects what went out + and not the original draft. + +### Request to an approver + +When the person who approves isn't the person who asked (expense sign-off, access requests, +deploy gates): + +- **Send the request where the approver will act on it**: a DM to a named approver, or a post in an + approvals channel for a group. Give the requester a separate message showing that the request is + pending. +- **Name the requester and the reason up front**: "<@U123> requests prod database access for + INC-482". Put supporting details in `fields`. +- **Record each approval in place** for N-of-M sign-offs: a `context` line such as "Approved by + <@U234> · 1 of 2 needed", updated as each approver responds. +- **Send the outcome back to the requester**, whichever way the decision went, and include the + approver's reason when rejecting. + +## Close the loop + +- **Replace the controls once a decision is made.** Update the message (`chat.update`, or + `replace_original` via `response_url`) so the `actions` block becomes a `context` line: "Created + 2 of 3 issues · Approved by <@U123> · 10:42". Buttons that stay up after the decision invite + duplicate clicks. For a declined action, keep the preview but strike it through, followed by the + outcome: `~Delete the canvas Q3 planning~ Rejected, I won't run it.` +- **Give every request a way to end without an answer.** An agent waiting on approval holds up the + whole run. Every pending approval should settle exactly once, in one of these ways: + + | Ending | What happens | Message becomes | + |---|---|---| + | approved | the action runs | "Approved, running it now", then the result | + | rejected | the action is skipped | "Rejected, I won't run it." | + | timed out (minutes for an agent's in-run gate, longer for a human sign-off) | the action is skipped | "Timed out, I didn't run it." | + | run stopped | the action is skipped | "Cancelled, the request was stopped." | + +- **Show the result, not just the decision.** Link to what was created or sent. If an item failed + after approval, say which one and why. +- **Tell everyone else who saw the request.** In a channel, update the original message rather + than replying with a new one, so nobody approves something that was already handled. +- **Expire stale requests.** If the decision no longer matters (the deploy window passed, the + draft was replaced), update the message to say so and remove the buttons. A `response_url` only + works for 30 minutes (up to 5 uses), so use `chat.update` for decisions that may take longer. + +## Make approvals safe + +These are handler responsibilities, but the layout has to support them: + +- **When in doubt, don't run it.** If the approval prompt fails to post, the request times out, or + the run is cancelled, treat it as a rejection. An unanswered gate must never become a yes. +- **Check who clicked.** Anyone who can see a message can click its buttons. Check that the + `user.id` in the interaction payload is allowed to approve, and if not, respond with an + ephemeral message ("Only <@U234> can approve this request") without changing the original. +- **Make the decision idempotent.** Two approvers, or one double-click, can send two payloads. + Put a unique request ID in the button's `value` (or `private_metadata` in a modal), settle that + ID once, and ignore later clicks, including ones that arrive after a timeout. +- **Approve exactly what was shown.** If the proposal changes, post or update it with a new + `block_id`, so a click on the old version can be recognized and rejected. +- **Show whose identity the action uses**: "Will be sent as you" or "Posted by the app on behalf + of <@U123>", in a `context` block next to the actions. +- **Use ephemeral messages for personal approvals in a shared channel**, so other members don't + see or click them. Use `response_type: "ephemeral"` via `response_url`, or `chat.postEphemeral`. + +## Earn trust over time + +- **Offer Undo after reversible actions** that ran without a gate: a "Created LIN-204 · Undo" + `context` line, or a button that expires after a short window. +- **Offer "Always Allow" for a class of action** once the user has approved it a few times, as a + secondary button next to the main approval ("Approve" and "Always Allow in #eng"). Honor it, and + give users a place to revoke it, such as the App Home. +- **Let users review what the agent did on their behalf**, especially for asynchronous or bulk + work. An App Home log of recent actions works well for this. + +## Quick self-review + +1. Does this action need a gate, and does the gate match the stakes? +2. Does the preview show exactly what will happen, with the action and scope in the first line? +3. Are the buttons specific verbs, with one `primary`, and is there a way to edit rather than only + reject? +4. For several items, is it one message where the user can approve some and not others? +5. After the decision, are the controls replaced by a record of what happened? +6. Does every request end, by timeout or cancellation if not by a click, and does that ending + default to not running the action? +7. Does the handler check who clicked, ignore duplicate clicks, and reject clicks on outdated + versions? diff --git a/.agents/skills/block-kit/references/modal-design.md b/.agents/skills/block-kit/references/modal-design.md new file mode 100644 index 0000000..ac8df87 --- /dev/null +++ b/.agents/skills/block-kit/references/modal-design.md @@ -0,0 +1,150 @@ +# Modal and Form Design + +Guidance on modals and forms that are quick to fill in and hard to get wrong. Like +`design-principles.md`, this covers _appropriateness_, not validity: `blocks.validate` tells you +whether a view parses, and this tells you whether it works for the person filling it in. For the +view object's fields and the full modal lifecycle, see `https://docs.slack.dev/surfaces/modals.md` +and `https://docs.slack.dev/reference/views/modal-views.md`. Apply these principles unless the +developer explicitly asks otherwise. + +## Decide whether it should be a modal at all + +A modal interrupts the user. Use one only for short, focused work that the user started: + +- **Use a modal** to collect structured input (a form), to confirm a consequential action with + more context than a `confirm` dialog can hold, or to show details on demand. +- **Use a message** for a decision one or two buttons can capture (Approve / Reject). A modal + adds a click and hides the decision from everyone else in the channel. +- **Use the App Home** for persistent settings or a dashboard the user returns to. Modals are + short-lived and their state is lost when they close. +- **Never open a modal the user didn't ask for.** A modal needs a `trigger_id` from the user's + own interaction, and that trigger expires after 3 seconds. Open the modal right away, and show a + loading view if the data isn't ready yet (see **Loading, success, and failure** below). +- **Never ask for passwords or other credentials.** Send the user to your own sign-in flow. + +## Frame the modal + +- **Title says what the form is**, in 24 characters or fewer: "New incident", "Request time off". + Leave out the app name; Slack already shows it. +- **Submit label is the outcome, as a verb**: "Create Incident", "Send Request", "Save". Never + "Submit" or "OK" when a specific verb fits. It is limited to 24 characters, and `submit` is + required whenever the view contains an `input` block. +- **Close label is "Cancel"** unless closing does something other than discard the form. Use + "Done" for a modal that only shows information, and "Save" (never "Done") for one that commits + changes. +- **Let Submit be the only emphasized button.** Slack renders it as the modal's main action, so + leave buttons inside the view's blocks unstyled (or `danger` for a destructive one). +- **Say what submitting will do** when it isn't obvious from the label, especially if it sends + something on the user's behalf: "This sends a message to #incidents and pages the on-call + engineer." Put it in a + `context` block just above the inputs, or in the modal's first `section`. +- **Lead with a short `section`** only when the user needs instructions. A form whose labels are + clear doesn't need a paragraph introducing it. + +## Inputs + +Each `input` block holds one field: a label, an element, and optionally a hint. + +- **Every input gets a label that names the value**, in sentence case: "Due date", "Affected + service". Not a question, and not "Please enter…". +- **Use `hint` for constraints and format** ("Use the service's PagerDuty name"). It stays visible + below the field. Use `placeholder` only for an example value ("Ex. api-gateway"). Placeholders + disappear as soon as the user starts typing, so they must never carry instructions the user + needs. +- **Mark optional fields as `optional: true`** rather than putting "(optional)" in the label. + Inputs are required by default, so think about each field: if your handler can work without it, + make it optional. +- **Pre-fill what you already know** with `initial_value`, `initial_option(s)`, `initial_date`, + `initial_user`, or `initial_conversation`. Reviewing a pre-filled value is faster than typing + it. For a conversation picker opened from a channel, set `default_to_current_conversation`. +- **Put `focus_on_load` on the first field** the user should fill in (at most one per view). +- **Pick the element that constrains the answer** so you don't have to validate free text: + + | The answer is… | Use | + |---|---| + | one of 2–5 visible choices | `radio_buttons` | + | one of many | `static_select` (up to 100 options), or `external_select` for a large or live list | + | several from a list | `checkboxes` (up to 10 options) or `multi_static_select` | + | a person, channel, or conversation | `users_select`, `conversations_select` (and multi variants) | + | a date, time, or both | `datepicker`, `timepicker`, `datetimepicker` | + | a number, email, or URL | `number_input`, `email_input`, `url_input` | + | short or long free text | `plain_text_input` (`multiline: true` for long text, `max_length` to cap it) | + | formatted text | `rich_text_input` | + | a file | `file_input` | + +- **Order fields the way the user thinks about the task**: the most important or identifying + field first ("Title"), details after, optional fields last. + +## Keep it short + +- **Ask only for what you need now.** Every field costs the user time. Slack's guidance is to + split the form once it reaches about six inputs. +- **Split a long form into steps** with `response_action: "push"` (or `views.push` from a button + inside the modal). A modal holds at most 3 views in its stack, so plan for no more than three + steps. Carry earlier answers forward in `private_metadata` (up to 3,000 characters), not in + hidden fields. +- **Use `views.update` to show or hide dependent fields** in place. Set `dispatch_action: true` + on the controlling input so changing it sends a `block_actions` payload, then update the view. + Keep the same `block_id` and `action_id` on every input so the user's entries are kept, and pass + the payload's `hash` so a stale update can't overwrite a newer one. +- **Don't push a view for something that fits in the current one.** Each pushed view is another + screen the user has to get through, and another Cancel that might send them back. + +## Validation and errors + +- **Validate on submit and respond with `response_action: "errors"`**, keyed by the input's + `block_id`: `{ "response_action": "errors", "errors": { "due_date": "Pick a date in the future" } }`. + The error appears under that field and the modal stays open with everything the user entered. + You have 3 seconds to respond. +- **Write errors that say how to fix the problem**: "Pick a date in the future", not "Invalid + date". Don't just repeat the label. +- **Don't blame the user or apologize.** "This email address doesn't look quite right", not "You + entered an invalid email address" or "Sorry, that's invalid". "You don't have permission…" is + fine. +- **Show every field error at once**, not one per submit. +- **Constrain input before you validate it.** A `datepicker`, `number_input` with `min_value`, or + a select prevents errors that a free-text field would need a message for. +- **For a problem with the whole form**, not one field (for example "That incident was already + closed"), update the view with `response_action: "update"` and put an `alert` block at the top + with `level: "error"`. `alert` is available only in modals. + +## Loading, success, and failure + +- **For slow work, open the modal first with a loading view.** Show a short `section` such as + "Loading your projects…", then fill it in with `views.update` when the data arrives. Don't + hold the `trigger_id` while you fetch data: it expires after 3 seconds. +- **For slow submissions**, acknowledge with `response_action: "update"` to a "Creating + incident…" view, do the work, then `views.update` that view to the result. +- **Confirm what happened after submit.** Either close the modal and post the result where the + user will see it (an ephemeral message, a DM, or the thread the flow started in, with a link to + what was created), or update the modal to a success view with an `alert` at `level: "success"` + and a link. Don't close silently. +- **When submission fails on your side**, keep the user's input. Return `errors` or an `update` + with an `alert` that says what went wrong and what to try next. Never close the modal and + throw the form away. +- **Close the whole stack when the flow is done** with `response_action: "clear"`, so the user + doesn't land back on an earlier step of a form they already finished. +- **Handle Cancel gracefully.** Set `notify_on_close: true` if you need to clean up (release a + lock, delete a draft). Don't reopen the modal or nag the user to finish. + +## Destructive and consequential actions + +- **Use a `confirm` dialog** on a button for a single irreversible action. Keep its title to the + action, with no end punctuation ("Delete incident"), its text to the consequence, and its confirm label to the + verb ("Delete"). Set `style: "danger"` on the confirm dialog itself. +- **Use a review view instead** when the user needs to see what will happen before confirming, + such as a bulk change, a message that will be posted, or anything that sends on their behalf. + Push a view that summarizes the result, with the Submit label stating the action ("Send to 42 People"). + +## Quick self-review + +Before handing back a modal, check: + +1. Is a modal the right surface, and does the title say what the form is in 24 characters or + fewer? +2. Does the Submit label name the outcome, and is it clear what submitting will do? +3. Does every input have a clear label, constraints in `hint` (not `placeholder`), and the right + `optional` setting? +4. Are known values pre-filled, and does the element limit the possible answers wherever it can? +5. Is the form six inputs or fewer per view, and three views or fewer in the stack? +6. What does the user see while loading, on a validation error, on success, and on failure? diff --git a/.agents/skills/create-slack-app/SKILL.md b/.agents/skills/create-slack-app/SKILL.md new file mode 100644 index 0000000..7b28854 --- /dev/null +++ b/.agents/skills/create-slack-app/SKILL.md @@ -0,0 +1,274 @@ +--- +name: create-slack-app +description: 'Use when a developer wants to create, scaffold, or bootstrap a new Slack app or agent from scratch with the Slack CLI, or scaffold the project for a new app just created in App Settings (`--app`, `--template`, `--team`). Covers prerequisites, authentication, choosing a workspace to install into, and creating a project from a Bolt (JS or Python) template locally. Trigger on "create a Slack app", "new Bolt app", "start a Slack agent".' +argument-hint: "[bolt-js | bolt-python]" +--- + +# Create Slack App + +Help the developer create a Slack app or agent using Bolt. If `$0` is exactly `bolt-js` or `bolt-python`, treat it as the chosen framework and skip asking. Otherwise (including if it's empty or any other value), ignore it and ask the developer which framework they want before continuing. + +This skill walks through the full setup: prerequisites, authentication, choosing a workspace to install into, project scaffolding from a template, and running the app locally. + +## Existing App from App Settings + +The developer may already have created and installed the app in App Settings, which hands off with arguments in the developer's message, for example `--app A0123456789 --template slack-samples/bolt-js-starter-agent --team T0123456789`. The agent setup prompt passes them along, after turning the App Settings template name into a template repo: + +| Argument | Meaning | Accept only | +|----------|---------|-------------| +| `--app` | The existing app's ID | `A` followed by uppercase letters and digits | +| `--template` | The template repo to create the project from | `org/repo`, each part letters, digits, dots, hyphens, and underscores | +| `--team` | The workspace (or Enterprise org) the app is installed in | `T` or `E` followed by uppercase letters and digits | +| `--subdir` (optional) | The template subdirectory to use | lowercase letters, digits, and hyphens | + +When `--app` is present, follow this skill as an **existing app**. The app ID, template, and team are already decided, so do not ask about them again. The framework is the template's language: `bolt-js` for a `slack-samples/bolt-js-*` repo and `bolt-python` for `slack-samples/bolt-python-*`, so do not ask for it either. Each step below says what changes. Check every value against the table before putting it in a command. If a value doesn't match, or `--app` comes without `--template` and `--team`, tell the developer which value is wrong and ask for it rather than guessing. + +--- + +## Step 1: Check Prerequisites + +### 1a. Detect the Slack CLI command + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public Slack CLI is installed and resolve its command name. Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. The fingerprint check, alias fallback, and install instructions all live there; do not duplicate them here. + +Once resolved, use the detected command name for **all** CLI commands throughout the rest of this skill. We refer to it as `SLACK_CMD` below — substitute the actual resolved command name everywhere you see `SLACK_CMD`. + +### 1b. Verify the CLI version + +Run `SLACK_CMD version` and print the version to confirm everything is working before continuing. + +### 1c. Check language runtime + +- **If `$0` is `bolt-js`**: Run `node --version` to verify Node.js is installed (v18+ required). If not installed, suggest `brew install node` or point to . +- **If `$0` is `bolt-python`**: Run `python3 --version` to verify Python is installed (3.6+ required). If not installed, suggest `brew install python3` or point to . + +--- + +## Step 2: Authenticate with the Slack CLI + +Use the `slack-cli` skill — **Step 5: Authentication (`slack auth`)** — to check the developer's auth status and walk them through `SLACK_CMD login` if they're not already authenticated. + +Wait for confirmation that authentication succeeded before proceeding. + +**Existing app:** the CLI must be logged in to the team from `--team`. Check that `SLACK_CMD auth list` shows that team ID. If it doesn't, log in to that workspace with the same flow. + +--- + +## Step 3: Choose Where to Install the App + +**Existing app:** skip this step. The app is already installed in the team from `--team`. + +The app needs a Slack workspace to install into. Three targets work and they are not equivalent. Use AskUserQuestion to let the developer pick, presenting them in this order: + +| Target | Best for | Cost of entry | +|--------|----------|---------------| +| **Developer sandbox** (recommended) | Anything the developer plans to keep building on. A free Enterprise Grid org isolated from real users, so org-level features are testable. | Needs a Slack Developer Program account, which is free to join. Every account can create a basic sandbox, with no paid plan or payment method. | +| **Free Team** (second choice) | Starting right now, when Developer Program signup is the thing in the way. A free workspace the developer creates and owns. | Capped at 10 apps per workspace, and no Enterprise Grid org features. | +| **Existing production workspace** (last resort) | Only when the app must reach real data or real coworkers. | Usually gated by admin approval, and the developer may not be the admin. | + +Then follow the matching sub-step below. Whichever target they pick, authentication is the same Step 2 flow: the `/slackauthticket` command works in any workspace the developer belongs to, so there is no sandbox-specific login. + +Whichever sub-step you follow, wait for confirmation that a target workspace exists and is authenticated before proceeding. + +### 3a. Developer sandbox (recommended) + +List existing sandboxes. Pass `--team` so the CLI does not stop to ask which authentication to use (get the team ID from `SLACK_CMD auth list`): + +```bash +SLACK_CMD sandbox list --team +``` + +**If the developer has no Developer Program account**, `sandbox list` returns nothing useful, because sandboxes belong to the developer program account whose email matches the authenticated user rather than to the workspace. If they say they do have an account, check that the email they are logged in with matches it before sending them to sign up, and log into a workspace under that email if not. Point them at , and offer the Free Team path in 3b as a way to start building now rather than waiting on signup. + +- **If a sandbox exists**: Show it and confirm they want to use it. +- **If no sandbox exists**: Create one. Ask the developer for a name and a password with AskUserQuestion, then run: + + ```bash + SLACK_CMD sandbox create --team --name --password + ``` + + **Important**: the password is a credential. Do NOT echo it, restate it, or write it into a summary. Pass it straight to the command, the same rule Step 4c applies to API keys. + + Sandboxes can also be created in the browser at . + +Once the sandbox exists, have the developer log into it with the Step 2 flow before continuing. + +**Basic sandboxes.** A developer who is not on a paid plan and has not added a payment method gets a basic sandbox. It works for everything this skill builds, with stricter limits: it is archived after 1 month of inactivity, has no Slack Connect, and does not support deploying apps to Slack infrastructure (ROSI). If the developer needs more, they can add a payment method (they are not charged) or join a paid plan, then upgrade the sandbox from without losing their apps or data. Limits are listed at . + +### 3b. Free Team (second choice) + +A Free Team is an ordinary Slack workspace on the free plan. The developer creates one at , then logs into it with the Step 2 flow. + +What to tell them: + +- Everything this skill builds works there. Bolt apps install and run fine on the free plan. +- The workspace is capped at **10 apps**. Past that the CLI reports `service_limits_exceeded`. +- **It is a standalone workspace, not an Enterprise Grid org**, unlike a developer sandbox. Anything org-level is therefore untestable: org-wide app installs and org-level app grants, the `admin.*` API methods (which need Business+ or Enterprise Grid), and multi-workspace behaviour generally. If the app targets those, use a sandbox instead. +- Do not invite coworkers into it. A Free Team with real users in it is a production workspace for the purposes of 3c. + +### 3c. Existing production workspace (last resort) + +Only when the app genuinely needs real data or real users. Warn the developer before they log in: + +- **Admin app approval (AAA) is likely to block the install.** It is always on for Enterprise Grid organizations and can be switched on in standalone workspaces. When it applies, the install in Step 5 stops and asks whether to request approval, and then the developer waits on an admin. +- To send that request without the prompt, set `SLACK_AUTO_REQUEST_AAA=1` in the environment. It is an environment variable, not a CLI flag. +- If approval is denied or slow, fall back to 3a or 3b instead of fighting it. + +--- + +## Step 4: Create the App from a Template + +Ask the developer what kind of app they want to build. Present the available templates based on their chosen framework (`$0`): + +### bolt-js templates + +| Template | Repo | Description | +|----------|------|-------------| +| Starter Template | `slack-samples/bolt-js-starter-template` | Basic Bolt JS app — great starting point | +| Starter Agent | `slack-samples/bolt-js-starter-agent` | Minimal AI agent using Claude/OpenAI | +| Support Agent | `slack-samples/bolt-js-support-agent` | AI-powered IT helpdesk agent | +| Getting Started | `slack-samples/bolt-js-getting-started-app` | Official getting started tutorial app | +| Examples | `slack-samples/bolt-js-examples` | Unified showcase of Slack features | + +### bolt-python templates + +| Template | Repo | Description | +|----------|------|-------------| +| Starter Template | `slack-samples/bolt-python-starter-template` | Basic Bolt Python app — great starting point | +| Starter Agent | `slack-samples/bolt-python-starter-agent` | Minimal AI agent using Claude/OpenAI/Pydantic AI | +| Support Agent | `slack-samples/bolt-python-support-agent` | AI-powered IT helpdesk agent | +| Assistant Template | `slack-samples/bolt-python-assistant-template` | Agents & Assistants template | +| Examples | `slack-samples/bolt-python-examples` | Unified showcase of Slack features | + +Use AskUserQuestion to let the developer pick a template. Recommend the **Starter Template** for first-timers or the **Starter Agent** if they want to build an AI agent. + +**Existing app:** do not ask which template. Use the repo from `--template`. + +### 4a. Choose an AI provider (agent templates only) + +If the developer picks **Starter Agent** or **Support Agent**, these templates contain subdirectories for different AI providers. Ask the developer which provider they want to use via AskUserQuestion, offering only the subdirectories for their framework (`$0`) from the tables below. + +The provider list depends on the framework, so the framework must be settled before you ask. If it isn't yet, ask for the framework first and wait for the answer. Do not batch the framework and provider questions into one AskUserQuestion call. + +**bolt-js subdirectories:** + +| Subdir | Description | +|--------|-------------| +| `claude-agent-sdk` | Uses Anthropic's Claude Agent SDK | +| `openai-agents-sdk` | Uses OpenAI's Agents SDK | + +**bolt-python subdirectories:** + +| Subdir | Description | +|--------|-------------| +| `claude-agent-sdk` | Uses Anthropic's Claude Agent SDK | +| `openai-agents-sdk` | Uses OpenAI's Agents SDK | +| `pydantic-ai` | Uses Pydantic AI (supports multiple LLM backends) | + +Recommend **Claude Agent SDK** as the default option. + +**Existing app:** the same rule applies when `--template` is a Starter Agent or Support Agent repo. If `--subdir` was given, use it and skip the question. + +### 4b. Name and create the project + +Ask what they want to name their project (suggest a default like `my-slack-app`), then run: + +**For templates WITHOUT subdirectories** (Starter Template, Getting Started, Assistant Template, Examples): + +```bash +SLACK_CMD create -t +``` + +**For agent templates WITH subdirectories** (Starter Agent, Support Agent): + +```bash +SLACK_CMD create -t --subdir +``` + +For example: + +```bash +# Non-agent template +SLACK_CMD create my-slack-app -t slack-samples/bolt-js-starter-template + +# Agent template with provider subdir +SLACK_CMD create my-slack-agent -t slack-samples/bolt-js-starter-agent --subdir claude-agent-sdk +``` + +**Existing app:** link the project to the app instead of creating a new one. Add `--app`, `--team`, and `--environment local`, and `--subdir` for agent templates: + +```bash +SLACK_CMD create -t [--subdir ] --app --team --environment local +``` + +For example: + +```bash +SLACK_CMD create my-slack-agent -t slack-samples/bolt-js-starter-agent --subdir claude-agent-sdk --app A0123456789 --team T0123456789 --environment local +``` + +The CLI saves the app ID to the project's local environment and updates the project's manifest to match the app in App Settings, so keep the scopes and events the developer picked there. Don't change the manifest back to the template's. + +If `SLACK_CMD create` fails with `invalid_app_id`, the CLI has created the project folder but not linked the app, so stop before Step 5. Tell the developer that the app ID and team don't match a workspace they are logged in to, delete the new project folder, and ask them to check both values in App Settings. + +Confirm the project was created successfully by checking that the directory exists and listing its contents. + +### 4c. Set required environment variables (agent templates only) + +If the developer chose an agent template (Starter Agent or Support Agent), they need to set the required API key for their chosen AI provider. Ask for the key value using AskUserQuestion, then set it using the Slack CLI from within the project directory. + +**Required environment variables by provider:** + +| Provider | Env Variable | Description | +|----------|-------------|-------------| +| `claude-agent-sdk` | `ANTHROPIC_API_KEY` | Anthropic API key | +| `openai-agents-sdk` | `OPENAI_API_KEY` | OpenAI API key | +| `pydantic-ai` | `OPENAI_API_KEY` | OpenAI API key (required). Optionally also `ANTHROPIC_API_KEY` if using Anthropic as the backend — if both are set, Anthropic is used by default. | + +Use AskUserQuestion to ask the developer for their API key value(s). Then set each one: + +```bash +cd && SLACK_CMD env set +``` + +For example: + +```bash +cd my-slack-agent && SLACK_CMD env set ANTHROPIC_API_KEY sk-ant-... +``` + +**Important**: Do NOT store or echo API key values in logs or output. Only pass them directly to `SLACK_CMD env set`. + +--- + +## Step 5: Run the App Locally + +Use the `slack-cli` skill — **Step 6: Running an App Locally (`slack run`)** — to resolve the app or team target and start the dev server in the background. + +Tell the developer their app is now running and installed in the workspace they chose in Step 3, and that file changes will auto-reload it. + +**Existing app:** the app runs as the app from `--app`, in the team from `--team`, so the developer can try it where App Settings installed it. + +If the install stops on an admin approval request, they picked a workspace with AAA turned on: see Step 3c for the options. + +--- + +## Step 6: Next Steps + +After the app is running, suggest next steps: + +1. **Explore the code**: Read through the project files together — offer to explain the app structure, manifest, listeners, etc. +2. **Make a change**: Suggest a small modification (like changing a message response) to see hot-reload in action. +3. **Add features**: Based on the template, suggest relevant Slack features to add (slash commands, events, modals, AI capabilities, etc.). For any Block Kit UI (a message layout, a modal, or a Home tab), use the `block-kit` skill rather than building the JSON here. +4. **Check the docs**: Point to for the full Slack Platform documentation. + +--- + +## Notes + +- `SLACK_CMD` is a placeholder — always substitute the actual command name resolved in Step 1a (typically `slack`, but may be an alias). +- This skill focuses on **Bolt for JavaScript** and **Bolt for Python** only. Do not suggest Deno, workflow apps, or `slack deploy` (hosted deployment). +- This skill scaffolds and runs the app. It does not own Block Kit JSON. If the developer asks to build or edit a message, modal, or Home tab layout (now or in Step 6), use the `block-kit` skill instead of writing the blocks here from memory. +- `SLACK_CMD sandbox create` prompts for a name and password only when those flags are missing. Supply `--team`, `--name`, and `--password` and it runs non-interactively, so you can run it yourself rather than handing it to the developer. `SLACK_CMD sandbox list` needs `--team` for the same reason: without it the CLI prompts for which authentication to use. +- Free Teams and developer sandboxes both support everything this skill builds. The CLI's `free_team_not_allowed` error is scoped to low-code workflow and function apps, which this skill does not create. +- If the developer hits issues, suggest `SLACK_CMD doctor` to diagnose their setup. diff --git a/.agents/skills/deploy-slack-app/SKILL.md b/.agents/skills/deploy-slack-app/SKILL.md new file mode 100644 index 0000000..d1d1ad1 --- /dev/null +++ b/.agents/skills/deploy-slack-app/SKILL.md @@ -0,0 +1,200 @@ +--- +name: deploy-slack-app +description: Use when a developer wants to deploy, host, or run a Slack app somewhere it keeps working after the local process stops, or mentions Railway, Heroku, `railway up`, `git push heroku`, `slack deploy`, a `deploy` hook in `.slack/hooks.json`, hosting a Socket Mode or Request URL (HTTP) Bolt app, deploying from Windows, graduating an app out of a developer sandbox, or tearing down a deployed app. +--- + +# Deploy Slack App + +Take a Slack app that already works locally and deploy it to a hosting provider as a separate Slack app, with its own app ID, that keeps running without the developer's machine. The local development app is unchanged, and **Step 5: Deploy** explains how the two coexist. This is the step after the `test-slack-app` skill confirms the app responds. + +The mechanism is the Slack CLI's `deploy` hook. Adding a `deploy` key to the project's `.slack/hooks.json` replaces Slack's own hosted deployment with a script of your choosing, and the CLI runs that script _after_ it has created and installed the deployed app. That ordering is the whole reason this approach is worth using: the app's bot and app-level tokens are already in the script's environment by the time it runs, so nothing here has to prompt for a secret or store one. + +Two supported providers, both running the app as a long-lived worker process: + +| Provider | Process type | Deploys from | Secrets | Current pricing | +| --- | --- | --- | --- | --- | +| Railway | Service, no port binding required | The working directory | Passed on stdin | | +| Heroku | `worker` dyno | A git push of committed code | Passed as arguments | | + +Railway is the better default, and the reasons are in **Step 2a: Choose a Provider**. + +--- + +## Step 1: Check Prerequisites + +### 1a. Detect the Slack CLI + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public Slack CLI is installed and resolve its command name. Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. The fingerprint check, alias fallback, and install instructions all live there; do not duplicate them. Refer to the resolved command as `SLACK_CMD` throughout. + +This matters more than it looks. Some machines have an unrelated internal tool named `slack` on the path, and running that instead produces confusing failures well into the deploy. + +### 1b. Confirm the App Uses Socket Mode + +**Read the app's manifest rather than asking.** The project already declares which mode it uses, so a question here is redundant. Check `manifest.json` for `settings.socket_mode_enabled`. If `.slack/config.json` sets the manifest source to `remote`, there is no local file, so read it with `SLACK_CMD manifest info` instead. + +- **Socket Mode enabled:** continue. The app opens an outbound websocket to Slack, needs no public URL, and binds no HTTP port. +- **Socket Mode disabled, or the app uses a Request URL:** **stop here.** This skill does not cover Request URL apps yet, because a hosted Request URL app also needs a public address captured after the deploy and written back into the app manifest. Tell the developer plainly that this is the gap, and that converting the app to Socket Mode is the supported path today. Support may have shipped in a newer version of the Slack Skills Plugin, so ask the developer to update the plugin and try again. If they are already on the latest version, point them to to add a reaction or comment. + +If the manifest is ambiguous, read the app's entrypoint. A Bolt for JavaScript app constructed with `socketMode: true` and an `appToken`, or a Bolt for Python app started through `SocketModeHandler`, is a Socket Mode app. + +### 1c. Confirm the Runtime Is Supported + +This flow is verified on macOS and Linux. The deploy hook is a shell script, so a Windows developer needs a PowerShell equivalent that does not exist yet. On Windows, say so rather than letting the deploy fail partway through. WSL is a workable path in the meantime. Support may have shipped in a newer version of the Slack Skills Plugin, so ask the developer to update the plugin and try again. If they are already on the latest version, point them to to add a reaction or comment. + +--- + +## Step 2: Choose a Provider and a Team + +Ask the developer two things the project cannot tell you: which provider to deploy to, and which Slack team to deploy into. + +### 2a. Choose a Provider + +Ask which provider, because cost is the thing the developer cannot infer from the project. Give the developer both pricing links from the table above so they can check current terms. **Do not fetch the pages or quote prices, plan names, or trial terms.** Providers change them often, and this skill can be installed long after it was written. + +What does not change with the price list, and is worth saying: + +- **Railway** is the default recommendation. It accepts secrets on stdin, so the tokens never appear in process arguments. It deploys the working directory, so a re-deploy needs no commit, and it needs no `Procfile`. +- **Heroku** fits when the developer already has an account, or a team standard that points there. It builds from git, so only committed code is deployed. Some accounts, including enterprise-managed ones, cannot own a personal app and must create it on a Heroku team. Personal apps and team apps can have different plans and billing, so ask which team to use rather than picking one: a shared team has a shared budget. + +Say plainly that **both providers keep the app running continuously**, which is what a Socket Mode app requires. Always-on hosting is a paid service in the end, so expect it to cost something once any trial runs out. + +Once the developer picks one, read that provider's reference file and follow it: `references/railway.md` or `references/heroku.md`. Each holds the install and authentication commands, the provider's own requirements for the project, and the environment variables its deploy script reads. **Step 4: Wire Up the Deploy Hook** works through them. + +### 2b. Choose a Team + +Run `SLACK_CMD auth list`. If it lists one team, use it. If it lists more than one, show the developer each team's name and ID and ask which one to deploy into. + +**Never pick the team yourself.** Do not assume the standalone workspace or the Enterprise org, and do not reuse the team from `.slack/apps.dev.json`, which is often a developer sandbox. A wrong guess installs the app into a team the developer did not intend, and a later deploy to the right team creates a second Slack app. + +--- + +## Step 3: Confirm It Works Locally First + +**Do not deploy an app that has not been seen working.** A broken deploy and a broken app look identical in a provider's logs, and separating them afterwards costs far more than checking first. + +Use the `test-slack-app` skill to run the app with `SLACK_CMD run` and exercise at least one real surface, so there is a known-good behaviour to re-check after the deploy. Note which surface was used: the same one is the check in **Step 6: Verify the Deployment**. + +--- + +## Step 4: Wire Up the Deploy Hook + +Three things to set up. **Check whether each already exists before writing it**, because re-deploying an app is the common case and clobbering a developer's edited script is not recoverable. + +### 4a. Prepare the Provider + +Work through the chosen provider's reference file before writing anything, because the deploy script only checks these and stops. It cannot fix them. + +- **Install and authenticate the provider's CLI.** Run its `whoami` check. Logging in opens a browser, so if the check fails, ask the developer to run the login command in their own terminal rather than running it yourself. +- **Settle the names and ownership with the developer.** For Heroku: a distinctive app name, and whether the app belongs to a team (`heroku teams`). For Railway: the workspace, if the account has more than one. These become environment variables on the deploy command in **Step 5: Deploy**. +- **Meet the provider's project requirements.** For Heroku, write the `Procfile` and commit it. For Railway, confirm the start command it will detect. + +### 4b. Write the Deploy Script + +Copy the provider's deploy script into the project's `.slack/` directory under the same name, then make it executable: + +- Railway: `references/deploy-railway.sh` to `.slack/deploy-railway.sh` +- Heroku: `references/deploy-heroku.sh` to `.slack/deploy-heroku.sh` + +For example, `chmod +x .slack/deploy-railway.sh`. + +Each script is self-contained. It validates that both tokens arrived, reads the deployed app ID from `.slack/apps.json` for its log line, and then runs the provider's preflight, provision, configure, and deploy steps in order. There is nothing else to copy. The CLI runs the hook from the project root, so the script's relative paths resolve there even though the file lives in `.slack/`. + +**If the script already exists**, show the developer that it is there and ask before overwriting. A developer may have adjusted it. + +### 4c. Register the Hook + +Add a `deploy` key inside the existing `hooks` object in `.slack/hooks.json`, pointing at the provider's script. For Railway: + +```json +"deploy": "./.slack/deploy-railway.sh" +``` + +For Heroku, the value is `./.slack/deploy-heroku.sh`. **Leave the `get-hooks` entry exactly as it is.** Its value differs between Bolt for JavaScript and Bolt for Python projects, so do not copy one from elsewhere. + +**If a `deploy` key is already present, do not add a second one.** A duplicate key produces invalid JSON, and the CLI will reject the project rather than deploy it. If the existing key already points at the chosen provider's script, leave it. If it points somewhere else, such as the other provider's script, show the developer and ask before changing it. + +--- + +## Step 5: Deploy + +Run `SLACK_CMD deploy` from the project root and watch the output. The CLI creates the deployed app, installs it, and then runs the hook script, so the first part of the output is app installation and the second is the provider's build. + +Four flags matter when running this outside an interactive terminal, which includes most agent sessions. The CLI asks four questions, and each one is fatal unanswered: a non-interactive shell gets `The input device is not a TTY or does not support interactivity` and nothing is deployed. + +- `--skip-update` stops the CLI pausing to offer an upgrade. +- `--team ` picks the workspace or organization. Use the team the developer chose in **Step 2b: Choose a Team**. +- `--app deployed` selects the deployed app environment, and creates that app on a first deploy. Without it the CLI asks the developer to choose between an existing app and a new one. This is the flag most easily missed, because the prompt it answers only appears on a project that has never been deployed. +- `--org-workspace-grant all` answers the workspace-grant prompt for an org-installed app. + +So the full command is `SLACK_CMD deploy --skip-update --team --app deployed --org-workspace-grant all`. + +Put any provider variables settled in **Step 4a: Prepare the Provider** in front of it. The hook inherits the CLI's environment, so this is how they reach the script: + +```sh +HEROKU_TEAM= HEROKU_APP_NAME= SLACK_CMD deploy --skip-update --team --app deployed --org-workspace-grant all +``` + +**The deployed app is a different app from the one `SLACK_CMD run` uses.** The CLI writes the deployed app to `.slack/apps.json` and the local development app to `.slack/apps.dev.json`, keyed by team. Both keep working independently, which is the intended design, not a mistake to correct. + +**Commit `.slack/apps.json` after the first deploy.** It holds app and team IDs, not secrets, and the project's `.slack/.gitignore` leaves it tracked on purpose. Committing it keeps every later deploy pointed at the same app. On Heroku it also stops the deploy script warning about uncommitted changes on each re-deploy. + +One consequence to warn the developer about: the two apps declare the same slash commands in the same workspace. Running `SLACK_CMD run` while the deployed app is live makes it ambiguous which one answers a slash command. Stop the local process when checking the deployed app, which **Step 6: Verify the Deployment** does anyway. + +--- + +## Step 6: Verify the Deployment + +Check all three of these. The first two can pass while the app is silent in Slack. + +### 6a. The Service Is Running + +Use the status and log commands from the provider's reference file. Look for the app's own startup logging and the Socket Mode websocket connecting. A build that succeeded and a process that then exited look very different here, so read the logs rather than trusting the build result. + +### 6b. The App Answers in Slack, With Nothing Running Locally + +**Stop the local process first.** This is the only check that proves the deployed app is doing the work rather than the developer's laptop. Exercise the surface noted in **Step 3: Confirm It Works Locally First**, and confirm the response appears in Slack and the corresponding request appears in the provider's logs. + +### 6c. Both Apps Are Distinct + +Show the developer the app ID in `.slack/apps.json` and the one in `.slack/apps.dev.json` and confirm they differ. Then confirm `SLACK_CMD run` still drives the development app. + +--- + +## Step 7: Re-deploy + +Shipping a change is the same `SLACK_CMD deploy` command, with the same flags as **Step 5: Deploy**. Everything in **Step 4: Wire Up the Deploy Hook** is already in place, so skip it and go straight to the deploy, and expect the same app rather than a second one. + +Two provider differences to know about, both handled by the deploy scripts: + +- **Railway** uploads the working directory and rebuilds every time, so no commit is needed. +- **Heroku** builds from a git push, so uncommitted changes are not deployed. A push with no new commit builds nothing, so the script restarts the dynos instead, which picks up any changed tokens. Commit code changes before re-deploying. + +If a re-deploy creates a second Slack app, the deployed app entry in `.slack/apps.json` was lost. Before deploying again, confirm `.slack/apps.json` has an entry for the `--team` ID, rather than deleting apps afterwards. + +--- + +## Step 8: Tear Down a Deployment + +Use this when the developer is done with the deployed app, for example after trying the skill out. It deletes the host's copy and the deployed Slack app, and leaves the development app alone. + +**Name every resource and ask once before deleting anything.** These deletes are permanent. Say which provider project or app goes, and which Slack app ID from `.slack/apps.json`, then wait for a yes. + +1. **Delete the provider's copy first**, so nothing is left holding a connection to Slack with tokens that are about to stop working. The commands are in the provider's reference file, under "Tearing down". +2. **Delete the deployed Slack app** with `SLACK_CMD app delete --team --app deployed --force`. Read the team ID from `.slack/apps.json`. `--force` skips the confirmation prompt, which would otherwise fail in a non-interactive shell. When it was the only deployed app, the CLI removes `.slack/apps.json` as well, so commit that deletion. +3. **Leave the development app** unless the developer asks for it too. It is the app `SLACK_CMD run` uses, and they will usually keep working on it. If they ask, the same command with `--app local` deletes it. + +Leave `.slack/hooks.json` and the deploy script in place, so a later `SLACK_CMD deploy` sets everything up again from the start. + +--- + +## Notes + +**Serverless providers cannot host a Socket Mode app.** A Socket Mode app is a process that stays resident and holds an outbound websocket open. Vercel, AWS Lambda, and similar platforms run per-request functions with a maximum duration and no always-on process type, so there is nothing for the websocket to live in. When a developer asks for one of these, explain the constraint rather than attempting it. Hosting a Slack app on a serverless platform means a Request URL app, which this skill does not cover yet. + +**Other providers.** When a developer asks about a provider this skill does not cover, the two things to check are whether it offers an always-on background worker process type and how that process is billed. + +**The token handoff is not a documented contract.** The Slack CLI does not pass the tokens to the deploy hook explicitly. It sets them on its own process during app installation, and the hook script inherits them because it runs later in that same process. It works, and it only works for apps with no Slack-hosted function runtime, which covers every Bolt app. That is why each deploy script checks for both tokens and stops with a readable message instead of assuming they are present. + +**Not `slack deploy` without a hook.** With no `deploy` key in `.slack/hooks.json`, `SLACK_CMD deploy` targets Slack's own hosted infrastructure, which is a different product for a different kind of app. The `slack-cli` skill covers the CLI's commands generally. + +**Building the app comes first.** If there is no app yet, start with the `create-slack-app` skill and come back here once it runs locally. diff --git a/.agents/skills/deploy-slack-app/references/deploy-heroku.sh b/.agents/skills/deploy-slack-app/references/deploy-heroku.sh new file mode 100755 index 0000000..91c711d --- /dev/null +++ b/.agents/skills/deploy-slack-app/references/deploy-heroku.sh @@ -0,0 +1,186 @@ +#!/usr/bin/env bash +# +# Deploy a Socket Mode Bolt app to Heroku, as a Slack CLI `deploy` hook. +# +# Installed as .slack/deploy-heroku.sh and registered as the `deploy` hook in +# .slack/hooks.json by the deploy-slack-app skill. The CLI runs it from the +# project root after installing the deployed app, so relative paths resolve +# there and SLACK_BOT_TOKEN and SLACK_APP_TOKEN are inherited from its +# environment. That handoff is not a documented contract, which is why the +# checks below exist. +# +# Supported on macOS and Linux. + +set -euo pipefail + +say() { printf '%s\n' "$*"; } +die() { printf 'error: %s\n' "$*" >&2; exit 1; } + +# The Heroku app name. When unset, reuse the app the `heroku` git remote already +# points at, so a re-deploy targets the same app even though an environment +# variable set on the first deploy is gone by the next one. The directory name +# is only the default for a first deploy. Heroku app names are global, so a +# generic one is often taken. +remote_app=$( + git remote get-url heroku 2>/dev/null \ + | sed -n 's#.*/\([^/]*\)\.git$#\1#p' \ + || true +) +HEROKU_APP_NAME="${HEROKU_APP_NAME:-${remote_app:-$(basename "$PWD")}}" + +# Set HEROKU_TEAM when the app has to belong to a Heroku team rather than to the +# account personally. Some accounts, including enterprise-managed ones, cannot +# own personal apps at all: `apps:create` refuses with "All apps must belong to +# a team. Create the app on a team instead." Leave empty for a personal app. +HEROKU_TEAM="${HEROKU_TEAM:-}" + +# --------------------------------------------------------------------------- +# 1. Preconditions +# --------------------------------------------------------------------------- + +# Both tokens are required. A Socket Mode app cannot open a websocket without an +# app-level token carrying connections:write, so a missing SLACK_APP_TOKEN is a +# hard stop rather than something to warn about and continue past. +[ -n "${SLACK_BOT_TOKEN:-}" ] || die \ + "SLACK_BOT_TOKEN is not set. It is normally supplied by 'slack deploy' during app install. If you are running this script directly, export it first." +[ -n "${SLACK_APP_TOKEN:-}" ] || die \ + "SLACK_APP_TOKEN is not set. Socket Mode needs an app-level token with connections:write. It is normally supplied by 'slack deploy' during app install." + +command -v heroku >/dev/null 2>&1 || die \ + "the heroku CLI is not installed. Install it with 'brew tap heroku/brew && brew install heroku' (macOS) or see https://devcenter.heroku.com/articles/heroku-cli, then re-run 'slack deploy'." +heroku auth:whoami >/dev/null 2>&1 || die \ + "the heroku CLI is not authenticated. Run 'heroku login' (or set HEROKU_API_KEY), then re-run 'slack deploy'." +git rev-parse --git-dir >/dev/null 2>&1 || die \ + "this project is not a git repository. Heroku builds from a git push, so run 'git init' and commit the project first." +# A project created inside another repository passes the check above on the +# parent's .git, and the push below would then deploy the parent's code. Compare +# physical paths, because macOS reports some directories through symlinks. +repo_root=$(cd "$(git rev-parse --show-toplevel)" && pwd -P) +[ "${repo_root}" = "$(pwd -P)" ] || die \ + "this project is inside another git repository (${repo_root}) rather than being its own. Heroku would deploy that repository's code instead of this app. Run 'git init' in the project directory and commit the project there." +git rev-parse --verify HEAD >/dev/null 2>&1 || die \ + "this repository has no commits yet. Heroku builds from a git push, so commit the project first." +[ -z "$(git status --porcelain)" ] || say \ + "warning: there are uncommitted or untracked changes. Heroku deploys committed code only, so those changes will not go live." +git ls-files --error-unmatch Procfile >/dev/null 2>&1 || die \ + "Procfile is missing or not committed. Heroku needs it to run this app as a worker rather than a web process. Create it with one line, such as 'worker: npm start' (Bolt for JavaScript) or 'worker: python app.py' (Bolt for Python), and commit it." + +# --------------------------------------------------------------------------- +# 2. Report which app is being deployed +# --------------------------------------------------------------------------- + +# The deploy hook receives no app ID, so read it off disk. .slack/apps.json holds +# deployed apps keyed by team ID; .slack/apps.dev.json holds the local dev app +# and is deliberately not touched here. +# +# Parsed with grep and sed rather than a language runtime: this script has to +# work in a Bolt for Python project as readily as a Bolt for JavaScript one. +app_id="unknown" +if [ -f .slack/apps.json ]; then + found=$( + tr -d '\n' < .slack/apps.json \ + | grep -o '"app_id"[[:space:]]*:[[:space:]]*"[^"]*"' \ + | sed 's/.*"\([^"]*\)"$/\1/' \ + | paste -sd , - \ + || true + ) + [ -n "${found}" ] && app_id="${found}" +fi + +say "Deploying Slack app ${app_id} to Heroku" + +# --------------------------------------------------------------------------- +# 3. Provision the Heroku app +# --------------------------------------------------------------------------- + +# apps:create fails outright when the app already exists, so check first. This +# is what lets a re-deploy target the same app instead of erroring. +# +# apps:info reports "Couldn't find that app" both for an app that does not exist +# and for one that exists under another account, because Heroku app names are +# globally unique across all of Heroku. A generic name taken by a stranger +# therefore reaches apps:create below and fails there on the name rather than +# here. Set HEROKU_APP_NAME to something distinctive to avoid it. +if heroku apps:info --app "${HEROKU_APP_NAME}" >/dev/null 2>&1; then + say "Reusing the Heroku app ${HEROKU_APP_NAME}" +else + say "Creating the Heroku app ${HEROKU_APP_NAME}" + if [ -n "${HEROKU_TEAM}" ]; then + heroku apps:create "${HEROKU_APP_NAME}" --team "${HEROKU_TEAM}" >/dev/null + else + heroku apps:create "${HEROKU_APP_NAME}" >/dev/null + fi +fi + +# Sets or resets the `heroku` git remote to point at this app. Safe to repeat. +heroku git:remote --app "${HEROKU_APP_NAME}" >/dev/null + +# --------------------------------------------------------------------------- +# 4. Configure secrets +# --------------------------------------------------------------------------- + +# heroku config:set takes values as arguments only, so these two tokens are +# visible to `ps` while the command runs. The Heroku CLI offers no alternative. +say "Setting SLACK_BOT_TOKEN and SLACK_APP_TOKEN on ${HEROKU_APP_NAME}" +heroku config:set \ + "SLACK_BOT_TOKEN=${SLACK_BOT_TOKEN}" \ + "SLACK_APP_TOKEN=${SLACK_APP_TOKEN}" \ + --app "${HEROKU_APP_NAME}" >/dev/null + +# --------------------------------------------------------------------------- +# 5. Deploy +# --------------------------------------------------------------------------- + +# Push the current HEAD to the app's main branch, whatever local branch the +# developer is on. The output is captured rather than piped so that a failed +# push is distinguishable from an up-to-date one. +# +# A push with no new commit reports "Everything up-to-date" and builds nothing. +# In that case the dynos are restarted below instead, which picks up any +# changed tokens. The code itself has not changed, so there is nothing to +# rebuild, and an empty commit would also sweep up anything the developer had +# staged. +say "Pushing to Heroku" +push_out=$(git push heroku HEAD:refs/heads/main 2>&1) \ + || die "the git push to Heroku failed: +${push_out}" +printf '%s\n' "${push_out}" + +up_to_date=false +if printf '%s' "${push_out}" | grep -q 'Everything up-to-date'; then + up_to_date=true +fi + +# Run exactly one worker and no web dyno, in one call. +# +# The Node buildpack adds a default `web` process type even though the Procfile +# only declares `worker`, and Heroku starts it on the first release. It runs the +# same start command, so it is a second copy of the app holding a second Socket +# Mode connection, stuck in a restart loop because it never binds $PORT, and +# billed as a second dyno. The worker's own logs look healthy throughout. +# +# The release starts it before this step can run, so for a few seconds after a +# first deploy both copies are connected. After this scale, web stays at 0 on +# every later release. +# +# The Python buildpack adds no `web` type, and scaling one that does not exist +# is an error, so only scale web when the formation has it. +formation=$(heroku ps:scale --app "${HEROKU_APP_NAME}" 2>/dev/null || true) +if printf '%s' "${formation}" | grep -qE '(^|[[:space:]])web='; then + say "Scaling the worker dyno to 1 and the web dyno to 0" + heroku ps:scale worker=1 web=0 --app "${HEROKU_APP_NAME}" +else + say "Scaling the worker dyno to 1" + heroku ps:scale worker=1 --app "${HEROKU_APP_NAME}" +fi + +if [ "${up_to_date}" = true ]; then + say "No new commit to deploy. Restarting the dynos to pick up the current config." + heroku ps:restart --app "${HEROKU_APP_NAME}" +fi + +say "" +say "Deployed. A successful build does not prove the app started, so check for" +say "the Socket Mode connection in the app's logs:" +say " heroku logs --num 100 --app ${HEROKU_APP_NAME}" +say " heroku ps --app ${HEROKU_APP_NAME}" diff --git a/.agents/skills/deploy-slack-app/references/deploy-railway.sh b/.agents/skills/deploy-slack-app/references/deploy-railway.sh new file mode 100755 index 0000000..140aade --- /dev/null +++ b/.agents/skills/deploy-slack-app/references/deploy-railway.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# +# Deploy a Socket Mode Bolt app to Railway, as a Slack CLI `deploy` hook. +# +# Installed as .slack/deploy-railway.sh and registered as the `deploy` hook in +# .slack/hooks.json by the deploy-slack-app skill. The CLI runs it from the +# project root after installing the deployed app, so relative paths resolve +# there and SLACK_BOT_TOKEN and SLACK_APP_TOKEN are inherited from its +# environment. That handoff is not a documented contract, which is why the +# checks below exist. +# +# Supported on macOS and Linux. + +set -euo pipefail + +say() { printf '%s\n' "$*"; } +die() { printf 'error: %s\n' "$*" >&2; exit 1; } + +RAILWAY_PROJECT_NAME="${RAILWAY_PROJECT_NAME:-$(basename "$PWD")}" +RAILWAY_SERVICE_NAME="${RAILWAY_SERVICE_NAME:-$(basename "$PWD")}" + +# Set RAILWAY_WORKSPACE when the account belongs to more than one workspace. +# `railway init` otherwise asks which one to use, and that prompt fails outside +# an interactive terminal. Only read when a new project is created. +RAILWAY_WORKSPACE="${RAILWAY_WORKSPACE:-}" + +# --------------------------------------------------------------------------- +# 1. Preconditions +# --------------------------------------------------------------------------- + +# Both tokens are required. A Socket Mode app cannot open a websocket without an +# app-level token carrying connections:write, so a missing SLACK_APP_TOKEN is a +# hard stop rather than something to warn about and continue past. +[ -n "${SLACK_BOT_TOKEN:-}" ] || die \ + "SLACK_BOT_TOKEN is not set. It is normally supplied by 'slack deploy' during app install. If you are running this script directly, export it first." +[ -n "${SLACK_APP_TOKEN:-}" ] || die \ + "SLACK_APP_TOKEN is not set. Socket Mode needs an app-level token with connections:write. It is normally supplied by 'slack deploy' during app install." + +command -v railway >/dev/null 2>&1 || die \ + "the railway CLI is not installed. Install it with 'brew install railway' (macOS) or see https://docs.railway.com/guides/cli, then re-run 'slack deploy'." +railway whoami >/dev/null 2>&1 || die \ + "the railway CLI is not authenticated. Run 'railway login' in a terminal (or export RAILWAY_API_TOKEN, an account token), then re-run 'slack deploy'." + +# --------------------------------------------------------------------------- +# 2. Report which app is being deployed +# --------------------------------------------------------------------------- + +# The deploy hook receives no app ID, so read it off disk. .slack/apps.json holds +# deployed apps keyed by team ID; .slack/apps.dev.json holds the local dev app +# and is deliberately not touched here. +# +# Parsed with grep and sed rather than a language runtime: this script has to +# work in a Bolt for Python project as readily as a Bolt for JavaScript one. +app_id="unknown" +if [ -f .slack/apps.json ]; then + found=$( + tr -d '\n' < .slack/apps.json \ + | grep -o '"app_id"[[:space:]]*:[[:space:]]*"[^"]*"' \ + | sed 's/.*"\([^"]*\)"$/\1/' \ + | paste -sd , - \ + || true + ) + [ -n "${found}" ] && app_id="${found}" +fi + +say "Deploying Slack app ${app_id} to Railway" + +# --------------------------------------------------------------------------- +# 3. Provision the Railway project and service +# --------------------------------------------------------------------------- + +# `railway status` fails when the directory is not linked to a project. Reusing +# an existing link is what makes a re-deploy update the same service instead of +# creating a second project on every run. The status is printed so a link to +# the wrong project is visible in the deploy output. +if status_out=$(railway status 2>&1); then + say "Reusing the Railway project already linked to this directory:" + printf '%s\n' "${status_out}" +else + say "No linked Railway project. Creating ${RAILWAY_PROJECT_NAME}" + if [ -n "${RAILWAY_WORKSPACE}" ]; then + railway init -n "${RAILWAY_PROJECT_NAME}" --workspace "${RAILWAY_WORKSPACE}" + else + railway init -n "${RAILWAY_PROJECT_NAME}" + fi +fi + +# A fresh `railway init` leaves the project with no service at all, and every +# variable command fails with "Project has no services" until one exists. So +# create the service explicitly before setting anything on it. +# +# `railway add -s NAME` on its own still prompts ("Enter a variable") and hangs +# in a non-interactive shell even though the name was supplied. Passing +# --variables answers that prompt. The value here is a harmless marker, not a +# secret: the two tokens go over stdin below, never on a command line. +if railway variable list --service "${RAILWAY_SERVICE_NAME}" >/dev/null 2>&1; then + say "Reusing the Railway service ${RAILWAY_SERVICE_NAME}" +else + say "Creating the Railway service ${RAILWAY_SERVICE_NAME}" + railway add --service "${RAILWAY_SERVICE_NAME}" --variables "SLACK_DEPLOY_HOOK=1" >/dev/null +fi + +# --------------------------------------------------------------------------- +# 4. Configure secrets +# --------------------------------------------------------------------------- + +# --stdin keeps the token values out of the command line, so they never reach +# `ps` output or a shell history file. --skip-deploys stops each set from +# triggering its own build; the single `railway up` below is the deploy. +say "Setting SLACK_BOT_TOKEN and SLACK_APP_TOKEN on ${RAILWAY_SERVICE_NAME}" +printf '%s' "${SLACK_BOT_TOKEN}" \ + | railway variable set SLACK_BOT_TOKEN --service "${RAILWAY_SERVICE_NAME}" --stdin --skip-deploys >/dev/null +printf '%s' "${SLACK_APP_TOKEN}" \ + | railway variable set SLACK_APP_TOKEN --service "${RAILWAY_SERVICE_NAME}" --stdin --skip-deploys >/dev/null + +# --------------------------------------------------------------------------- +# 5. Deploy +# --------------------------------------------------------------------------- + +# --ci streams the build logs and exits when the build ends, so a failed build +# shows up here rather than after the hook has already reported success. +# --detach would return before the build starts. +say "Uploading and building" +railway up --service "${RAILWAY_SERVICE_NAME}" --ci + +say "" +say "Build finished. A successful build does not prove the app started, so check" +say "for the Socket Mode connection in the app's logs:" +say " railway logs --service ${RAILWAY_SERVICE_NAME} --lines 100" +say " railway service status --service ${RAILWAY_SERVICE_NAME}" diff --git a/.agents/skills/deploy-slack-app/references/heroku.md b/.agents/skills/deploy-slack-app/references/heroku.md new file mode 100644 index 0000000..103baec --- /dev/null +++ b/.agents/skills/deploy-slack-app/references/heroku.md @@ -0,0 +1,129 @@ +# Heroku + +Heroku runs the app as a `worker` dyno, a process type that binds no HTTP port. +Only `web` dynos have to listen on `$PORT`, so a Socket Mode app fits the `worker` +type exactly. + +The deploy script for this provider is `deploy-heroku.sh`, alongside this file. +Copy it to `.slack/deploy-heroku.sh` as described in the parent skill's Step 4. + +**Cost.** Current pricing is at . Point the developer +there rather than quoting or fetching it. Two things hold whatever the price list +says: + +- **Who owns the app changes the bill.** Personal apps and team apps can have + different plans available and be billed differently, and a shared team has a + shared budget. Confirm with the developer which one they are creating. +- **Every running dyno counts.** That is why the deploy script makes sure no `web` + dyno runs alongside the worker. + +**Three things to know before choosing Heroku.** + +- **Some accounts cannot own an app personally.** Enterprise-managed Heroku accounts + are one case: `heroku apps:create` refuses with "All apps must belong to a team." + Run `heroku teams` to see which teams the account belongs to, ask the developer + which one to use, and set `HEROKU_TEAM` to it. +- **Tokens go on the command line.** `heroku config:set` has no stdin or file + input, so `SLACK_BOT_TOKEN` and `SLACK_APP_TOKEN` appear as process arguments and + are visible to `ps` while the command runs. The deploy hook runs the command + rather than a person typing it, so it stays out of shell history, but the `ps` + exposure is real. Mention it to the developer. +- **Deploying means pushing a commit.** Heroku builds from git, not from the + working directory, so the project must be a git repository with at least one + commit, and the code being deployed must be committed. Uncommitted changes are + not deployed. + +--- + +## Install and authenticate + +```sh +brew tap heroku/brew && brew install heroku +heroku auth:whoami # confirms the CLI is authenticated +``` + +If `heroku auth:whoami` fails, ask the developer to run `heroku login` in their +own terminal. It waits for a keypress and opens a browser, so it cannot complete +inside an agent session. For a headless setup, create a token with +`heroku authorizations:create` and export it as `HEROKU_API_KEY`. + +--- + +## What Heroku needs from the project + +A committed `Procfile` in the project root declaring the `worker` process type. +Without it Heroku infers a `web` process from the start command, which is the +wrong shape: it would expect the app to bind a port and mark the deploy as failed +when it does not. Write it with the project's own start command: + +```text +worker: npm start +``` + +For Bolt for Python, use the project's entrypoint, for example +`worker: python app.py`. Commit the file before deploying: the deploy script stops +if the `Procfile` is not in git, because an uncommitted one never reaches Heroku. + +The project must be its own git repository, not a directory inside another one. +`slack create` does not run `git init`, so check with `git rev-parse --show-toplevel` +and run `git init` in the project if it names a parent directory. The deploy script +stops in that case, because the push would deploy the parent repository's code. + +For Bolt for Python, also commit a `.python-version` file holding the major and minor +version the app runs on locally, such as `3.13`. Without one, Heroku picks its own +default version and warns that a missing file will become an error. + +--- + +## Environment variables + +- `HEROKU_APP_NAME` (optional): the Heroku app name. When unset, the script reuses + the app the project's `heroku` git remote points at, and on a first deploy falls + back to the project directory name. Names are globally unique across all of + Heroku and may only contain lowercase letters, digits, and dashes, so on a first + deploy pick something distinctive with the developer. +- `HEROKU_TEAM` (optional, sometimes required): the Heroku team to create the + app under. Required when the account cannot own personal apps. Leave empty for + a personal app. Only read when the app is first created. + +Pass them on the deploy command, as shown in the parent skill's Step 5. + +--- + +## Verifying + +```sh +heroku ps --app # expect one worker dyno, state "up" +heroku logs --num 100 --app # look for the Socket Mode connection +heroku config --app | cut -d: -f1 # confirms both tokens are set, without printing them +``` + +Do not use `heroku logs --tail`: it streams until it is stopped, which hangs an +agent session. Do not run a bare `heroku config`: it prints the token values. + +**Confirm only one dyno is running.** `heroku ps` should list `worker` at 1 and no +`web` process at all. If a `web` dyno appears, the app has two copies of itself +connected to Slack and the second one is in a restart loop. Run +`heroku ps:scale web=0 --app `. The worker's own logs will not reveal this: +they look healthy either way. + +**Two connections right after a first deploy are expected.** For Bolt for +JavaScript, Heroku starts a `web` dyno with the first release, before the deploy +script scales it to 0. The worker's first log line can show `num_connections: 2` +while that `web` dyno shuts down. If `heroku ps` lists only the worker, there is +one copy running. + +**If the chosen plan's documentation mentions dynos sleeping**, leave the app idle +for longer than the stated period, then message it. A sleeping dyno drops the +websocket and the app goes quiet in Slack. + +## Tearing down + +Read the app name from the `heroku` git remote, then destroy the app. +`--confirm` takes the same name and skips the confirmation prompt, and the command +also removes the `heroku` git remote: + +```sh +git remote get-url heroku # https://git.heroku.com/.git +heroku apps:destroy --app --confirm +``` diff --git a/.agents/skills/deploy-slack-app/references/railway.md b/.agents/skills/deploy-slack-app/references/railway.md new file mode 100644 index 0000000..a5eb1a7 --- /dev/null +++ b/.agents/skills/deploy-slack-app/references/railway.md @@ -0,0 +1,96 @@ +# Railway + +Railway runs the app as a long-lived service built from the uploaded working +directory. It suits a Socket Mode app well: the service binds no HTTP port, and +Railway does not require one. + +The deploy script for this provider is `deploy-railway.sh`, alongside this file. +Copy it to `.slack/deploy-railway.sh` as described in the parent skill's Step 4. + +**Cost.** Current pricing is at . Point the developer +there rather than quoting or fetching it. Railway bills by resource usage, so a +long-running service costs something for every hour it is up. + +--- + +## Install and authenticate + +```sh +brew install railway # macOS; see https://docs.railway.com/guides/cli +railway whoami # confirms the CLI is authenticated +``` + +If `railway whoami` fails, ask the developer to run `railway login` in their own +terminal. It opens a browser, so it cannot complete inside an agent session. For +a headless setup, export `RAILWAY_API_TOKEN` with an account token. A +project-scoped `RAILWAY_TOKEN` cannot create projects, so it is not enough for a +first deploy. + +--- + +## What Railway needs from the project + +No `Procfile`, `Dockerfile`, or config file. Railway's builder detects the +language and picks a start command, so check that it will pick the right one: + +- **Bolt for JavaScript:** it runs `npm start`, so `package.json` needs a + `scripts.start` entry that starts the app. +- **Bolt for Python:** it runs the first of `main.py`, `app.py`, `start.py`, or + `bot.py` that exists. The Bolt templates use `app.py`, which works unless a + `main.py` is also present. For any other entrypoint, set a start command in a + `railway.json` file (see ). + +--- + +## Environment variables + +- `RAILWAY_PROJECT_NAME` (optional): the Railway project name. Defaults to the + project directory name. +- `RAILWAY_SERVICE_NAME` (optional): the Railway service name. Defaults to the + project directory name. +- `RAILWAY_WORKSPACE` (optional, sometimes required): the workspace to create the + project in. Required when the account belongs to more than one workspace, + because `railway init` otherwise prompts, and the prompt fails in a deploy + hook. `railway whoami --json` lists the account's workspaces. If there is more + than one, ask the developer which to use. + +Pass them on the deploy command, as shown in the parent skill's Step 5. + +--- + +## Verifying + +```sh +railway service status --service # deployment state +railway logs --service --lines 100 # look for the Socket Mode connection +railway logs --build --service --lines 100 # build output, if the build failed +``` + +Always pass `--lines`. Without it `railway logs` streams until it is stopped, +which hangs an agent session. + +**Two connections right after a re-deploy are expected.** Railway starts the new +deployment before removing the old one, so the new one's logs can show +`"num_connections":2` for a moment. `railway deployment list --service ` +should then show the new deployment as `SUCCESS` and the old one as `REMOVED`. +If two deployments stay `SUCCESS`, two copies of the app are connected to Slack. + +Expect the build to take a few minutes on the first deploy. Railway injects a +`PORT` variable even when nothing listens on it, which is harmless for a Socket +Mode app. + +## Tearing down + +Read the project name from `railway status`, then delete the project and unlink +the directory: + +```sh +railway status # shows the linked project +railway delete --project --yes +railway unlink --yes +``` + +Railway stops the service right away but schedules the project's removal for +later, so the project stays in `railway list` for a while. `railway list --json` +shows the scheduled date as `deletedAt`. The project being listed does not mean +the delete failed. diff --git a/.agents/skills/slack-api/SKILL.md b/.agents/skills/slack-api/SKILL.md new file mode 100644 index 0000000..32eafbf --- /dev/null +++ b/.agents/skills/slack-api/SKILL.md @@ -0,0 +1,207 @@ +--- +name: slack-api +description: "Use when a developer asks which Slack Web API method does something, needs a method's OAuth scopes or token type, wants to call or test a family.method endpoint (chat.postMessage, conversations.history, users.info, views.open), is handling cursor pagination (next_cursor) or rate limits (tier/ratelimited/Retry-After), or is debugging errors like missing_scope, invalid_auth, or channel_not_found. Also trigger on a pasted slack.com/api/ URL or docs.slack.dev/reference/methods link." +argument-hint: "[method.name | family]" +--- + +# Slack Web API + +Help the developer **discover** the right Web API method, **read its contract**, and **call** it correctly. Slack exposes hundreds of methods named in `family.method` dot notation (e.g. `chat.postMessage`, `conversations.history`) at `https://slack.com/api/`. Every method's doc page follows a fixed URL pattern, so the contract for any method is always one fetch away. + +If `$0` is provided, it is either a full `method.name` (jump to Step 2 to read its contract) or a `family` name (go to Step 1 and find it in the index). + +> **Critical rules:** +> +> - Verify a method name and its required scopes against its doc page **before** calling it — never invent method names or guess scopes. Method names use `family.method` dot notation. +> - Every response has a top-level `ok` boolean. **Always check `ok`** before using the result; on `ok: false`, read the `error` string. +> - Method names, scopes, rate tiers, and arguments come from the **live doc page** (`https://docs.slack.dev/reference/methods/.md`). The docs are the source of truth — discover from the live index, read the contract from the method's own page. + +> **DO NOT rules:** +> +> - DO NOT assume a method is GET — many are POST. Check the doc page. +> - DO NOT hardcode bearer tokens into committed code or share them in plain text. +> - DO NOT use deprecated methods (`files.upload`, `dialog.open`, `rtm.*`, `oauth.access`, `search.*`, `stars.*`, `reminders.*`) without checking the replacement — a deprecated method's own doc page names what supersedes it; prefer the replacement for new apps. +> - DO NOT paginate by incrementing a page number — Slack uses opaque cursors (see Step 5). + +> **Execution posture — run reads, confirm writes:** +> +> - **Read-only methods** (`*.list`, `*.info`, `*.history`, `conversations.members`, `auth.test`, etc.) may be run directly to help the developer. +> - **State-changing or destructive methods** (`chat.postMessage`/`update`/`delete`, any `*.delete`/`*.remove`/`*.kick`/`*.archive`, and all `admin.*`) — prepare the exact command and **confirm with the developer before running it**. + +--- + +## Fast Path (for clear, specific requests) + +If the developer already knows the method — they named it, pasted a `https://slack.com/api/` URL or a `docs.slack.dev/reference/methods/` link, or gave a `family.method` — skip discovery: + +1. Go to **Step 2** to read the method's contract. +2. Go to **Step 4** to call it (honoring the execution posture above). + +**Full-workflow indicators** (start at Step 1): + +- "Which method does X?" / "How do I list/fetch/post … via the API?" +- The capability is known but the method name is not. +- Exploratory questions about what the API can do. + +--- + +## Step 1: Identify the Method (Discover) + +Map the developer's intent to a family, then to a candidate method. + +### Browsing the index + +WebFetch the live method index: + +```text +https://docs.slack.dev/reference/methods.md +``` + +It lists every Web API method in `family.method` notation with a one-line description and a link to that method's own doc page. It is complete and always current — scan it for a candidate, then follow the method's link into Step 2 to read the contract (the index has descriptions only; rate tier, scopes, token type, and pagination all live on the per-method page). + +Never publish or call a method name you have not seen on a live page. + +### Searching the docs + +When you would rather search by keyword than scan the index, and the Slack CLI is available, use the `slack-cli` skill — **Step 3: Searching Documentation (`slack docs search`)** — to query Slack's docs from the terminal. That step covers the command and flags; results will point you to the method's reference page, which you then read in Step 2. Without the CLI, WebFetch the index (`https://docs.slack.dev/reference/methods.md`) and scan it instead. + +--- + +## Step 2: Read the Method Contract (Navigate) + +Fetch the method's doc page with WebFetch. Either follow the method's link from the index (Step 1) or construct the URL — the path segment is **all-lowercase** and ends in `.md`: + +```text +https://docs.slack.dev/reference/methods/.md +``` + +For example, `conversations.members` → `https://docs.slack.dev/reference/methods/conversations.members.md`, and `chat.postMessage` → `https://docs.slack.dev/reference/methods/chat.postmessage.md`. When in doubt about casing, follow the index link rather than building the URL by hand. + +Every method page documents, consistently: + +- **HTTP method** (GET / POST) and the endpoint `https://slack.com/api/` +- **Required OAuth scopes** and the **token type** (bot `xoxb-` vs user `xoxp-`) +- **Arguments** — required vs optional, with types +- An **example request and response** +- An **errors table** (method-specific codes) +- The **rate-limit tier** + +Extract the **required arguments** and **required scopes** before calling. For what these cross-cutting concepts _mean_ in general — beyond what the method page states — the canonical references are: the response envelope, POST bodies, and auth at `https://docs.slack.dev/apis/web-api.md`; pagination at `https://docs.slack.dev/apis/web-api/pagination.md`; and rate-limit tiers at `https://docs.slack.dev/apis/web-api/rate-limits.md`. + +--- + +## Step 3: Authenticate and Scope + +Calling any non-public method requires a token with the right scopes and type. This skill's job here is to determine, from the contract you read in Step 2, **which token type and scopes** the method needs — independent of how you ultimately send the token. + +From the contract you read in Step 2: + +- Confirm the **token type** — a bot token cannot call a user-only method (the method's doc page states which token types it accepts), and vice versa. For what each token prefix (`xoxb-`, `xoxp-`, `xapp-`) is and when to use it, see `https://docs.slack.dev/authentication/tokens.md`. +- Note the **required scopes**. If a call later fails with `missing_scope`, the response's `needed` and `provided` fields name the gap — add the `needed` scope to the app manifest and reinstall the app. +- `admin.*` methods require an Enterprise Grid **org-level** token. + +A couple of methods need no auth: `api.test` (connectivity), `auth.test` (validates whatever token you do send) and `blocks.validate`. + +You need a token only when the method requires one. There are two ways to get one — pick whichever fits the developer's setup. **The Slack CLI is optional**: if the developer does not have it and prefers not to install it, take Path B rather than forcing an install. + +### Path A: Use the Slack CLI (if installed or wanted) + +The CLI supplies an authenticated session, so once the developer is logged in you can call methods without handling a token yourself (Step 4, "Via the Slack CLI"). + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public Slack CLI is installed and resolve its command name. Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. That step also proposes installing the CLI when it is absent. The fingerprint check, alias fallback, and install instructions all live there; do not duplicate them here. + +Once resolved, use the detected command name for **all** CLI commands in this skill. We refer to it as `SLACK_CMD` — substitute the actual resolved command name everywhere you see `SLACK_CMD`. + +Use the `slack-cli` skill — **Step 5: Authentication (`slack auth`)** — to check the developer's login state and, if needed, walk them through `slack login`. Authentication mechanics live there. + +### Path B: No CLI — bring your own token + +You do not need the CLI to call a method. Get a token of the type you determined above from the app's **OAuth & Permissions** page in the Slack app config (`https://api.slack.com/apps` → your app → **OAuth & Permissions** → **OAuth Tokens**): the **Bot User OAuth Token** (`xoxb-…`) or the **User OAuth Token** (`xoxp-…`). That page also lists the scopes currently granted — confirm the ones from Step 2 are present. Then send that token with curl or an SDK in Step 4 ("Via raw HTTP" / "Via an SDK"). + +--- + +## Step 4: Call the Method (Manage) + +First apply the **execution posture**: if the method changes state (post/update/delete/archive/kick, or any `admin.*`), show the developer the exact command and get a yes before running it. Read-only calls can be run directly. + +### Via the Slack CLI (if installed) + +To call a method from the terminal, use the `slack-cli` skill — **Step 4: Calling Web API Methods (`slack api`)**. That step covers the `SLACK_CMD api key=value …` syntax so that it is not repeated here. Pass the required arguments you gathered from the method's doc page in Step 2. + +The CLI uses the developer's authenticated session, so it is the simplest path once they are logged in (Step 3). + +### Via raw HTTP (curl) + +Use the **Bash tool** when the developer wants a raw request or isn't using the CLI. Send the token in the `Authorization` header — the bot or user token from Step 3 (Path B, or the CLI session). + +**Form-encoded** (the default for most methods): + +```bash +curl -s -X POST 'https://slack.com/api/conversations.list' \ + -H 'Authorization: Bearer xoxb-YOUR-TOKEN' \ + -d 'types=public_channel&limit=200' +``` + +**JSON body** (for methods taking complex arguments like `blocks`, `view`, `attachments`, `metadata`): + +```bash +curl -s -X POST 'https://slack.com/api/chat.postMessage' \ + -H 'Authorization: Bearer xoxb-YOUR-TOKEN' \ + -H 'Content-Type: application/json' \ + -d '{"channel":"C0123456789","text":"Hello from the API"}' +``` + +Check the method's page for which content type it expects. With form encoding, a structured argument is passed as a JSON-encoded string value (e.g. `blocks=[...]`). + +### Via an SDK + +In Bolt and the Slack SDKs, each method is a client function whose arguments match the doc page's argument table: + +- **JavaScript:** `await client.chat.postMessage({ channel, text, blocks })` +- **Python:** `client.chat_postMessage(channel=channel, text=text, blocks=blocks)` + +(Note the JS dot form `chat.postMessage` vs the Python underscore form `chat_postMessage`.) To construct the `blocks`/`view` payload these calls take, use the `block-kit` skill — this skill treats that payload as an opaque argument and focuses on the method call around it. + +--- + +## Step 5: Handle Pagination + +Methods that return collections use **cursor pagination**, not page numbers. A method's doc page states whether it paginates, and the full list of cursor-paginated methods is under _Methods supporting cursor-based pagination_ at `https://docs.slack.dev/apis/web-api/pagination.md`: + +1. Call with a `limit` (page size — check the method's max). +2. Read `response_metadata.next_cursor` from the response. +3. If it is **non-empty**, call again with `cursor=`. +4. Repeat until `next_cursor` comes back empty. + +```bash +# First page +curl -s -X POST 'https://slack.com/api/conversations.history' \ + -H 'Authorization: Bearer xoxb-YOUR-TOKEN' \ + -d 'channel=C0123456789&limit=200' + +# Next page — pass the cursor from response_metadata.next_cursor +curl -s -X POST 'https://slack.com/api/conversations.history' \ + -H 'Authorization: Bearer xoxb-YOUR-TOKEN' \ + -d 'channel=C0123456789&limit=200&cursor=dXNlcjpVMDYxTkZUVDI=' +``` + +Cursors are opaque — never construct, parse, or reuse an old one. + +--- + +## Step 6: Handle Rate Limits and Errors + +When `ok` is `false`, branch on the `error` string: + +- For method-specific codes, read the **errors table** on the method's doc page (Step 2) — it lists every error that method returns, including cross-cutting ones like `not_authed`, `invalid_auth`, `missing_scope`, `channel_not_found`, and `invalid_arguments`. +- For what the envelope itself means (`ok`, `error`, `warning`, `response_metadata`), see _Evaluating responses_ at `https://docs.slack.dev/apis/web-api.md`. +- `response_metadata.messages` often pinpoints a malformed argument. + +**Rate limits:** on HTTP `429` / `error: "ratelimited"`, honor the `Retry-After` response header (seconds) — wait, then retry. Do not retry in a tight loop. Each method's tier (1–4 or special) caps calls per minute; the tier table is at `https://docs.slack.dev/apis/web-api/rate-limits.md`, and newer non-Marketplace apps face stricter caps on some methods, so trust the method's own page for the exact number. + +--- + +## Notes + +- **Slack Lists** methods use the `slackLists.*` prefix — a bare `lists.*` name does not exist. +- **Scope:** this skill owns the method layer — which method, its contract, and the call around it. CLI auth and calls are delegated to the `slack-cli` skill; Block Kit payloads to the `block-kit` skill. diff --git a/.agents/skills/slack-cli/SKILL.md b/.agents/skills/slack-cli/SKILL.md new file mode 100644 index 0000000..47d857f --- /dev/null +++ b/.agents/skills/slack-cli/SKILL.md @@ -0,0 +1,253 @@ +--- +name: slack-cli +description: "Use when a developer works with the Slack CLI (slack command) to create, run, or manage a Slack app from the terminal: logging in or authenticating (slack login), adding a team or switching workspaces, running locally (slack run), deploying, editing the app manifest, calling Web API methods (slack api), or searching Slack docs (slack docs search)." +--- + +# Slack CLI + +Use the Slack CLI to create, run, and manage Slack apps — including calling Web API methods directly and searching Slack developer documentation from the terminal. + +For initial setup (sandbox creation, project scaffolding from templates), use the `create-slack-app` skill instead. + +--- + +## Step 1: Detect the Slack CLI + +Resolve the path to the **public** Slack CLI before running any other command. We refer to the resolved value as `SLACK_CMD` — substitute it everywhere below. **Try 1a → 1b → 1c in order; do not skip ahead.** + +### 1a. Standard install path (preferred — no verification needed) + +The official install scripts place the binary at a fixed per-user path. If the file exists, use it directly: only the install script writes to that path. + +- macOS / Linux: `~/.slack/bin/slack` +- Windows: `%USERPROFILE%\AppData\Local\slack-cli\bin\slack.exe` (or `%USERPROFILE%\.slack-cli\bin\slack.exe` as a fallback) + +POSIX shell: + +```bash +[ -x "$HOME/.slack/bin/slack" ] && echo "$HOME/.slack/bin/slack" +``` + +PowerShell: + +```powershell +$p = "$env:USERPROFILE\AppData\Local\slack-cli\bin\slack.exe" +if (Test-Path $p) { $p } elseif (Test-Path "$env:USERPROFILE\.slack-cli\bin\slack.exe") { "$env:USERPROFILE\.slack-cli\bin\slack.exe" } +``` + +If a path is returned, set `SLACK_CMD` to that **absolute path** and proceed to Step 2. Do not also run `_fingerprint`. + +### 1b. `slack` on PATH (verify with fingerprint) + +If 1a found nothing, try `slack` on PATH: + +```bash +slack _fingerprint 2>/dev/null +``` + +If it outputs `d41d8cd98f00b204e9800998ecf8427e`, set `SLACK_CMD=slack` and proceed. + +### 1c. Ask about an alias, or install + +If 1b fails or returns a different value, ask the developer using AskUserQuestion: + +- "The `slack` command on your system doesn't appear to be the public Slack CLI. Do you have it installed under a different name or alias?" +- Options: "Yes, it's aliased as..." (let them provide the alias), "No, I need to install it" +- If they provide an alias, verify it with ` _fingerprint 2>/dev/null` and set `SLACK_CMD=`. +- If they need to install it, run: + + ```text + curl -fsSL https://downloads.slack-edge.com/slack-cli/install.sh | bash + ``` + + Then re-run **1a** — the install script will have written `~/.slack/bin/slack`. + +**Common mistakes:** Don't use `which slack` to discover the binary — `which` resolves any shell alias and defeats the point of 1a. In Git Bash on Windows, use the POSIX probe form, not PowerShell. + +--- + +## Step 2: Command Discovery via Help + +**Always run `SLACK_CMD --help` before constructing a command you have not used in the current session.** Do not guess at flags — the help output is the source of truth. + +- `SLACK_CMD help` — lists all available command groups +- `SLACK_CMD --help` — shows subcommands, flags, and usage examples + +If a command or flag in this skill is missing from the help output, the installed CLI is older than this skill. Ask the developer to run `SLACK_CMD upgrade`, then check the help output again. + +### Resolving `--app` and `--team` values + +When a command requires `--app` or `--team`: + +- **App ID**: Run `SLACK_CMD app list` from the project directory to see installed apps and their IDs. +- **Team ID**: Run `SLACK_CMD auth list` to see authenticated workspaces and their team IDs. + +--- + +## Step 3: Searching Documentation (`slack docs search`) + +Search Slack's developer documentation directly from the terminal. + +```bash +SLACK_CMD docs search "" --output=text --limit=5 +``` + +Use `--output=text` for concise terminal-readable results. Use this when you are already running CLI commands and want to: + +- Check a Slack feature before implementing it +- Verify API behavior or required scopes +- Look up Block Kit elements, event types, or method parameters + +--- + +## Step 4: Calling Web API Methods (`slack api`) + +Call any Slack Web API method directly. Run `SLACK_CMD api --help` for full details and examples. + +Parameters are passed as positional `key=value` pairs (NOT `--key=value` flags): + +```bash +SLACK_CMD api chat.postMessage channel=C0123456789 text="Hello from the CLI" +``` + +**Important distinction**: `--team`, `--token`, `--json`, and `--data` are meta-flags (prefixed with `--`). API method parameters use positional `key=value` syntax without dashes. + +**Reference**: Full method list at . + +--- + +## Step 5: Authentication (`slack auth`) + +### When to run this flow + +Slack auth is **per-team**, not a single boolean. Run the seamless login flow below whenever any of these is true: + +- The developer is not authenticated to any team yet. +- The developer wants to **add a new team / workspace / sandbox**, even if `SLACK_CMD auth list` already shows other teams. +- The developer asks to log in, switch teams, or re-authenticate. + +`SLACK_CMD auth list` showing other teams is **not** a reason to skip login — those are different teams. Ask the developer which team they want, then run the flow. + +The flow below is the same for every kind of workspace. `/slackauthticket` works in any workspace the developer belongs to, whether that is a developer sandbox, a Free Team, or a production workspace, so there is no sandbox-specific login. Which target to prefer is the `create-slack-app` skill's call (**Step 3: Choose Where to Install the App**). + +### Inspect existing auth (optional) + +```bash +SLACK_CMD auth list +``` + +Use this to show the developer which teams are already authenticated, or to confirm a successful login. Do not treat a non-empty list as "auth complete" when the developer asked to log in to a new team. + +### Run the seamless login flow + +The agent drives this end-to-end — **no separate terminal window, no browser confirmation**. + +`SLACK_CMD login --no-prompt` makes the CLI emit a single-use ticket and exit immediately instead of waiting on stdin. Slack itself renders the challenge code **inside a workspace modal** when the developer sends the `/slackauthticket` slash command — there is no browser step. The agent submits the challenge back to the CLI to complete login. + +**1. Start login and capture the ticket** + +```bash +SLACK_CMD login --no-prompt +``` + +The CLI prints a `/slackauthticket ` slash command and exits. Capture the ticket — you will need it in step 4. Sample output: + +```text +📋 Run the following slash command from any Slack channel in the workspace + you'd like to authenticate + + /slackauthticket eyJ0eXAiOiJKV1QiLCJh… + +? Slack will then show you a challenge code. Submit it via: + slack login --ticket --challenge +``` + +**2. Hand the slash command to the developer** + +Show the full `/slackauthticket …` line and ask the developer to paste it into the message box of the Slack workspace they want to authenticate, then send it. Slack responds with a modal containing a short challenge code (e.g. `JDt1IK7X`). + +**3. Collect the challenge code** + +Use `AskUserQuestion` to ask the developer for the challenge code shown in the Slack modal. Wait for their answer — do not guess or default. + +**4. Complete login** + +```bash +SLACK_CMD login --ticket --challenge +``` + +On success the CLI returns the team name and ID. Verify with `SLACK_CMD auth list` and report the team back to the developer. + +**Troubleshooting**: tickets are single-use and time-limited. If step 4 fails with an invalid/expired ticket or wrong challenge, restart from step 1 with a fresh `SLACK_CMD login --no-prompt` — do not retry the same ticket. + +Use `--team ` on individual commands to target a specific workspace without switching globally. + +### Red flags — STOP + +If you catch yourself thinking any of these, you are about to regress to the old broken flow: + +| Rationalization | Reality | +|---|---| +| "`auth list` already shows teams, so login isn't needed." | Auth is per-team. The developer asked for a _new_ team — drive the flow. | +| "`slack login` needs browser confirmation, so I can't drive it." | False with `--no-prompt`. The challenge code appears in Slack's modal, not a browser. The agent runs both `slack login` invocations itself. | +| "I should tell the developer to run `slack login` in a separate terminal." | Never. Step 5 is the agent's job from start to finish. | + +**All of these mean: run `SLACK_CMD login --no-prompt` yourself and follow the four numbered steps above.** + +--- + +## Step 6: Running an App Locally (`slack run`) + +Run `SLACK_CMD run --help` for all available flags. + +### Resolve the app or team target + +Run `SLACK_CMD app list` from the project directory to check for installed apps: + +- **If an app exists**: Use `--app=` in the run command. +- **If no apps are listed**: Use `--team=` instead (get the team ID from `SLACK_CMD auth list`). + +### Start the dev server in the background + +Run this command as a **background process** so the developer can continue working: + +**If an app ID was found:** + +```bash +cd && SLACK_CMD run --org-workspace-grant=all --app= +``` + +**If no apps — use the team ID:** + +```bash +cd && SLACK_CMD run --org-workspace-grant=all --team= +``` + +Tell the developer the app is running in the background. They can ask: + +- "What's the status of the dev server?" — to check on it +- "Show me the output from slack run" — to see activity logs +- "Stop the dev server" — to terminate the process + +--- + +## Step 7: Managing the Manifest + +Run `SLACK_CMD manifest --help` for subcommands (`validate`, `info`) and the `--source local|remote` flag. + +Use `SLACK_CMD manifest validate` before deploying or when something seems wrong with the app configuration. + +--- + +## Step 8: Other Commands + +For any other command group (e.g., `trigger`, `datastore`, `env`, `collaborator`, `external-auth`, `deploy`), run `SLACK_CMD --help` to discover subcommands and flags. Run `SLACK_CMD help` to see all available command groups. + +--- + +## Notes + +- `SLACK_CMD` is a placeholder — always substitute the actual command name resolved in Step 1. +- **Always run `--help`** before constructing a command you have not used in the current session. +- Interactive commands (e.g., `slack trigger create` without `--trigger-def`) cannot be run in the background. Tell the developer to run these in a **new terminal window**. `slack login` is **not** in this category — drive it inline using the `--no-prompt` / `--ticket` / `--challenge` flow in Step 5. +- `slack run` runs locally for development. `slack deploy` deploys to Slack's hosted infrastructure, unless `.slack/hooks.json` defines a `deploy` hook, in which case it runs that hook instead (see the `deploy-slack-app` skill). These are different operations, so do not confuse them. diff --git a/.agents/skills/slack-docs/SKILL.md b/.agents/skills/slack-docs/SKILL.md new file mode 100644 index 0000000..2b79ecb --- /dev/null +++ b/.agents/skills/slack-docs/SKILL.md @@ -0,0 +1,145 @@ +--- +name: slack-docs +description: "Use when answering a conceptual or how-to question about Slack platform features, or when asked to look up, fetch, or summarize a docs.slack.dev page, including a pasted docs.slack.dev link. Covers finding and reading official Slack docs as clean markdown." +argument-hint: "[topic or docs.slack.dev URL]" +--- + +# Slack Platform Documentation + +Help the developer **find** the right page on the official Slack documentation site (`https://docs.slack.dev`) and **read** it as clean markdown, so answers come from the live docs rather than memory. The site exposes three machine-readable surfaces an agent can use directly, with no authentication and no Slack workspace: + +- A **search API method**: `GET https://docs.slack.dev/api/v1/search?query=&category=&pin=false` returns ranked page hits as JSON. Scope every search with a `category` (guides, reference, a specific SDK, etc.); an uncategorized search skews heavily toward SDK pages. Always pass `pin=false`, which stops the API from putting this plugin's own page first for searches about coding agents; you already have the plugin. +- **Per-page markdown**: every page is available at its URL **+ `.md`** (e.g. `/quickstart.md`). +- **Index files**: `/llms.txt` (a curated overview) and `/llms-sitemap.md` (a list of every markdown page). + +If `$0` is provided, it is either a `docs.slack.dev` URL (jump to the **Fast Path**) or a topic to search (start at **Step 1**). For a broad "how do I build X on Slack?" question rather than one specific page, read `https://docs.slack.dev/llms.txt` first; it is a curated, LLM-oriented overview of the platform and the recommended build path. + +> **Critical rules:** +> +> - The docs are the **source of truth**. Do not answer a factual question about the Slack platform from memory; discover the page, fetch it, then answer from what it says. +> - Prefer the **`.md` version** of any page over the HTML version. It is cleaner for reading and quoting. +> - Every fetched markdown page begins with a `Source: ` line. Keep that URL so you can cite the page back to the developer. + +> **DO NOT rules:** +> +> - DO NOT invent documentation URLs. Get them from the search API, the sitemap, or a link the developer gave you then verify by fetching. +> - DO NOT paraphrase a page you have not actually fetched. If a fetch fails, say so rather than filling the gap from memory. +> - DO NOT assume every URL has a `.md` version. If a fetch returns an error, fall back to the search API or the sitemap (Step 1) rather than guessing another URL. + +--- + +## Fast Path (the developer already has a URL) + +If the developer pasted a `https://docs.slack.dev/...` link, skip discovery and go straight to **Step 2** to fetch and read it. + +--- + +## Step 1: Discover the Page (search) + +**If the Slack CLI is installed, search from the terminal.** Load the `slack-cli` skill (with your skill tool, if you have one) and follow **1a** and **1b** of its **Step 1: Detect the Slack CLI** to check whether the public CLI is installed and resolve its command (`SLACK_CMD`). Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. Stop there: don't ask the developer about an alias or offer to install the CLI just to search the docs. If neither finds it, use the search API below. + +```bash +SLACK_CMD docs search '' --category= --limit=5 --hide-pinned +``` + +Keep the query in single quotes, so the shell doesn't run anything inside it, and leave any `'` out of the query (`whats socket mode`). Search ignores punctuation. It calls the same search API and takes the same categories as below. On a current CLI, each result links to the page's `.md` version, ready for **Step 2**. An older CLI returns the page URL, which Step 2 turns into its `.md` version. `--hide-pinned` leaves out the Slack MCP and Skills Plugin page that the API pins to the top of searches about coding agents. You already have the plugin. + +Check `SLACK_CMD docs search --help` first. If `search` or its `--category` flag is missing, use the search API below. If only `--hide-pinned` is missing, the CLI is older than this skill: search without it and skip the plugin page (`https://docs.slack.dev/ai/slack-skills-plugin/`) if it comes first. Suggest `SLACK_CMD upgrade` once, as the `slack-cli` skill's **Step 2: Command Discovery via Help** does for a missing command or flag. + +**Otherwise, use the search API.** WebFetch this URL, with the query URL-encoded and a `category` to scope the results: + +```text +https://docs.slack.dev/api/v1/search?query=&category=&limit=5&pin=false +``` + +**Always start with a `category`.** An uncategorized search is dominated by SDK reference pages (a query like `socket mode` or `oauth` can return a top 10 that is entirely Bolt/Node pages), which buries the conceptual and reference content most questions are actually about. Pick the starting category from the developer's intent: + +- **`guides`** — the default for "how do I…", "what is…", and conceptual platform questions (Events API, OAuth, Socket Mode, manifests, modals, App Home). Start here when in doubt. +- **`reference`** — for a specific method, event, scope, object, or Block Kit element, especially an exact name like `chat.postMessage`. +- **A tool/SDK category** (`python`, `javascript`, `java`, `slack_cli`, `slack_github_action`, `deno_slack_sdk`) — only once you know the developer's tool. See **Step 3**. + +So `socket mode` as a concept → `https://docs.slack.dev/api/v1/search?query=socket%20mode&category=guides&limit=5&pin=false`. + +The response is JSON: + +```json +{ + "total_results": 12, + "results": [ + { "url": "/apis/events-api/using-socket-mode", "title": "Using Socket Mode" } + ], + "limit": 5 +} +``` + +Scan `results` for the best `title`/`url` match, then read it in **Step 2**. A query is **required**; calling the endpoint with no `query` returns a `400` with an `error` field. + +Full set of categories: + +| Category | Scopes results to | +|----------|-------------------| +| `guides` | Conceptual and how-to guides | +| `reference` | API reference: methods, events, scopes, objects, Block Kit | +| `changelog` | Changelog and release notes | +| `python` | Python tools (Bolt for Python, Python Slack SDK) | +| `javascript` | JavaScript tools (Bolt for JS, Node Slack SDK) | +| `java` | Java tools (Bolt for Java, Java Slack SDK) | +| `slack_cli` | Slack CLI docs | +| `slack_github_action` | Slack Send GitHub Action docs | +| `deno_slack_sdk` | Deno Slack SDK docs | + +If a categorized search returns no good hit, widen it: try the other likely category (`guides` ⇄ `reference`), then drop `category` entirely as a last resort. An unrecognized value returns a `400` with an `error` field listing the valid categories, so re-run with one of those or with no category. + +**Fallbacks** when search does not surface a good hit, or returns a `500`/temporary error (the endpoint is rate-limited and cached ~5 minutes): + +- WebFetch `https://docs.slack.dev/llms-sitemap.md`, a flat list of every documentation page's `.md` URL, and scan it for the relevant path. +- For API reference lookups, the enriched index pages are often faster: `https://docs.slack.dev/reference/methods.md`, `.../events.md`, `.../scopes.md`, `.../objects.md`, and `.../block-kit.md` each list every item with a one-line description and a `.md` link. + +--- + +## Step 2: Read the Page (fetch markdown) + +Given a page reference (a `url` from Step 1, or a link the developer pasted), read its markdown. + +**If the Slack CLI is installed, print the page from the terminal.** Use the `SLACK_CMD` from Step 1. When you came here from the Fast Path with a pasted link, resolve it the same way first, with **1a** and **1b** of the `slack-cli` skill's **Step 1: Detect the Slack CLI**. + +```bash +SLACK_CMD docs get '' +``` + +It accepts a link from `SLACK_CMD docs search`, a pasted docs.slack.dev URL, or a site path, with or without `.md` or an `#anchor`, and prints the page's markdown. If `SLACK_CMD docs --help` doesn't list `get`, the CLI is older than this skill: suggest `SLACK_CMD upgrade` once and fetch the page as below. + +Generated SDK reference pages end in `.html` and have no markdown version, so `docs get` reports that and appending `.md` fails too. WebFetch a `.html` link as it is. + +**Otherwise, fetch the markdown:** + +1. Normalize the reference to its `.md` URL: + - A site-relative path from Step 1 (e.g. `/apis/events-api/using-socket-mode`): prepend `https://docs.slack.dev`. + - A full URL the developer pasted, or a link from `SLACK_CMD docs search`: drop any `#anchor` first. + - Unless it already ends in `.md`, drop a trailing `/`, then append `.md`, e.g. `…/using-socket-mode/` → `https://docs.slack.dev/apis/events-api/using-socket-mode.md`. Keeping the slash (`…/using-socket-mode/.md`) returns a 404. + The server lowercases `.md` requests, so casing does not matter: `chat.postMessage.md` and `chat.postmessage.md` both resolve. +2. **WebFetch** it. The page opens with `Source: `; the rest is the page body in markdown. +3. Answer the developer from the fetched content, and cite the `Source` URL. + +If a page is long and the developer asked something narrow, fetch it and quote only the relevant section rather than dumping the whole page. + +--- + +## Step 3: Tool and SDK Documentation + +Implementation details differ significantly between the official tools, so **establish which one the developer is using first**, then scope your reading to that tool's doc subtree. Each lives under `https://docs.slack.dev/tools/` and its pages are fetchable as `.md` like any other (e.g. `https://docs.slack.dev/tools/bolt-js/concepts.md`). If the developer has not said, ask before assuming. + +| Tool | Docs path | Search `category` | Use when the developer… | +|------|-----------|-------------------|--------------------------| +| **Slack CLI** | `/tools/slack-cli` | `slack_cli` | scaffolds, runs, or manages an app from the terminal; mentions `slack` commands or app manifests | +| **Bolt for JavaScript** | `/tools/bolt-js` | `javascript` | builds an app in Node/TypeScript with the Bolt framework | +| **Bolt for Python** | `/tools/bolt-python` | `python` | builds an app in Python with the Bolt framework | +| **Bolt for Java** | `/tools/java-slack-sdk` | `java` | builds an app in Java with Bolt (Bolt for Java lives in the Java SDK docs) | +| **Node Slack SDK** | `/tools/node-slack-sdk` | `javascript` | wants lower-level Node clients (`@slack/web-api`, `@slack/socket-mode`) without the full Bolt framework | +| **Python Slack SDK** | `/tools/python-slack-sdk` | `python` | wants the lower-level Python client without Bolt | +| **Java Slack SDK** | `/tools/java-slack-sdk` | `java` | wants Java clients, or is using Bolt for Java | +| **Slack Send GitHub Action** | `/tools/slack-github-action` | `slack_github_action` | sends data to Slack from a GitHub Actions workflow | + +Once you know the tool, narrow discovery with the matching `category` from Step 1, e.g. `…?query=middleware&category=javascript`. Note the languages group: both Bolt for JavaScript and the Node Slack SDK fall under `javascript` (likewise `python` and `java` each cover their Bolt framework plus lower-level SDK), so the category scopes to the language family, not a single subtree. + +**Bolt** is the framework built upon the matching language **SDK**. When unsure which subtree a topic lives in, fall back to the search API (Step 1) as it indexes all of these. diff --git a/.agents/skills/slack-messaging/SKILL.md b/.agents/skills/slack-messaging/SKILL.md new file mode 100644 index 0000000..71ee92e --- /dev/null +++ b/.agents/skills/slack-messaging/SKILL.md @@ -0,0 +1,84 @@ +--- +name: slack-messaging +description: "Use when writing, drafting, scheduling, or improving a Slack message, announcement, or reply sent via the Slack MCP tools (slack_send_message, slack_send_message_draft, slack_schedule_message). Covers Slack markdown formatting, message structure, thread etiquette, reactions, and scheduling, and points to the right dialect for canvases and Block Kit." +--- + +# Slack Messaging Best Practices + +This skill provides guidance for composing well-formatted, effective Slack messages. + +## When to Use + +Apply this skill whenever composing, drafting, or helping the user write a Slack message, including when using `slack_send_message`, `slack_send_message_draft`, or `slack_schedule_message`. The formatting rules below cover these message tools. `slack_create_canvas` uses a different, richer markdown dialect — see the Canvas note below. + +## Formatting + +The message tools (`slack_send_message`, `slack_send_message_draft`, `slack_schedule_message`) accept **standard markdown** and convert it to Slack formatting on send. Write normal markdown. Do **not** use Slack's legacy `mrkdwn` syntax (`*bold*`, `~strike~`); those single-character forms mean something different in standard markdown. Each text element is limited to ~5000 characters. + +| Format | Syntax | +| ------------- | ---------------------- | +| Bold | `**text**` | +| Italic | `_text_` (or `*text*`) | +| Strikethrough | `~~text~~` | +| Code (inline) | `` `code` `` | +| Quote | `> text` | +| Link | `[display text](url)` | +| Bulleted list | `- item` | +| Numbered list | `1. item` | + +Block elements also work. Write them as literal markdown: + +- **Code block** with an optional language for syntax highlighting: + + ````text + ```python + print("hello") + ``` + ```` + +- **Table** with `|` delimiters (escape a literal pipe inside a cell as `\|`): + + ```text + | Feature | Status | + |---------|--------| + | Tables | works | + ``` + +- **Headers** with `#` / `##` / `###`: + + ```text + ## Section title + ``` + +The one thing that does **not** embed in a message: inline images (`![alt](url)`) typically render as a plain link rather than an inline image. For rich embedded layouts (buttons, images, structured cards) you need Block Kit; for a document-style surface where images do embed, use a canvas. See the Notes below. + +## Message Structure Guidelines + +- **Lead with the point.** Put the most important information in the first line. Many people read Slack on mobile or in notifications where only the first line shows. +- **Keep it short.** Aim for 1-3 short paragraphs (the ~5000-character limit is a ceiling, not a target). If the message is long or structured, consider a Canvas instead. +- **Use line breaks generously.** Walls of text are hard to read. Separate distinct thoughts with blank lines. +- **Use bullet points for lists.** Anything with 3+ items should be a list, not a run-on sentence. +- **Bold key information.** Use `**bold**` for names, dates, deadlines, and action items so they stand out when scanning. + +## Thread vs. Channel Etiquette + +- **Reply in threads** when responding to a specific message to keep the main channel clean. +- **Use `reply_broadcast`** (also post to channel) only when the reply contains information everyone needs to see. +- **Post in the channel** (not a thread) when starting a new topic, making an announcement, or asking a question to the whole group. +- **Don't start a new thread** to continue an existing conversation; find and reply to the original message. + +## Tone and Audience + +- Match the tone to the channel: `#general` is usually more formal than `#random`. +- For simple acknowledgments, add an emoji reaction with `slack_add_reaction` instead of a reply message (use `slack_get_reactions` to read existing reactions). +- When writing announcements, use a clear structure: context, key info, call to action. + +## Scheduling + +- Use `slack_schedule_message` to post later. `post_at` is a Unix timestamp that must be at least 2 minutes in the future and at most 120 days out; the message body uses the same standard markdown as above. +- Scheduled messages can't be edited via the API once set — the user manages them from **Drafts & sent** in Slack. + +## Notes + +- **Canvas formatting is different.** `slack_create_canvas` uses Canvas-flavored Markdown, a richer dialect than the message tools: headers, tables, checklists, and inline images (`![alt](url)`) all embed, and it also supports user/channel reference cards, callouts, and columns. Do **not** assume the message rules above apply — follow the `slack_create_canvas` tool's own formatting guidance when composing a canvas. +- **Scope:** this skill owns composing and formatting the _text_ of messages sent through the Slack MCP message tools. For interactive layouts (buttons, menus, modals, Home tabs, or any Block Kit JSON), use the `block-kit` skill, which composes and validates the block payload. For calling the Slack Web API directly (`chat.postMessage` and friends) rather than the MCP tools, use the `slack-api` skill. diff --git a/.agents/skills/slack-search/SKILL.md b/.agents/skills/slack-search/SKILL.md new file mode 100644 index 0000000..6015eb9 --- /dev/null +++ b/.agents/skills/slack-search/SKILL.md @@ -0,0 +1,123 @@ +--- +name: slack-search +description: "Use when locating messages, files, channels, or people across Slack, or gathering context before answering, with the search MCP tools (slack_search_public, slack_search_public_and_private, slack_search_channels, slack_search_users). Covers search modifiers (in:, from:, before:), file-type filters, natural-language vs. keyword search, and reading results in context." +--- + +# Slack Search + +This skill provides guidance for effectively searching Slack to find messages, files, and information. + +## When to Use + +Apply this skill whenever you need to find information in Slack, including when a user asks you to locate messages, conversations, files, or people, or when you need to gather context before answering a question about what's happening in Slack. + +## Search Tools Overview + +| Tool | Use When | +| --------------------------------- | ------------------------------------------------------------------------------------ | +| `slack_search_public` | Searching public channels only. Does not require user consent. | +| `slack_search_public_and_private` | Searching all channels including private, DMs, and group DMs. Requires user consent. | +| `slack_search_channels` | Finding channels by name or description. | +| `slack_search_users` | Finding people by name, email, or role. | + +## Search Strategy + +### Start Broad, Then Narrow + +1. Begin with a simple keyword or natural language question. +2. If too many results, add filters (`in:`, `from:`, date ranges). +3. If too few results, remove filters and try synonyms or related terms. + +### Choose the Right Search Mode + +- **Natural language questions** (e.g., "What is the deadline for project X?"): Best for fuzzy, conceptual searches where you don't know exact keywords. +- **Keyword search** (e.g., `project X deadline`): Best for finding specific, exact content. + +### Use Multiple Searches + +Don't rely on a single search. Break complex questions into smaller searches: + +- Search for the topic first +- Then search for specific people's contributions +- Then search in specific channels + +## Search Modifiers Reference + +### Location Filters + +- `in:channel-name`: Search within a specific channel +- `in:<#C123456>`: Search in channel by ID +- `-in:channel-name`: Exclude a channel +- `in:<@U123456>` or `in:@username`: Search in DMs with a user + +### User Filters + +- `from:<@U123456>`: Messages from a specific user (by ID) +- `from:username`: Messages from a user (by Slack username) +- `to:<@U123456>`: Messages sent to a specific user +- `to:me`: Messages sent directly to you +- `creator:@username`: Canvases created by a specific person + +### Content Filters + +- `is:thread`: Only threaded messages +- `is:saved`: Only your saved messages +- `has:pin`: Pinned messages +- `has:link`: Messages containing links +- `has:file`: Messages with file attachments +- `has::emoji:`: Messages with a specific reaction +- `hasmy::emoji:`: Messages you reacted to with a specific reaction + +### Date Filters + +- `before:YYYY-MM-DD`: Messages before a date +- `after:YYYY-MM-DD`: Messages after a date +- `on:YYYY-MM-DD`: Messages on a specific date +- `during:month`: Messages during a specific month (e.g., `during:january`) + +### Text Matching + +- `"exact phrase"`: Match an exact phrase +- `-word`: Exclude messages containing a word +- `wild*`: Wildcard matching (minimum 3 characters before `*`) + +## File Search + +To search for files, set the `content_types="files"` parameter and use a `type:` filter in the query: + +- `type:images`, `type:documents`, `type:pdfs`, `type:spreadsheets`, `type:presentations` +- `type:canvases`, `type:lists`, `type:emails`, `type:audio`, `type:videos` + +Example: `content_types="files" type:pdfs budget after:2025-01-01` + +All the standard modifiers above (`in:`, `from:`, dates, etc.) work with file searches too. + +## Useful Parameters + +Beyond the query string, the search tools accept parameters that materially improve results: + +- `sort`: `score` (relevance, default) or `timestamp` (newest first); pair with `sort_dir` (`asc`/`desc`). +- `content_types`: `messages` (default) or `files`. +- `only_my_channels`: restrict to channels you're a member of. +- `limit`: results per page (capped at 20); paginate with the returned `cursor`. + +## Following Up on Results + +After finding relevant messages: + +- Use `slack_read_thread` to get the full thread context for any threaded message. +- Use `slack_read_channel` with `oldest`/`latest` timestamps to read surrounding messages for context. +- Use `slack_read_user_profile` to identify who a user is when their ID appears in results. +- Use `slack_read_file` to read the contents of a file surfaced by a file search. +- Use `slack_list_channel_members` to see who is in a channel you found. + +## Common Pitfalls + +- **Boolean operators don't work.** `AND`, `OR`, `NOT` are not supported. Use spaces (implicit AND) and `-` for exclusion. (Repeating the same modifier, e.g. two `from:`, ORs those values together.) +- **Parentheses don't work.** Don't try to group search terms with `()`. +- **Search is not real-time.** Very recent messages (last few seconds) may not appear in search results. Use `slack_read_channel` for the most recent messages. +- **Private channel access.** Use `slack_search_public_and_private` when you need to include private channels, but note this requires user consent. + +## Notes + +- **Scope:** this skill owns searching _workspace content_: messages, files, channels, and people inside Slack. To search and read the official Slack _platform documentation_ at docs.slack.dev (conceptual and how-to questions about Slack features), use the `slack-docs` skill instead. diff --git a/.agents/skills/test-slack-app/SKILL.md b/.agents/skills/test-slack-app/SKILL.md new file mode 100644 index 0000000..69f08ff --- /dev/null +++ b/.agents/skills/test-slack-app/SKILL.md @@ -0,0 +1,111 @@ +--- +name: test-slack-app +description: Use when a developer wants to test, try out, smoke-test, verify, or confirm that a Slack app built with the Slack CLI (or a plain Bolt app) actually works, by running it in a developer sandbox or a Free Team, never a workspace with real users, with `slack run` and exercising its real slash commands, shortcuts, events, actions, modals, App Home, and assistant surfaces. Also covers `slack doctor` and `slack manifest validate` health checks before hands-on testing. +--- + +# Test Slack App + +Help a developer confirm that a Slack app they already built actually works. This is the last step of the build loop, after the `create-slack-app` skill scaffolds an app and the `slack-cli` skill runs it. + +The approach is simple and safe: + +1. **Run the app in a developer sandbox or a Free Team:** a sandbox for preference, or a Free Team the developer created for this. Never a workspace with real coworkers in it. +2. **Read the app's source** to learn what it actually listens for. +3. **Hand the developer concrete steps** to perform in Slack, then help them confirm the app responds. + +This is guided manual checking, not an automated test suite: you drive the setup and tell the developer what to type or click, and they confirm what they see. It works best for apps managed by the Slack CLI; there is a best-effort path for plain Bolt apps in Step 2. + +--- + +## Step 1: Set Up a Safe Place to Test + +### 1a. Detect the Slack CLI + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public Slack CLI is installed and resolve its command name. Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. The fingerprint check, alias fallback, and install instructions all live there; do not duplicate them here. Refer to the resolved command as `SLACK_CMD` throughout. If the CLI is not installed, guide the developer through that same step to install it, since running the app needs it. + +### 1b. Make sure there is a safe workspace to test in + +Testing belongs in a workspace nobody is working in: a developer sandbox for preference, or a Free Team the developer created for this. Never a workspace with real coworkers in it. + +- **Explain it from the live docs, not from here.** Use the `slack-docs` skill to fetch and summarize , so the recommendation always reflects the current docs rather than a copy that drifts out of date. Tell the developer that Slack recommends a sandbox for building and testing apps. +- **Find the current target.** Run `SLACK_CMD auth list` for the authenticated workspaces and their team IDs, and, from the project directory, `SLACK_CMD app list` for the apps already installed and their IDs. +- **Confirm the target is safe.** The CLI cannot tell a sandbox, a Free Team, and a workspace full of real users apart, so ask the developer which one they are pointed at. A sandbox or a Free Team they created for this is fine. A workspace with coworkers in it is not: stop and get them onto one of the other two. +- **If there is no safe target yet**, set one up with the `create-slack-app` skill (**Step 3: Choose Where to Install the App**), which owns the ranked targets, the `sandbox list` / `sandbox create` flow, and the Developer Program links. Either path finishes in the browser, so have the developer come back here once the workspace exists and they have logged into it. + +### 1c. Quick health check + +Catch obvious setup problems with the CLI's own validation before the slower hands-on checks: + +- `SLACK_CMD doctor`: checks the CLI, language runtime, and authentication. +- `SLACK_CMD manifest validate`: run from the project directory if the app has a manifest, to confirm the app configuration is well-formed. + +Surface anything these flag before moving on. + +--- + +## Step 2: Run the App + +Whichever path you use below, first turn the app's log level up to debug so you have the most context while testing. Prefer a way that leaves the developer's code untouched: read the logger setup to see whether it reads a log-level environment variable (some templates wire one such as `SLACK_LOG_LEVEL` or `LOG_LEVEL`). If it does, set that variable instead of editing source. For a CLI-managed app, `SLACK_CMD env set debug` stores it in the project `.env` that `slack run` reads; for a plain Bolt app, set it in the environment or `.env` the app already reads. Only when the logger reads no such variable should you edit the source, finding where the log level is set and switching it to debug for this run. + +### CLI-managed apps (recommended) + +Follow **Step 6: Running an App Locally (`slack run`)** in the `slack-cli` skill to start the local dev server in the background. This also installs the app into the target workspace, which matters for a fresh sandbox or Free Team where nothing is installed yet. Once it is running, file changes auto-reload. + +### Plain Bolt apps without the CLI (best-effort) + +If the app is a plain Bolt app started with `node` or `python` rather than the Slack CLI, this skill can still help, but the run path is best-effort and not the primary flow: + +- Point the app at the test workspace: set its bot and app-level tokens (from that workspace's app settings) in the environment or the `.env` file the app reads. +- Prefer socket mode so the app needs no public URL. This works only if the app is coded for socket mode and the app-level token has `connections:write`; adding tokens to an app scaffolded for HTTP will not deliver events. +- Start the app with its own command (for example `npm start` or `python app.py`) and watch its logs. + +Say plainly that this path is best-effort, and that the smoothest experience comes from a CLI-managed app. + +--- + +## Step 3: Try It Out in Slack and Confirm It Works + +This is the heart of the skill. Do not hand the developer a generic checklist. Ground every step in what _this_ app actually registers. + +### 3a. Read the source to find what the app listens for + +Read the app's listener code and list the interactions it registers. Depending on the framework these look like: + +- **[Slash commands](https://docs.slack.dev/interactivity/implementing-slash-commands.md):** a registered command name such as `/ship`. +- **[Shortcuts](https://docs.slack.dev/interactivity/implementing-shortcuts.md):** global or message shortcuts with a callback ID. +- **[Events](https://docs.slack.dev/apis/events-api.md):** subscribed events such as `app_mention`, `message`, or `reaction_added`. +- **[Actions](https://docs.slack.dev/interactivity/handling-user-interaction.md):** interactive components (buttons, selects) with an action ID. +- **[View submissions](https://docs.slack.dev/surfaces/modals.md):** modal submit handlers (`view_submission`). +- **[App Home](https://docs.slack.dev/surfaces/app-home.md):** an `app_home_opened` handler or a published Home tab. +- **[Assistant / agent](https://docs.slack.dev/ai.md):** an assistant or `assistant_thread_started` handler, common in the agent templates. + +Name the concrete identifiers you find (the actual command and callback names), not placeholders. + +### 3b. Turn each into a "do this, expect that" step + +For every registered interaction, give the developer a concrete step and what a working app should do in response. A few spots are non-obvious, so spell them out: + +- **Slash command** → type the command (for example `/ship`) in a channel or DM in the test workspace → expect the response the handler sends. +- **Global shortcut** → open the shortcuts menu (the lightning-bolt or `+` button in the message composer, depending on your client) and pick it → expect the modal or message it opens. +- **Message shortcut** → hover a message, open **More actions** (the `⋯` menu), pick the shortcut → expect its response. +- **Event** such as `app_mention` → @-mention the app in a channel it belongs to → expect its reply. +- **Button or select** → click the component in a message or modal the app posted → expect what the action handler does. +- **Modal submit** (`view_submission`) → submit the modal → expect the confirmation or side effect. +- **App Home** → click the app in the left sidebar to open its **Home** tab → expect the published view. + +### 3c. Confirm and report + +While the developer interacts, help them confirm it is working: + +- If the app runs under `slack run`, watch its logs (ask "show me the output from slack run") to confirm events arrive and to read any errors. +- If a response looks wrong (a malformed message or Block Kit view, or an API error), use the `block-kit` and `slack-api` skills to dig into the payload or method. + +Close with a short summary: what you and the developer confirmed working, and what they should eyeball themselves. Remember this is manual checking: you are helping the developer watch the app respond, not producing an automated pass or fail. + +--- + +## Notes + +- `SLACK_CMD` is a placeholder: always substitute the actual command name resolved in Step 1a. +- Scope: this skill tests an app that already exists. To create or scaffold one, use the `create-slack-app` skill; for raw CLI mechanics, use the `slack-cli` skill; for message or Block Kit formatting, use the `slack-messaging` and `block-kit` skills. +- Out of scope for now: automated test frameworks for Bolt, programmatically simulating user interactions, and driving the Slack UI with a browser. Today the developer performs the interactions; this skill makes sure they know exactly what to do and what to expect. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..5e09534 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,21 @@ +# Skills installed by `npx skills add`. Collapsed in GitHub diffs. +# Listed by name so skills you add to your app still show in diffs. +.agents/skills/block-kit/** linguist-generated +.agents/skills/create-slack-app/** linguist-generated +.agents/skills/deploy-slack-app/** linguist-generated +.agents/skills/slack-api/** linguist-generated +.agents/skills/slack-cli/** linguist-generated +.agents/skills/slack-docs/** linguist-generated +.agents/skills/slack-messaging/** linguist-generated +.agents/skills/slack-search/** linguist-generated +.agents/skills/test-slack-app/** linguist-generated +.claude/skills/block-kit/** linguist-generated +.claude/skills/create-slack-app/** linguist-generated +.claude/skills/deploy-slack-app/** linguist-generated +.claude/skills/slack-api/** linguist-generated +.claude/skills/slack-cli/** linguist-generated +.claude/skills/slack-docs/** linguist-generated +.claude/skills/slack-messaging/** linguist-generated +.claude/skills/slack-search/** linguist-generated +.claude/skills/test-slack-app/** linguist-generated +skills-lock.json linguist-generated diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..d84d138 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,68 @@ +{ + "version": 2, + "skills": { + "block-kit": { + "source": "slackapi/slack-skills-plugin", + "sourceType": "github", + "skillPath": "skills/block-kit/SKILL.md", + "computedHash": "04748a453ee9ad97263e82effb17f8ce6788cccc19375b386fc8023ba6708493", + "installMode": "copy" + }, + "create-slack-app": { + "source": "slackapi/slack-skills-plugin", + "sourceType": "github", + "skillPath": "skills/create-slack-app/SKILL.md", + "computedHash": "4a0c9055a219fe49614d990c74a0e4c1c3fbc8c4d005c6adbbdd91f106c6fe02", + "installMode": "copy" + }, + "deploy-slack-app": { + "source": "slackapi/slack-skills-plugin", + "sourceType": "github", + "skillPath": "skills/deploy-slack-app/SKILL.md", + "computedHash": "b45a2154bf461795d0cbab3d4c66fafc1293edfe0c0b54ad51a0e5f1f4e37e2a", + "installMode": "copy" + }, + "slack-api": { + "source": "slackapi/slack-skills-plugin", + "sourceType": "github", + "skillPath": "skills/slack-api/SKILL.md", + "computedHash": "e452e766b936e2a93ebe5fd2ec33ff3f1c68c6d6d4b64fd1eae1d4fb2ccc21f6", + "installMode": "copy" + }, + "slack-cli": { + "source": "slackapi/slack-skills-plugin", + "sourceType": "github", + "skillPath": "skills/slack-cli/SKILL.md", + "computedHash": "4506040f94cbe20252b26cc8463c8eec4b89899ae6e4e46a4137b7e6b91d0b20", + "installMode": "copy" + }, + "slack-docs": { + "source": "slackapi/slack-skills-plugin", + "sourceType": "github", + "skillPath": "skills/slack-docs/SKILL.md", + "computedHash": "07013bbbb0ffa8bf0f62ca3a8fb8c0762f970c2058c3a00544068cebfc4fee2f", + "installMode": "copy" + }, + "slack-messaging": { + "source": "slackapi/slack-skills-plugin", + "sourceType": "github", + "skillPath": "skills/slack-messaging/SKILL.md", + "computedHash": "4bb55059cf58a4614d896a0e8ad3421d8d5d0ceb76bc1fec6153914cae41934c", + "installMode": "copy" + }, + "slack-search": { + "source": "slackapi/slack-skills-plugin", + "sourceType": "github", + "skillPath": "skills/slack-search/SKILL.md", + "computedHash": "e3fe85c29469e157db02e0898b14c1532f9e35cbe239a814388c7cd2c1a24746", + "installMode": "copy" + }, + "test-slack-app": { + "source": "slackapi/slack-skills-plugin", + "sourceType": "github", + "skillPath": "skills/test-slack-app/SKILL.md", + "computedHash": "818e70481f7671d2cbc3e103631d626e4b29bc7520ffbfcfeffc6f920467850d", + "installMode": "copy" + } + } +} From 1b9dcbd15cff51b95f07bb312f8087fe8be71de5 Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Sun, 15 Nov 2026 15:22:40 -0600 Subject: [PATCH 2/2] chore: commit the Claude Code copy of the Slack skills --- .claude/skills/block-kit/SKILL.md | 284 ++++++++++ .../references/agent-progress-design.md | 162 ++++++ .../block-kit/references/common-patterns.md | 485 ++++++++++++++++++ .../references/data-display-design.md | 111 ++++ .../block-kit/references/design-principles.md | 195 +++++++ .../block-kit/references/home-tab-design.md | 88 ++++ .../block-kit/references/human-in-the-loop.md | 223 ++++++++ .../block-kit/references/modal-design.md | 150 ++++++ .claude/skills/create-slack-app/SKILL.md | 274 ++++++++++ .claude/skills/deploy-slack-app/SKILL.md | 200 ++++++++ .../references/deploy-heroku.sh | 186 +++++++ .../references/deploy-railway.sh | 130 +++++ .../deploy-slack-app/references/heroku.md | 129 +++++ .../deploy-slack-app/references/railway.md | 96 ++++ .claude/skills/slack-api/SKILL.md | 207 ++++++++ .claude/skills/slack-cli/SKILL.md | 253 +++++++++ .claude/skills/slack-docs/SKILL.md | 145 ++++++ .claude/skills/slack-messaging/SKILL.md | 84 +++ .claude/skills/slack-search/SKILL.md | 123 +++++ .claude/skills/test-slack-app/SKILL.md | 111 ++++ .gitignore | 3 +- 21 files changed, 3638 insertions(+), 1 deletion(-) create mode 100644 .claude/skills/block-kit/SKILL.md create mode 100644 .claude/skills/block-kit/references/agent-progress-design.md create mode 100644 .claude/skills/block-kit/references/common-patterns.md create mode 100644 .claude/skills/block-kit/references/data-display-design.md create mode 100644 .claude/skills/block-kit/references/design-principles.md create mode 100644 .claude/skills/block-kit/references/home-tab-design.md create mode 100644 .claude/skills/block-kit/references/human-in-the-loop.md create mode 100644 .claude/skills/block-kit/references/modal-design.md create mode 100644 .claude/skills/create-slack-app/SKILL.md create mode 100644 .claude/skills/deploy-slack-app/SKILL.md create mode 100755 .claude/skills/deploy-slack-app/references/deploy-heroku.sh create mode 100755 .claude/skills/deploy-slack-app/references/deploy-railway.sh create mode 100644 .claude/skills/deploy-slack-app/references/heroku.md create mode 100644 .claude/skills/deploy-slack-app/references/railway.md create mode 100644 .claude/skills/slack-api/SKILL.md create mode 100644 .claude/skills/slack-cli/SKILL.md create mode 100644 .claude/skills/slack-docs/SKILL.md create mode 100644 .claude/skills/slack-messaging/SKILL.md create mode 100644 .claude/skills/slack-search/SKILL.md create mode 100644 .claude/skills/test-slack-app/SKILL.md diff --git a/.claude/skills/block-kit/SKILL.md b/.claude/skills/block-kit/SKILL.md new file mode 100644 index 0000000..6696d55 --- /dev/null +++ b/.claude/skills/block-kit/SKILL.md @@ -0,0 +1,284 @@ +--- +name: block-kit +description: 'Use when a developer wants to build or validate Block Kit layouts for Slack messages, modals, or Home tabs: message layouts, modals/forms/dialogs, Home tab interfaces, interactive buttons or menus, or modifying existing Block Kit JSON. Also trigger on any Slack UI component (sections, actions, inputs, headers, alerts, tables, carousels), the words "blocks" or "Block Kit Builder", a request to preview rendered blocks, or pasted JSON like "type": "section". Validates via the blocks.validate API method.' +argument-hint: "[message | modal | home-tab]" +--- + +# Block Kit + +Help the developer build a rich Block Kit layout. If `$0` is exactly `message`, `modal`, or `home-tab`, treat it as the target surface. Otherwise (including if it's empty or any other value), ignore it and determine the surface in Step 1. + +This skill walks through surface selection, layout planning, JSON generation, and validation. Block types, elements, and fields come from the live docs (see **Source of Truth** below) — discover them and read each component's schema there, never from memory. + +> **Common Block Kit mistakes (and why):** A few errors recur often enough to flag up front. Most others are caught by `blocks.validate` in Step 5, so lean on validation rather than memorizing rules. +> +> - **`"type": "text"` is not a thing.** Text is a composition object: `{ "type": "plain_text", "text": "..." }` or `{ "type": "mrkdwn", "text": "..." }`. +> - **`markdown` is a _block_ type, not a text type.** A `markdown` block holds standard markdown; text objects inside other blocks use `mrkdwn` (see **mrkdwn vs. the `markdown` block** in Step 4). Slack's `mrkdwn` is `*bold*` / `_italic_` / `~strike~`, not `**bold**`. +> - **Messages need a top-level `text` fallback.** `blocks.validate` won't flag a missing one, but notifications and screen readers display it instead of the blocks — so summarize what the layout conveys rather than leaving it empty. + +--- + +## Source of Truth: the Live Docs + +Every block, element, and composition object is documented on `docs.slack.dev`. Append `.md` to any reference URL to fetch it as markdown with WebFetch (no auth required). + +- **Master index**: the authoritative list of every block, block element, and composition object, each linking to its own page: `https://docs.slack.dev/reference/block-kit.md`. WebFetch it to confirm a type exists and to get the link to its page. +- **Per-component pages** carry the full field schema (a fields table with required/optional flags and constraints, plus JSON examples): + - Blocks: `https://docs.slack.dev/reference/block-kit/blocks/-block.md` + - Block elements: `https://docs.slack.dev/reference/block-kit/block-elements/-element.md` + - Composition objects: `https://docs.slack.dev/reference/block-kit/composition-objects/.md` +- **The slug is not always the type name.** For example `datepicker` maps to `date-picker-element.md`, and every `*_select` menu (`static_select`, `users_select`, `multi_channels_select`, and so on) is documented on `select-menu-element.md`. When unsure of a slug, follow the link from the master index rather than building the URL by hand. +- **Surface payload structure** lives in the surface guides: messages at `https://docs.slack.dev/messaging/formatting-message-text.md`, modals at `https://docs.slack.dev/surfaces/modals.md`, and Home tabs at `https://docs.slack.dev/surfaces/app-home.md`. + +Never use a block type, element, or field you have not seen on a live page. + +--- + +## Fast Path (for clear, specific requests) + +If the developer's request is specific enough to determine both the target surface and the desired layout, collapse Steps 1-4 into a single pass: + +1. Determine the surface from `$0` or context +2. Fetch only the doc pages for the blocks and elements mentioned +3. Generate the JSON directly +4. Proceed to Step 5 (validation) + +**Fast-path indicators** (skip the full workflow): + +- Developer provides existing JSON to modify → use Modification Mode instead +- Developer names specific block types: "add an actions block with two buttons" +- Developer describes a well-known pattern: "approval message", "feedback form", "settings modal" +- Developer provides a complete description in one message with enough detail to build + +**Full-workflow indicators** (use Steps 1-7): + +- Vague requests: "make something cool", "build a dashboard" +- Exploratory: "what can Block Kit do?", "show me my options" +- Complex layouts: 10+ blocks, nested modals, conditional logic +- Developer asks for help deciding what to build + +--- + +## Modification Mode + +If the developer provides existing Block Kit JSON (pasted inline, in a file, or referenced from code), enter Modification Mode instead of the full creation workflow: + +1. **Parse the existing structure:** + - List each block by index, type, and a short description of its content + - Infer the surface: `"type": "modal"` = modal, `"type": "home"` = home tab, bare `blocks` array = message + +2. **Ask what changes they want:** + - Add blocks (where in the sequence?) + - Remove blocks (which ones?) + - Modify blocks (which block, what change?) + - Reorder blocks + +3. **Apply changes while preserving:** + - All existing `block_id` values (these are referenced in app interaction handlers) + - All existing `action_id` values (these map to event listeners) + - Existing styles, text content, and structure for unchanged blocks + +4. **Validate the modified JSON**: proceed to Step 5 (validation) + +**Detection:** If the developer's message contains a JSON array starting with `[{"type":` or a view object with `"blocks":`, enter Modification Mode automatically. If they say "edit", "update", "modify", or "change" in reference to existing blocks, ask them to provide the current JSON. + +--- + +## Step 1: Determine the Target Surface + +If `$0` is provided and matches one of `message`, `modal`, or `home-tab`, use it directly. + +Otherwise, ask the developer using AskUserQuestion: + +- **Message**: Conversational content posted to a channel or DM. Max 50 blocks. +- **Modal**: A dialog or form opened by a user action. Max 100 blocks. +- **Home tab**: A persistent, per-user dashboard in the App Home. Max 100 blocks. + +Once the surface is determined, use the correct payload structure for it: + +- **Message**: a `{ "text": "Fallback text", "blocks": [...] }` object posted via `chat.postMessage` (and friends). The `text` field is the notification/accessibility fallback. For message text formatting (mrkdwn, mentions, dates), see `https://docs.slack.dev/messaging/formatting-message-text.md`. +- **Modal**: a view object (`{ "type": "modal", "title": ..., "blocks": [...] }`). For the full view object structure, lifecycle, and the rule that `submit` is required when the view contains any `input` block, see `https://docs.slack.dev/surfaces/modals.md`. +- **Home tab**: a view object (`{ "type": "home", "blocks": [...] }`) published via `views.publish`. For structure and behavior, see `https://docs.slack.dev/surfaces/app-home.md`. + +--- + +## Step 2: Understand What to Build + +Ask the developer to describe what they want their layout to look like or accomplish. + +If they need inspiration, suggest examples — several map directly onto a ready-made template in `references/common-patterns.md` (named in parentheses), which you can start from in Step 3: + +- "A feedback form with a text input and a category selector" (Simple Form Modal) +- "A deploy-failure notification with a description and next-step buttons" (Notification Alert), or "an approval request with Approve/Reject buttons" (Approval Message) +- "A dashboard home tab with a welcome header, key metrics in fields, and quick-action buttons" (Dashboard Home Tab) +- "A settings modal with dropdowns, checkboxes, and a time picker" (Settings Modal with Multiple Input Types) +- "A table of sprint tasks with status and points" (Data Table) +- "A deploy summary with bold text, a link, and a bullet list" (Rich Text Section) +- "A row-level '⋯' menu for edit/duplicate/delete actions" (Row Actions with Overflow Menu) +- "A product card with an image, price, and Add to Cart button" (Card Preview) + +Get enough detail to plan the layout before generating any JSON. + +--- + +## Step 3: Plan the Block Layout + +Based on the developer's description: + +1. **Fetch only what you need** from the live docs: + - WebFetch the master index (`https://docs.slack.dev/reference/block-kit.md`) to confirm the block and element types you plan to use exist and to grab links to their pages. + - Consult `references/design-principles.md` for design appropriateness — which block fits the shape of the content (table vs. stacked sections, card vs. loose blocks), emphasis, reading order, and accessibility. It is guidance on building layouts that read well, not on validity. Depending on the layout, also consult: + - `references/modal-design.md` for modals and forms: titles and submit labels, input labels and hints, multi-step flows, validation errors, and loading or success states. + - `references/home-tab-design.md` for Home tabs: what goes at the top, empty and first-run states, keeping the view current, different views per role, and review surfaces for agents. + - `references/data-display-design.md` for numbers and records: choosing between `section` fields, `table`, `data_table`, and `data_visualization` charts, and presenting each clearly. + - `references/agent-progress-design.md` for showing an agent's work with `plan` and `task_card` blocks or streamed task updates. + - `references/human-in-the-loop.md` for approval gates, approving several proposed actions in one message, clarifying choices, and edit-before-send. + - Check `references/common-patterns.md` if the request matches a common pattern; start from the template instead of building from scratch. + - Defer reading individual component pages until Step 4, when you build each block's fields. +2. Propose a numbered block outline. For example: + + ```text + 1. header: "Weekly Report" + 2. section: Summary text with a datepicker accessory + 3. divider + 4. section: Status fields (Name, Role, Team) + 5. actions: "Approve Report" button (primary) and "Reject" button (unstyled) + ``` + +3. Present the outline to the developer and ask for approval or changes before generating JSON. + +**Surface constraints to check:** + +- Block count limit: 50 for messages, 100 for modals/home tabs +- Modal-specific: if using `input` blocks, the modal payload must include a `submit` field +- Table: only one `table` block per message +- Charts: at most two `data_visualization` blocks per message +- Alert: the `alert` block is available only in modals. In messages, state severity in words in a `header` or `section`. +- Surface compatibility (whether a block is valid on the chosen surface) and element compatibility (whether an element is allowed inside a given block) are not always spelled out on a component's doc page. Check `references/design-principles.md`'s surface and limits table for these. **`blocks.validate` in Step 5 does not enforce them** — it checks block and element shape only, and will return `ok: true` for a block on the wrong surface or over a count limit. Don't treat a pass there as confirmation of surface or count compliance. + +--- + +## Step 4: Generate the Block Kit JSON + +Once the layout is approved, build each block from its live doc page, fetching each page's fields table (required vs optional, constraints) and JSON example with WebFetch. The URL patterns are in **Source of Truth** above; the one slug to remember is that every `*_select` menu (`static_select`, `users_select`, `multi_channels_select`, …) lives on `select-menu-element.md`. Fetch pages as you need them and reuse what you have already fetched — don't re-fetch the same page for every block of the same type. Then build the payload block-by-block and wrap it in the surface structure from Step 1. + +**Guidelines:** + +- Use descriptive `action_id` values (e.g., `"approve_report_btn"` not `"action_1"`) — they identify the element in your interaction handlers +- Include `block_id` values where the developer will need them for interaction handling +- For modals, include `title`, `submit`, `close`, and `callback_id`; for home tabs, the `type: "home"` wrapper +- Use `mrkdwn` text for rich formatting, `plain_text` where required (headers, labels, modal title) + +**mrkdwn vs. the `markdown` block:** `section` and `context` blocks format text with Slack's `mrkdwn` (`*bold*`, not `**bold**`). The separate `markdown` block (messages only) renders standard markdown and is for AI/LLM-generated or long-form content that is already in standard markdown. `references/design-principles.md`, **Text: rich_text, mrkdwn, and the markdown block**, explains when to use each, including `rich_text` for formatted text you build in code. + +**Accessibility** is easy to skip and hard to retrofit, so build it in now. Apply `references/design-principles.md`, **Accessibility and fallback**, as you write each block: it covers the `text` fallback, `alt_text`, color and emoji, button labels, and text equivalents for tables and charts. + +Present the complete payload to the developer in the Step 1 surface structure. + +--- + +## Step 5: Validate + +**Always validate.** `blocks.validate` is a public Web API method, so no auth token is required. + +The authoritative reference for this method (its parameters, auth requirements, and response/error shape) is the live doc. WebFetch it before relying on any detail here: `https://docs.slack.dev/reference/methods/blocks.validate.md`. It documents the accepted parameters (`blocks` for a message's blocks array, `view` for a modal/home-tab view, `message` for a full message payload; send exactly one) and the response shape. + +### 5a. Build the validation request + +Prefer the Slack CLI when it's available, since it reuses the slack-cli skill's CLI detection and needs no token wrangling. If the CLI isn't installed, fall back to curl. Both call the same public method and return the same response, so Step 5b applies either way. + +**Path A: Slack CLI (preferred).** + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public CLI is installed and resolve its command (`SLACK_CMD`). Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. + +If the CLI is available, use the `slack-cli` skill, **Step 4: Calling Web API Methods (`slack api`)**, to invoke it. That step covers the `SLACK_CMD api key=value …` syntax. Run `SLACK_CMD api --help` first to confirm the syntax **and the flag that skips authentication**. `blocks.validate` needs no token, so call it without authentication. Don't hard-code that flag from memory; read it from the help output so this stays correct if it's ever renamed. Pass the payload as a positional `key=value` argument: `blocks=` for messages, or `view=` for modals and home tabs. + +**Path B: curl (fallback, when the CLI isn't installed).** + +POST to the endpoint with the **Bash tool**. The API uses form-urlencoded encoding, so pass the JSON directly as the parameter value. + +**For messages**, send the `blocks` array as a form-encoded parameter: + +```bash +curl -s -X POST 'https://slack.com/api/blocks.validate' \ + -d 'blocks=[ ... the blocks array ... ]' +``` + +**For modals and home tabs**, send the complete view object in the `view` field: + +```bash +curl -s -X POST 'https://slack.com/api/blocks.validate' \ + -d 'view={ "type": "modal", "title": ..., "blocks": [...] }' +``` + +### 5b. Handle the response + +**Success:** + +```json +{ "ok": true } +``` + +Tell the developer their blocks are valid. + +**Failure:** + +```json +{ + "ok": false, + "error": "invalid_blocks", + "errors": [ + { + "code": "missing_field", + "message": "missing required field: type", + "field": "type", + "pointer": "/0" + } + ] +} +``` + +When validation fails: + +1. Read each error. `pointer` is a JSON pointer to the offending node (e.g., `/0` = first block, `/2/elements/1` = second element of the third block, `/0/text/type` = the `type` field of the first block's text object). `message` describes the problem, and `constraint` (when present) names the rule that failed and its expected values. +2. Fix the JSON. For the authoritative meaning of an error code and the field requirements behind it, consult the live method doc (`https://docs.slack.dev/reference/methods/blocks.validate.md`) and the relevant block/element/composition-object page you fetched in Steps 3-4. +3. Re-validate. Repeat until `"ok": true`. + +--- + +## Step 6: Deliver the Final Output + +Present the validated payload, then help the developer put it to use. + +### Send it + +Building the payload is this skill's job; sending it (`chat.postMessage`, `views.open`, `views.publish`, and the token/scope handling around them) belongs to the Web API layer. To call the right method — via the Slack CLI, raw curl, or a Bolt SDK — use the `slack-api` skill, **Step 4: Call the Method (Manage)**, passing this payload as the method's `blocks` argument (messages) or `view` argument (modals and home tabs). That skill matches the argument names to the SDK or HTTP call so we don't duplicate them here. + +### Preview it + +Help the developer view their layout with the **Block Kit Builder**. Prefer the Slack CLI if it is installed. The CLI automatically loads the blocks, saving the developer from copying and pasting. If the CLI is not available, provide the standard Builder link instead. + +**Path A: Slack CLI (preferred).** + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public CLI is installed and resolve its command (`SLACK_CMD`). Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. + +If the CLI is available, run `SLACK_CMD blocks preview --help` to see how to pass the blocks and open the preview. The command loads the blocks into the Block Kit Builder in the developer's browser. + +Because you run the CLI non-interactively, this command also needs a `--team` flag. Resolve the team ID with the `slack-cli` skill, **Step 2: Command Discovery via Help**, whose "Resolving `--app` and `--team` values" guidance covers running `SLACK_CMD auth list`; Any authenticated workspace works for a preview, if several are available, pick one and mention which you used rather than blocking on the choice. + +**Path B: Block Kit Builder link (fallback, when the CLI isn't installed).** + +Offer the Block Kit Builder link so the developer can paste the JSON in and tweak visually: `https://app.slack.com/block-kit-builder`. Builder needs an object (`{ "blocks": [...] }` or a full view object), not a bare array. + +--- + +## Step 7: Iterate + +Ask whether the developer wants to add, modify, remove, or reorder blocks, or build a layout for a different surface. If they want to change the layout you just produced, re-enter **Modification Mode** (it preserves their `block_id`/`action_id` values); for a fresh layout, loop back to Step 3. + +--- + +## Notes + +- **Scope:** this skill owns building and validating the Block Kit payload — choosing the surface, composing the JSON from the live docs, and confirming it with `blocks.validate`. Sending it lives in the Web API layer (the `slack-api` skill), and CLI detection/auth in the `slack-cli` skill. +- **`blocks.validate` needs no auth** — it's a public method, so it works without a token whether you call it via the CLI or curl. Always validate before finalizing (Step 5). diff --git a/.claude/skills/block-kit/references/agent-progress-design.md b/.claude/skills/block-kit/references/agent-progress-design.md new file mode 100644 index 0000000..0f8a0c6 --- /dev/null +++ b/.claude/skills/block-kit/references/agent-progress-design.md @@ -0,0 +1,162 @@ +# Agent Progress Design: Plans and Task Cards + +Guidance on showing an agent's work while it happens, using `plan` and `task_card` blocks, and +their streaming equivalents, the `task_update` and `plan_update` chunks. This covers +_appropriateness_: when to show steps, how to word them, and how they should change over time. +For field schemas, see the `plan`, `task_card`, and `url_source` element pages. For the streaming +API, see `https://docs.slack.dev/reference/methods/chat.startStream.md` and Slack's agent design +guide, `https://docs.slack.dev/concepts/agent-design.md`. Apply these principles unless the +developer explicitly asks otherwise. + +Both blocks are **messages only**. A `plan` holds up to 50 task cards, and each `task_id` in a +plan must be unique. + +## Pick the lightest progress signal that works + +Progress UI is for the user, not a log of everything the agent did. Use only as much as the work +needs: + +| The work is… | Show | +|---|---| +| a message that needs no answer (thanks, a passing mention, people talking to each other) | nothing, or a single emoji reaction | +| quick (a few seconds) or a single lookup | a status only (`agents.sessions.setStatus`, such as "Searching your workspace…") | +| a few steps, with the steps mixed into the answer | `task_update` chunks in the default `timeline` display mode: individual task cards between the streamed text | +| multi-step work where the agent is making decisions | a `plan`: `task_display_mode: "plan"` when streaming, or a `plan` block you update with `chat.update` | + +- **Use a plan for decisions, not data fetching.** Slack's guidance is to save plans for + multi-step work where the agent chooses what to do next. Three lookups and an answer don't need + a plan. +- **Make the plan secondary to the answer.** The plan explains how the agent got there; the + answer is what the user came for. Put the answer after the plan and make it able to stand on its + own. +- **Acknowledge right away, before any progress UI.** Set a status, or add a working reaction + such as 👀 to the user's message and remove it when the reply lands. Then the user knows the + agent saw the message, even if it decides to stay quiet. +- **If you react instead of replying, give each emoji one meaning** (👍 "got it", ✅ "done", + ❤️ "thanks") and use only those. A reaction is a reply, so it should be as clear as one. + +## Streaming vs. a posted message + +- **When streaming** (`chat.startStream` → `chat.appendStream` → `chat.stopStream`), send + progress as `task_update` chunks. Choose `task_display_mode` when you start the stream: + `timeline` (the default) for cards interleaved with the streamed text, or `plan` for one grouped + plan. Send a `task_update` with the same `id` to change a task's status, and a `plan_update` + chunk to retitle the plan. Each `task_update` and `plan_update` chunk is limited to 256 + characters, so keep `details` and `output` short. +- **Send a task's `details` once.** On an update with the same `id`, Slack adds the new `details` + to the earlier text instead of replacing it, with no separator. Send details either while the + task is in progress or when it completes, not both, and never send placeholder text you'll want + to replace. +- **Open the stream when there's something to show**, not when the run starts. If the agent ends + up staying quiet or only reacting, nothing is posted, so there's no empty message to clean up. +- **Send stream updates one at a time, in order, and wait for them all before + `chat.stopStream`.** If updates are fired off without waiting, a task's final `complete` can + arrive after the stream stops, which leaves that task spinning forever. +- **When not streaming**, post a message with a `plan` block and update it in place with + `chat.update` as each task changes. Don't post a new message per step, and don't call + `chat.update` more than about once every 3 seconds. Collect several changes into one update. +- **Don't build a progress view from text** ("Step 3 done ✅" lines in a `section`). The plan and + task card blocks already provide status icons, structure, and accessibility. + +## Give each piece of text one job + +A plan has three layers of text. Keep each one to its job so the plan reads at a glance: + +| Layer | Says | While working | When done | On failure | +|---|---|---|---|---| +| plan title | where the run is overall | what the agent is doing now: "Searching Linear" | the outcome: "Worked for 12s" | "Error" or "Stopped" | +| task title | the action | present tense: "Searching Linear issues" | past tense: "Searched Linear issues" | "Couldn't search Linear issues" | +| task details / output | the facts | the subject: "#incidents, last 7 days" | the result: "3 matches: INC-41, INC-44, …" | the reason: "Linear needs a reconnect" | + +- **Task titles name the action, not the subject.** Keep the subject (a query, a channel, a file + name) in the details, so titles stay short and the same tool always reads the same way. +- **Keep each title to one short phrase.** Slack's guidance is that a step should be one short + phrase; a paragraph of reasoning is too much. +- **Name the system in plain language, not the API**: "Checking your calendar", not "Calling + `events.list`". This also shows the user what the agent can access. For tools from a connected + app, put the app's name in front of the details: "Todoist · 3 tasks due today". +- **Lead with the verb and object**: "Drafting the reply to Priya", "Creating a Linear issue". +- **Make write actions obvious.** A task that creates, sends, or deletes something should say so + in its title ("Sending summary to #eng"). Read-only lookups can be grouped or kept low-key. +- **Never show raw tool output.** Turn results into a human line: a count and a few names ("12 + messages", "3 files: plan.md, notes.md, …"). Never show JSON, and if there's nothing useful to + say, say nothing rather than "Done". +- **Show retries as retries.** If the agent calls the same tool again after an error, title it + "Retrying: Searching Linear issues", or add "attempt 2" to the details, so it doesn't look like a + duplicate step. + +## Status, details, output, and sources + +- **Status reflects what's actually happening.** Set a task to `in_progress` only when the agent + starts it, then switch it to `complete` or `error`. Don't mark everything complete at the end; + the point is to show live progress. +- **Show the whole plan up front when the steps are known in advance.** Tasks that haven't + started can use `pending` in plan display mode. The plan guide documents it, but the + `task_card` page lists only `in_progress`, `complete`, and `error`, so check the live page. + When the agent decides steps as it goes, add tasks as they start rather than inventing a plan it + might not follow. +- **`details` is what the task did; `output` is what it found.** Keep both to a line or two of + `rich_text`: details "Searched #incidents for the last 7 days", output "Found 3 related + incidents". The full answer goes in the message body, not in a task's output. +- **Attach `sources` to the task that used them** (`url_source` elements). This keeps + attribution next to the step it supports, so you don't need a separate citation list for those + steps. +- **Use `hide_title`** only when the task's details already say everything the title would. + +## Voice + +- **Keep one voice everywhere**, either first person ("I found 3 issues") or neutral ("Found 3 + issues"), across status, task titles, errors, and recaps. Slack's own AI uses the neutral voice. + Don't give the agent feelings or a gender, and skip casual apologies. + +## When something goes wrong + +- **Mark the failing task `error`, not the whole plan.** Leave completed tasks `complete` so the + user can see how far the agent got. +- **Say what failed and why in that task's `output`**, in plain language: "No access to the + Project Beta board". +- **Name the cause and the fix** rather than "Something went wrong." Tell apart a credential the + user must fix ("Todoist needs a reconnect", with a Reconnect button), a temporary limit ("Rate + limited, try again in a minute"), and a bug on your side ("Something broke on my end. I've + logged it, please try again"). +- **Set the plan title to "Error"** when the run ends with a failed step, so the outcome is + visible even when the plan is collapsed. +- **Follow the plan with recovery options**: two or three next steps as buttons (Retry, Change Request, Ask an Admin), not a dead end. See `human-in-the-loop.md` for how to structure those + choices. +- **Clear the status when the agent stops**, even on failure, so the thread isn't left showing + "thinking" forever. Set `agents.sessions.setStatus` to `active`, or to `suspended` if the user + has to do something before the agent can continue, such as when the reply ends with a + clarifying question. + +## Stopping and interruptions + +- **Honor the Stop button.** When the user stops a run (the `agent_session_stopped` event), + cancel the work, end the stream with the plan title "Stopped", and post one short line: "Okay, + I stopped." Leave completed tasks as they are, so the user can see what was already done. +- **If the user sends a new message mid-run, start over quietly.** When newer messages change the + request, abandon the current run without a "stopped" note and respond to the thread as it is + now. The user didn't ask to stop, so there's nothing to acknowledge. +- **Cancel pending approvals with the run.** If a stopped run was waiting on an approval, mark the + approval as cancelled (see `human-in-the-loop.md`) so its buttons don't outlive the run. + +## When the work is done + +- **Set the final plan title to the outcome**, such as "Worked for 12s", so a collapsed plan still + tells the user the run finished and roughly how long it took. +- **End with a short recap**: what happened, with links to anything created or changed, and + anything skipped and why ("Couldn't assign to <@U123>, who isn't on the project"). Keep the + recap shorter than the task took to describe. +- **Add `feedback_buttons`** in a `context_actions` block after the final answer, not inside the + plan. + +## Quick self-review + +1. Does this work need a plan, or would a status or timeline task updates be enough? +2. Does each task title name the action, in plain language, with the facts in the details? +3. Do statuses change live, do write actions stand out, and are retries labeled? +4. Are `details` and `output` short (under 256 characters when streamed), sent once, never raw + JSON, with sources on the task that used them? +5. If a step fails, does the user see what worked, what didn't, and what they can do next? +6. Does the plan title end as the outcome ("Worked for…", "Error", "Stopped"), with no task left + spinning? +7. Is the final answer complete on its own, with the plan clearly secondary? diff --git a/.claude/skills/block-kit/references/common-patterns.md b/.claude/skills/block-kit/references/common-patterns.md new file mode 100644 index 0000000..9e3a8e1 --- /dev/null +++ b/.claude/skills/block-kit/references/common-patterns.md @@ -0,0 +1,485 @@ +# Common Block Kit Patterns + +> Starting scaffolds for frequent use cases — copy one and customize rather than building from scratch. +> They were valid when written, but the live docs (the skill's **Source of Truth**) remain authoritative for field schemas, and Block Kit evolves. Confirm any field you change against the component's doc page, and re-run the customized payload through `blocks.validate` (Step 5) before shipping. +> `[M]` patterns show `{ "blocks": [...] }` — add `channel` and a `text` fallback when calling `chat.postMessage` per Step 1; don't skip `text`, it matters for accessibility. + +--- + +## Approval Message [M] + +A notification with context and Approve/Reject buttons. + +```json +{ + "blocks": [ + { + "type": "header", + "text": { "type": "plain_text", "text": "New approval request" } + }, + { + "type": "section", + "text": { "type": "mrkdwn", "text": "*Requester:* <@U0123456789>\n*Type:* Access request\n*Details:* Production database read access" } + }, + { "type": "divider" }, + { + "type": "actions", + "block_id": "approval_actions", + "elements": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "Approve" }, + "style": "primary", + "action_id": "approve_btn", + "value": "request_123" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "Reject" }, + "style": "danger", + "action_id": "reject_btn", + "value": "request_123" + } + ] + } + ] +} +``` + +**Customization points:** Header text, section fields, button values, adding a confirmation dialog to the Reject button. + +--- + +## Simple Form Modal [V] + +A modal with text input, select menu, and optional checkbox. + +```json +{ + "type": "modal", + "callback_id": "feedback_form", + "title": { "type": "plain_text", "text": "Send feedback" }, + "submit": { "type": "plain_text", "text": "Send Feedback" }, + "close": { "type": "plain_text", "text": "Cancel" }, + "blocks": [ + { + "type": "input", + "block_id": "category_block", + "label": { "type": "plain_text", "text": "Category" }, + "element": { + "type": "static_select", + "action_id": "category_select", + "placeholder": { "type": "plain_text", "text": "Choose a category" }, + "options": [ + { "text": { "type": "plain_text", "text": "Bug report" }, "value": "bug" }, + { "text": { "type": "plain_text", "text": "Feature request" }, "value": "feature" }, + { "text": { "type": "plain_text", "text": "General feedback" }, "value": "general" } + ] + } + }, + { + "type": "input", + "block_id": "description_block", + "label": { "type": "plain_text", "text": "Description" }, + "element": { + "type": "plain_text_input", + "action_id": "description_input", + "multiline": true, + "placeholder": { "type": "plain_text", "text": "Ex. The export button does nothing" } + } + }, + { + "type": "input", + "block_id": "urgency_block", + "label": { "type": "plain_text", "text": "Priority" }, + "element": { + "type": "radio_buttons", + "action_id": "urgency_select", + "options": [ + { "text": { "type": "plain_text", "text": "Low" }, "value": "low" }, + { "text": { "type": "plain_text", "text": "Medium" }, "value": "medium" }, + { "text": { "type": "plain_text", "text": "High" }, "value": "high" } + ] + }, + "optional": true + } + ] +} +``` + +**Customization points:** Title, callback_id, input types, options list, adding/removing input blocks. + +--- + +## Notification Alert [M] + +A notification headline with description, timestamp context, and next actions. The `alert` block is available only in modals, so a message states its severity in words in the `header`. Keep emoji out of headers and buttons; Slack's style uses emoji only in running text. + +```json +{ + "blocks": [ + { + "type": "header", + "text": { "type": "plain_text", "text": "Deployment failed: api-gateway" } + }, + { + "type": "section", + "text": { "type": "mrkdwn", "text": "The deployment to *production* failed during the health check phase.\n\n*Error:* `Connection timeout after 30s`\n*Commit:* `a1b2c3d`" } + }, + { + "type": "context", + "elements": [ + { "type": "mrkdwn", "text": "Triggered by <@U0123456789> · " } + ] + }, + { + "type": "actions", + "elements": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "View Logs" }, + "url": "https://logs.example.com/deploy/456", + "action_id": "view_logs_btn" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "Retry Deploy" }, + "style": "primary", + "action_id": "retry_deploy_btn" + } + ] + } + ] +} +``` + +**Customization points:** Severity word and emoji in the header ("Deployment failed", "Warning: disk at 90%"), description text, action buttons. Also set the message's top-level `text` fallback to the headline, such as "Deployment failed: api-gateway". In a modal, use an `alert` block with a `level` instead of the header. + +--- + +## Dashboard Home Tab [H] + +A welcome dashboard with metrics fields and quick-action buttons. + +```json +{ + "type": "home", + "blocks": [ + { + "type": "header", + "text": { "type": "plain_text", "text": "Welcome to AppName" } + }, + { + "type": "section", + "text": { "type": "mrkdwn", "text": "Here's your overview for today:" } + }, + { + "type": "section", + "fields": [ + { "type": "mrkdwn", "text": "*Open tickets*\n12" }, + { "type": "mrkdwn", "text": "*Resolved today*\n5" }, + { "type": "mrkdwn", "text": "*Average response*\n2.4 hours" }, + { "type": "mrkdwn", "text": "*SLA status*\nOn track :white_check_mark:" } + ] + }, + { "type": "divider" }, + { + "type": "actions", + "elements": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "New Ticket" }, + "style": "primary", + "action_id": "new_ticket_btn" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "My Queue" }, + "action_id": "my_queue_btn" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "Settings" }, + "action_id": "settings_btn" + } + ] + } + ] +} +``` + +**Customization points:** Metrics fields, action buttons, adding image blocks or additional sections. + +--- + +## Confirmation with Dialog [M] + +An action button with a confirmation dialog attached (prevents accidental clicks). + +```json +{ + "blocks": [ + { + "type": "section", + "text": { "type": "mrkdwn", "text": "Are you sure you want to shut down *prod-server-01*?" } + }, + { + "type": "actions", + "elements": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "Shut Down" }, + "style": "danger", + "action_id": "shutdown_btn", + "value": "prod-server-01", + "confirm": { + "title": { "type": "plain_text", "text": "Shut down server" }, + "text": { "type": "plain_text", "text": "This will immediately terminate the server. Active connections will be dropped." }, + "confirm": { "type": "plain_text", "text": "Shut Down" }, + "deny": { "type": "plain_text", "text": "Cancel" }, + "style": "danger" + } + } + ] + } + ] +} +``` + +**Customization points:** Confirmation title/text (title max 100 chars, text max 300 chars, confirm/deny max 30 chars), button style. + +--- + +## Data Table [M] + +A structured table for displaying tabular data. Only one table block per message. + +```json +{ + "blocks": [ + { + "type": "header", + "text": { "type": "plain_text", "text": "Sprint summary" } + }, + { + "type": "table", + "column_settings": [ + { "is_wrapped": true }, + { "align": "center" }, + { "align": "right" } + ], + "rows": [ + [ + { "type": "raw_text", "text": "Name" }, + { "type": "raw_text", "text": "Status" }, + { "type": "raw_text", "text": "Points" } + ], + [ + { "type": "raw_text", "text": "Auth refactor" }, + { "type": "raw_text", "text": "In Progress" }, + { "type": "raw_text", "text": "5" } + ], + [ + { "type": "raw_text", "text": "API docs update" }, + { "type": "raw_text", "text": "Done" }, + { "type": "raw_text", "text": "2" } + ], + [ + { "type": "raw_text", "text": "Bug #1234" }, + { "type": "raw_text", "text": "Blocked" }, + { "type": "raw_text", "text": "3" } + ] + ] + } + ] +} +``` + +**Customization points:** Column settings (alignment: `left`/`center`/`right`, wrapping: `is_wrapped`), row data, cell type (`raw_text` for plain content, `rich_text` for formatted content with links/emoji/mentions). Max 100 rows, max 20 cells per row. First row is the header. Only one table block per message. + +--- + +## Settings Modal with Multiple Input Types [V] + +A modal combining different input types for a settings/preferences form. + +```json +{ + "type": "modal", + "callback_id": "settings_modal", + "title": { "type": "plain_text", "text": "Notification settings" }, + "submit": { "type": "plain_text", "text": "Save" }, + "close": { "type": "plain_text", "text": "Cancel" }, + "blocks": [ + { + "type": "input", + "block_id": "channel_block", + "label": { "type": "plain_text", "text": "Notification channel" }, + "element": { + "type": "conversations_select", + "action_id": "channel_select", + "default_to_current_conversation": true + } + }, + { + "type": "input", + "block_id": "frequency_block", + "label": { "type": "plain_text", "text": "Digest frequency" }, + "element": { + "type": "static_select", + "action_id": "frequency_select", + "options": [ + { "text": { "type": "plain_text", "text": "Real-time" }, "value": "realtime" }, + { "text": { "type": "plain_text", "text": "Hourly" }, "value": "hourly" }, + { "text": { "type": "plain_text", "text": "Daily" }, "value": "daily" } + ], + "initial_option": { "text": { "type": "plain_text", "text": "Daily" }, "value": "daily" } + } + }, + { + "type": "input", + "block_id": "events_block", + "label": { "type": "plain_text", "text": "Notify me about" }, + "element": { + "type": "checkboxes", + "action_id": "events_checkboxes", + "options": [ + { "text": { "type": "plain_text", "text": "New deployments" }, "value": "deploys" }, + { "text": { "type": "plain_text", "text": "Failed builds" }, "value": "failures" }, + { "text": { "type": "plain_text", "text": "PR reviews needed" }, "value": "reviews" } + ] + } + }, + { + "type": "input", + "block_id": "quiet_hours_block", + "label": { "type": "plain_text", "text": "Quiet hours start" }, + "element": { + "type": "timepicker", + "action_id": "quiet_start", + "initial_time": "22:00", + "placeholder": { "type": "plain_text", "text": "Select time" } + }, + "optional": true + } + ] +} +``` + +**Customization points:** Input types, options, initial values, adding `hint` text to inputs, marking fields as `optional`. + +--- + +## Rich Text Section [M] + +Formatted text with bold, links, and a bullet list — the WYSIWYG-composer format, for layouts needing richer inline styling or structure than a `mrkdwn` string offers. + +```json +{ + "blocks": [ + { + "type": "rich_text", + "elements": [ + { + "type": "rich_text_section", + "elements": [ + { "type": "text", "text": "Deploy summary: " }, + { "type": "text", "text": "3 services", "style": { "bold": true } }, + { "type": "text", "text": " updated. See the " }, + { "type": "link", "url": "https://example.com/changelog", "text": "changelog" }, + { "type": "text", "text": " for details." } + ] + }, + { + "type": "rich_text_list", + "style": "bullet", + "elements": [ + { "type": "rich_text_section", "elements": [{ "type": "text", "text": "api-gateway: v2.4.1" }] }, + { "type": "rich_text_section", "elements": [{ "type": "text", "text": "auth-service: v1.9.0" }] } + ] + } + ] + } + ] +} +``` + +**Customization points:** Text styling (`bold`, `italic`, `strike`, `code`) on individual `text` elements, list `style` (`bullet` or `ordered`), adding `rich_text_quote` or `rich_text_preformatted` elements, mixing in `user`/`channel`/`emoji` elements for mentions and reactions inline. + +--- + +## Row Actions with Overflow Menu [M] + +A row-level "⋯" menu for actions that don't need dedicated buttons (edit, duplicate, delete). + +```json +{ + "blocks": [ + { + "type": "actions", + "block_id": "row_actions_block", + "elements": [ + { + "type": "overflow", + "action_id": "row_actions", + "options": [ + { "text": { "type": "plain_text", "text": "Edit" }, "value": "edit" }, + { "text": { "type": "plain_text", "text": "Duplicate" }, "value": "duplicate" }, + { "text": { "type": "plain_text", "text": "Delete" }, "value": "delete" } + ], + "confirm": { + "title": { "type": "plain_text", "text": "Delete item" }, + "text": { "type": "plain_text", "text": "This can't be undone." }, + "confirm": { "type": "plain_text", "text": "Delete" }, + "deny": { "type": "plain_text", "text": "Cancel" }, + "style": "danger" + } + } + ] + } + ] +} +``` + +**Customization points:** Option list (max 5), which option(s) trigger the `confirm` dialog, using `overflow` as a `section` block's `accessory` instead of inside `actions` for a single row's trailing menu. + +--- + +## Card Preview [M] + +An image/thumbnail-driven card — link preview, product card, or similar — with a title, body, and action buttons. + +```json +{ + "blocks": [ + { + "type": "card", + "hero_image": { + "type": "image", + "image_url": "https://example.com/product-photo.png", + "alt_text": "Wireless noise-cancelling headphones, matte black" + }, + "title": { "type": "plain_text", "text": "Noise-Cancelling Headphones" }, + "subtitle": { "type": "plain_text", "text": "$149.99 — In stock" }, + "body": { "type": "mrkdwn", "text": "30-hour battery life, USB-C fast charging, and adaptive noise cancellation." }, + "actions": [ + { + "type": "button", + "text": { "type": "plain_text", "text": "View Product" }, + "url": "https://example.com/products/headphones", + "action_id": "view_product_btn" + }, + { + "type": "button", + "text": { "type": "plain_text", "text": "Add to Cart" }, + "style": "primary", + "action_id": "add_to_cart_btn", + "value": "headphones_sku_123" + } + ] + } + ] +} +``` + +**Customization points:** `hero_image` (top image) vs. `icon` (small image beside title/subtitle — mutually exclusive with `slack_icon`), `subtext` for secondary detail below `body`, up to 3 `actions` buttons. At least one of `hero_image`, `title`, `actions`, or `body` is required; `title`/`subtitle` max 150 chars, `body`/`subtext` max 200 chars. diff --git a/.claude/skills/block-kit/references/data-display-design.md b/.claude/skills/block-kit/references/data-display-design.md new file mode 100644 index 0000000..803423d --- /dev/null +++ b/.claude/skills/block-kit/references/data-display-design.md @@ -0,0 +1,111 @@ +# Data Display Design: Fields, Tables, and Charts + +Guidance on presenting numbers and records so a reader understands them quickly. Like +`design-principles.md`, this covers _appropriateness_, not validity. For field schemas, see the +`section`, `table`, `data_table`, and `data_visualization` block pages. Apply these principles +unless the developer explicitly asks otherwise. + +## Pick the format that fits the data + +| The data is… | Use | Surfaces | +|---|---|---| +| one number that matters | a sentence that states it ("Error rate is 2.1%, up from 0.4%") | all | +| progress toward a goal, or fewer than 4 data points | a sentence ("412 of 500 seats filled (82%)") or `section` `fields` | all | +| a few key/value facts about one thing | a `section` with `fields` (up to 10) | all | +| a short set of rows with the same columns | a `table` (up to 100 rows) | messages, App Home | +| many rows, or rows the reader sorts, pages through, or acts on | a `data_table` (up to 200 rows, paginated, sortable, `action_cell` buttons) | messages, App Home | +| a trend over time | a `data_visualization` `line` (or `area` for totals that stack) | messages, App Home | +| a comparison across categories | a `data_visualization` `bar` | messages, App Home | +| shares of a whole | a `data_visualization` `pie`, with no more than about 5 slices | messages, App Home | + +- **Start from the question the reader has.** "Did the deploy work?" needs a sentence, not a + chart. "Which service is slowest this week?" needs a sorted table or a bar chart. +- **Don't show the same data twice** in a table and a chart unless they answer different + questions. Pick one, and link to the full data for anything more. +- **In a modal**, where `table`, `data_table`, and charts aren't available, use `section` `fields` + for key/value data and summarize rows into a few lines. Link out for the full set. + +## Fields + +- **Keep labels short and bold, and values short**: `*Status*\nIn review`. Fields lay out in two + columns, so long values wrap and break the grid. +- **Put the most important pair first.** Readers scan fields top-left to bottom-right. +- **Use an even number of fields** where you can, so the last row isn't half empty. + +## Tables + +- **Lead with the column that identifies the row** (name, ID, title), and set a `data_table`'s + `row_header_column_index` to it so screen readers announce each row by name. +- **Give every `data_table` a `caption`** (required) that says what the table shows: "Open + incidents, sorted by severity". +- **Keep it narrow.** About five columns fit comfortably, especially on mobile. Drop columns the + reader doesn't need to decide anything. +- **Sort rows by what matters**: the worst first, the newest first, the biggest first. Say how it's + sorted in the caption or the lead sentence. +- **Use `raw_number` cells for numbers** so a `data_table` sorts them numerically. Put units in + the header ("Latency (ms)") rather than in every cell. +- **Choose a page size for a `data_table`** that fits the message: the default of 5 rows suits a + digest, and 10–20 suits a report the reader came to look at. +- **Use an `action_cell` for one action per row** ("Open", "Mark Done"), with the row's ID in the + button's `value` and a `fallback` cell for clients that can't show buttons. Buttons in a copy of + the message shared elsewhere are disabled, so don't rely on them as the only way to act. +- **Only one `table` fits in a message, and cell text is capped across the message** (10,000 + characters for `table`, 20,000 for `data_table`). For more, summarize and link out. + +## Charts + +- **Write a title that says what the chart shows.** Keep it to 50 characters or fewer: "Deploys + per day, last 2 weeks". +- **State the takeaway in text.** Put the main point, with its number, in the chart's description + and in the message text: "Deploys doubled after the pipeline change." Notifications, previews, + and screen readers get only the text, and on mobile the reader can't open the expanded view. +- **Name the items that matter.** A chart can't highlight a bar or point, and it drops value labels + when space is tight. Write "3 accounts need attention: Harmony Labs, Acme, Northwind" rather than + leaving the reader to find them. +- **Label both axes, including units.** Use `x_label` and `y_label`: "Latency (ms)". +- **Use one series for one comparison.** A bar chart of 8 services is one series in one color. + Giving each bar its own series adds colors that suggest a difference that isn't there. +- **Keep series to a few.** One to three lines or bar groups are easy to read. Past 6, colors + repeat in a second shade that's hard to tell apart, especially with color vision deficiency. + Series names appear in the legend, so keep them short and distinct. +- **Use color only to tell series apart.** Slack assigns colors automatically, in series order, and + they change in dark mode. Avoid ordering series so a color seems to mean good or bad, and avoid + referring to "the orange line". Say what's good or bad in text, and refer to each series by name. +- **Choose the chart type that fits the data.** + - **Bar** compares values across categories. Keep to about 6 categories with one-word labels + ("Q1", "Legal", "API"), because the card is often narrow. For more categories or longer + labels, use a sorted table. + - **Line** shows a trend over time. Keep to 3 lines with at least 4 points each. + - **Area** shows a total over time and what it's made of. Areas always stack, so use one only + when the series add up to a meaningful total; otherwise, use a line chart. Keep to 3 series. + - **Pie** shows parts of one whole. Keep to 5 segments, largest first, and group the rest into + "Other". For more, use a sorted bar chart. +- **Order categories meaningfully.** Put time left to right. For bars, put the largest first unless + the categories have a natural order. Slack keeps the order you provide. +- **Fit the data to the block.** A series holds at most 20 points, so aggregate a long range + (weekly instead of daily) rather than trimming it. Every series needs a value for every + category, so don't fill a gap with zero. Drop that category from every series and say what's + missing in text. +- **Skip the chart when there's no data.** Say so in a sentence instead: "No deploys this week." +- **Include no more than two charts in a message.** For a dashboard, use the App Home or link to + your product. + +## Numbers and dates in text + +- **Round to what matters**: "2.1%", not "2.0847%". Abbreviate only from 10,000 up, with a capital + K or M ("21K messages"); below that, write the full number ("1,187"). +- **Show change with direction and a baseline**: "up 3 points from last week", not a bare arrow + or a color. +- **Use a `date` element in `rich_text`, or mrkdwn's `` syntax, for timestamps**, so each + reader sees them in their own timezone and format, with relative wording ("today", "3 hours + ago") where it helps. Always include fallback text. +- **Write dates without ordinals**: "Aug 2, 2026", not "Aug 2nd". + +## Quick self-review + +1. Does the format answer the reader's question, and is it supported on this surface? +2. Is the key number or takeaway stated in text, not only in the table or chart? +3. Does every table have the identifying column first, a clear sort, and units in the header? +4. Does every chart have a title, axis labels, and few enough series and categories to read, + with color used only to tell series apart? +5. Are timestamps localized, and are numbers rounded to what matters? diff --git a/.claude/skills/block-kit/references/design-principles.md b/.claude/skills/block-kit/references/design-principles.md new file mode 100644 index 0000000..4236977 --- /dev/null +++ b/.claude/skills/block-kit/references/design-principles.md @@ -0,0 +1,195 @@ +# Block Kit Design Principles + +Guidance on building layouts that read well, not on whether they parse. Validity — required +fields and allowed element nesting — is what `blocks.validate` checks. These principles are about +_appropriateness_: reaching for the block that fits the shape of the content, and arranging it so +a reader takes it in at a glance. Apply them unless the developer explicitly asks otherwise. + +**`blocks.validate` does not enforce which surface a block or how many of it are allowed.** It +checks block and element shape only. It will return `ok: true` for a `table` or `carousel` inside +a modal, an `alert` inside a message, two `table` blocks in one message, or an `input` block in a +modal with no `submit` — all invalid per the surface and limits table below. Treat that table, +not a passing validation, as the source of truth for surface and count limits. + +These principles apply to every surface. Companion references go deeper on specific kinds of +layout: `modal-design.md` (modals and forms), `home-tab-design.md` (App Home), +`data-display-design.md` (fields, tables, and charts), `agent-progress-design.md` (plans and +task cards), and `human-in-the-loop.md` (approvals and choices). + +## Reach for the block that fits the shape of the content + +Don't stack `section` + `divider` text when a purpose-built block fits better, and don't add +structure to content that doesn't need it. Match the block to what the content _is_: + +- **Tabular or comparable rows** (metrics, line items, a leaderboard) belong in a `table`. + Stacked sections force the reader to scan prose; a table aligns columns so values compare at a + glance. When the reader needs to page, sort, or act on rows (more than a screenful, or a button + per row), use a `data_table` instead. +- **A trend, comparison, or share of a whole** (deploys per day, spend by team) belongs in a + `data_visualization` chart, always with the key number stated in text as well. + `data-display-design.md` covers choosing between fields, tables, and charts. +- **One rich entity the message is about** (an alert, an incident, a record, a PR) belongs in a + `card`. A card groups the entity's title, body, and actions into one bounded unit instead of + loose blocks. +- **A browsable set of peer items the reader chooses among** (a catalog, options, search results) + belongs in a `carousel` of cards — horizontal browsing instead of an ever-growing vertical + stack. +- **A status update or an approval** (one subject plus a decision) is well served by a `header` + for the title, a `section` with `fields` for the key/value details, and an `actions` block for + the buttons. +- **Multi-step work an agent is doing** (a plan, a checklist of tool calls) belongs in a `plan` + of `task_card`s, each with a `status` — not a growing wall of "Step 3 done ✅" text. +- **A group of related blocks that belong together** (a record's details, an optional + breakdown) can go in a `container`, with a title and, for secondary detail, `is_collapsible` + so it starts collapsed. It holds up to 10 child blocks, but not `card`, `carousel`, or + `data_table`. +- **A notice about the whole view in a modal** (a validation problem, a success state, a warning + before submitting) belongs in an `alert` block. `alert` is available only in modals, so in a + message state the level in words ("Deploy failed", "Warning:") in a `header` or `section`. +- **A status, a date, or a source inside text** belongs in a `rich_text` inline element: a `tag` + for a status pill ("In progress"), a `date` for a timestamp that shows in each reader's own + timezone and format, and a `citation` for an AI answer's source. +- **A one-line notice with no structure** should stay plain text. Don't add blocks for their own + sake; wrapping a one-line status in a `card` or a table works against the content, not for it. + +Avoid `divider` between every block. Use it only to separate genuinely distinct groups; a +`header` or the edge of a `card` usually does the job better. + +### Know where each block works and how much it holds + +A block that fits the content can still be the wrong choice for the surface, and each block has +limits: + +| Block | Surfaces | Holds at most | +|---|---|---| +| `table` | messages, App Home | 100 rows × 20 cells; 10,000 chars across cells per message | +| `data_table` | messages, App Home | 200 rows + header × 20 columns; 20,000 chars across cells per message | +| `data_visualization` | messages, App Home | 2 per message; 12 series or slices; 20 points per series | +| `carousel` | messages, App Home | 1–10 cards | +| `card` | messages, modals, App Home | 3 actions; title 150 chars, body 200 chars | +| `container` | messages, App Home | 10 child blocks; title 150 chars | +| `alert` | modals only | 200 chars | +| `markdown` | messages only | 12,000 chars across all markdown blocks in the payload | +| `plan` / `context_actions` | messages only | 50 task cards / 5 elements | +| `section` `fields` | all | 10 fields, 2,000 chars each | +| _(whole surface)_ | — | 50 blocks per message; 100 per modal or App Home | + +In a modal, where `table` and `carousel` aren't available, use a `section` with `fields` for key/value +data. For content that would go over these limits, summarize and link out first. For a large +table, a paginated `data_table` comes next. Split content across messages only as a last resort: +a reader can't sort, search, or act on it as one set, and every extra message is another +notification. + +## Emphasis and actions + +- **Emphasize at most one button per message or view**, not per `actions` block. If the layout + has one clear main action, make it `primary` (Approve, Save, Send). Use `danger` only when the + _main_ action is destructive (Delete, Remove). In an Approve/Reject pair, `primary` goes on + Approve and Reject stays unstyled. When the buttons are equal choices (clarifying options, row + actions, filters), leave them all unstyled. If everything is emphasized, nothing is. +- **In a modal, Submit is already the main action.** Don't add a `primary` button inside the + view's blocks to compete with it. +- **Label buttons with specific verbs** ("Approve Request", "Open Incident"), never "Click Here". + The label, not the red or green style, must say what the button does. +- **Keep the visible action set small.** Put two or three actions inline and move advanced or + rare ones into an `overflow` menu. +- **Guard destructive actions with a confirmation dialog** (`confirm`) so an accidental click + can't do irreversible harm. + +## Words and labels + +Match the conventions of Slack's own UI, so an app reads like part of Slack: + +- **Use Title Case for action button labels** ("Approve Request", "View Logs"). **Use sentence + case for everything else**: `header` text, modal titles, input labels, menu and `overflow` + options, links, and `context` text. +- **No end punctuation in headings**: "Deploy failed on prod-3", not "Deploy failed on prod-3." +- **Save commits changes; Done only closes.** Don't label a button that saves "Done", or one that + only closes "Save". + +## Layout and reading order + +- **Order blocks top-to-bottom in reading order:** lead with a `header` for the title, then the + content `section`s, then any `actions`, then a trailing `context` block for footnotes. Don't + bury the title in the middle of the layout. +- **Put the point first.** The first line should say what happened or what's needed ("Deploy + failed on prod-3", "Your approval is needed"). Background comes after that. +- **Put secondary or metadata text in a `context` block, not a `section`**: attribution, + timestamps, status, help links. Separate multiple fragments with " · " (for example, + "Posted by <@U123> · 2 min ago"). + +## Messages that change over time + +- **Update the message in place** (`chat.update`, or `replace_original` via `response_url`) for + progress and state changes. Don't post a new message for each step. +- **When a flow is finished, remove its controls.** Replace the `actions` block with a + `context` line recording the outcome ("Approved by <@U123> · 10:42"), so stale buttons can't be + clicked again. +- **Keep `action_id`s stable** across updates so handlers keep matching. Give an updated message + a **new `block_id`**, so interactions from an older copy can be told apart. + +## Text: rich_text, mrkdwn, and the markdown block + +- **Formatted text you build in code** (lists, quotes, code blocks, mentions, links) belongs in + a `rich_text` block. It is the composer's native format and Slack's preferred one. +- **Short text inside a `section` or `context`** uses Slack `mrkdwn`: `*bold*`, `_italic_`, + `~strike~`, `` `code` ``. This is Slack's syntax, not `**bold**`. +- **Long-form or AI/LLM-generated content that already exists in standard markdown** (headings, + tables, numbered lists, `**bold**`) belongs in a `markdown` block (messages only). Its + `block_id` is not preserved and images render as links. Use it for body content, not for + anything you'll need to find again or update. Don't translate LLM markdown into mrkdwn by hand. + +## AI and agent output + +- **Show work in progress as structure:** use a `plan` / `task_card` for steps, and switch each + card's `status` to `complete` or `error` as the work happens. When streaming, send steps as + `task_update` chunks instead. `agent-progress-design.md` covers when to use a plan, how to word + steps, and how to handle failures. +- **When streaming, send the rest of the layout in the final call** (`chat.stopStream`), so + partly built blocks don't render mid-stream. +- **Collect feedback with `feedback_buttons`** inside a `context_actions` block at the end of the + response, instead of hand-rolled thumbs-up and thumbs-down buttons. +- **Cite sources where the claim is made.** In `rich_text`, use a `citation` element for each + source. In mrkdwn, use inline links, with a `context` block listing references at the end. +- **Ask before acting.** Put an explicit `confirm` or Approve/Cancel choice on + anything that creates, sends, or deletes on the user's behalf. `human-in-the-loop.md` covers + approval gates, approving several actions in one message, and closing the loop afterwards. + +## Accessibility and fallback + +Accessibility is easy to skip and hard to retrofit, so build it in from the start: + +- **Summarize the layout in a message's top-level `text` fallback.** Notifications and screen + readers show it instead of the blocks. State the point and any action needed ("Deploy failed + on prod-3 — approval needed to roll back"), not a generic "New message". An empty fallback + leaves those readers with nothing, and `blocks.validate` won't warn you. +- **Give images descriptive `alt_text`** (what the image shows, not just "image"). Make sure + image-heavy layouts also carry the key information as text. If an image is purely decorative, + drop it. +- **Never use color as the only signal.** A red `danger` button, an emoji, or an `alert` level + needs words that say the same thing. +- **Use emoji alongside text, never instead of it, and only in running text.** Keep them out of + buttons, menu options, labels, and headers, and don't use them as bullets. Keep them few. +- **Set `accessibility_label` on buttons** whose visible text is ambiguous out of context + ("View", "Open"). +- **Use `header` blocks for logical section headings.** They convey document structure to + assistive tech. They take `plain_text` only, up to 150 chars. +- **Give tables and charts a text equivalent.** A `data_table` needs a `caption`, and + `row_header_column_index` should point at the column that names each row. A chart needs its + main takeaway in text next to it ("Deploys doubled week over week"). +- **Avoid directional references** such as "see above" or "the button on the right". Layouts + reflow on mobile and are read linearly by screen readers. + +## Quick self-review + +Before handing back a layout, check: + +1. Does each block match the shape of its content, and is it supported on this surface? +2. Does the first line (and the `text` fallback) say the point? +3. Is at most one button `primary` in the whole message or view, and are destructive actions + confirmed? +4. Is metadata in `context`, and is the reading order header → content → actions → context? +5. Will this message be updated? If so, how does it look when the flow finishes? +6. Can someone who can't see colors, emoji, or images still understand it? +7. Are buttons in Title Case and everything else in sentence case, with no end punctuation in + headings and no emoji in buttons, labels, or headers? diff --git a/.claude/skills/block-kit/references/home-tab-design.md b/.claude/skills/block-kit/references/home-tab-design.md new file mode 100644 index 0000000..160126e --- /dev/null +++ b/.claude/skills/block-kit/references/home-tab-design.md @@ -0,0 +1,88 @@ +# App Home Design + +Guidance on Home tabs that people return to. Like `design-principles.md`, this covers +_appropriateness_, not validity. For the view object and publishing, see +`https://docs.slack.dev/surfaces/app-home.md`. Apply these principles unless the developer +explicitly asks otherwise. + +A Home tab is one view of up to 100 blocks, published per user with `views.publish`. Unlike a +message, it's persistent and personal: each user sees their own version, and it should be up to +date whenever they open it. + +## Put the most important thing at the top + +- **Lead with what this user needs now**: items waiting on them, today's status, or the one + action they come here for. Slack's guidance is that the most important content and the entry + points to your app's core features belong at the top. +- **Then the rest, in sections**, each with a `header`: recent activity, settings, help. + Separate genuinely different sections with a `divider`, not every block. +- **Don't open with a welcome banner** after the first visit. Returning users came for the + content, not the introduction. + +## Keep actions few + +- **Limit the visible calls to action.** Put the main one or two actions in an `actions` block + near the top, give each row its own button for its action ("Open", "Read"), and move rare + actions into an `overflow` menu. +- **Put settings behind a button** that opens a modal (see `modal-design.md`), rather than laying + out every setting on the Home tab. Show admin-only settings only to admins. +- **Open details in a modal** rather than expanding the Home tab. A "Read" or "Open" button that + opens a modal keeps the Home tab short. + +## Empty and first-run states + +- **Teach by example in empty states.** Instead of "No routines", say what it would look like and + how to start: `_None yet. Ask me for one: "every weekday at 8am, tell me what needs me today."_` +- **Onboard on the first visit.** Use the `app_home_opened` event to detect a new user and show a + short setup: what the app does, the one thing to try first, a button to start, and a way to + dismiss it. Replace it with the normal Home tab once they've done it. +- **Welcome back long-absent users** with what changed or what's waiting, not the full + onboarding again. + +## Keep it current + +- **Publish on `app_home_opened`** so the view is fresh when the user looks, and publish again + when the user's data changes (an item resolved, a setting saved). +- **Show freshness where it matters**: "Updated 2 min ago" in a `context` block at the top, using + a `date` element or `` so it's localized. +- **Make status rows self-explanatory**: name, state, and the last outcome. For example, + `*Daily digest* · paused` and `_Last run Tue 8:00 AM: nothing to report_`. +- **Don't show stale controls.** After an action completes, publish a view that reflects it, + rather than leaving a button that does nothing. + +## Different people, different Home tabs + +The Home tab is published per user, so it can, and often should, differ by role. + +- **Show each user only what they're allowed to see.** Decide on the server what each role + (owner, admin, member, guest) gets, and build the view from that. Hiding a button isn't access + control; the action handler must check permissions too. +- **Let owners and admins preview other roles' views**: a "View as Member" button that publishes + the reduced view to them, with a `context` line saying they're previewing and a button back. + +## A review surface for agents + +When an app or agent acts on a user's behalf, the Home tab is where the user checks what it did. + +- **List recent actions and conversations**, newest first, each with who, where, when, and a + short excerpt, and a button to read the full record in a modal. +- **Show pending items** (approvals waiting, failed runs) above the history, with a direct action + for each. +- **Give users a place to manage trust**: revoke an "Always Allow", reconnect an app, or pause a + routine. + +## Long content + +- **Split long text across `section` blocks** under the 3,000-character limit per text field. In a + modal, also stay under the 100-block view limit, and add a `context` line such as "File + continues beyond what this view can show" with a link to the full content. +- **Link out rather than paging inside the Home tab.** A short, current summary plus a link beats + a long view the user has to scroll through. + +## Quick self-review + +1. Is the most important content for this user at the top, with at most one or two main actions? +2. What does a brand-new user see, and what does the view show when a section is empty? +3. Is the view published on open and whenever the data changes, with no stale controls? +4. Does each role see only what it should, with permissions checked in the handlers? +5. If the app acts on users' behalf, can they review and manage what it did here? diff --git a/.claude/skills/block-kit/references/human-in-the-loop.md b/.claude/skills/block-kit/references/human-in-the-loop.md new file mode 100644 index 0000000..8d256c2 --- /dev/null +++ b/.claude/skills/block-kit/references/human-in-the-loop.md @@ -0,0 +1,223 @@ +# Human-in-the-Loop Design: Approvals, Choices, and Review + +Guidance on Block Kit layouts where a person has to decide before an app or agent continues: +approval gates, sets of proposed actions to approve together, clarifying choices, and +edit-before-send. As in `design-principles.md`, this covers _appropriateness_, not validity. For +the underlying guidance, see Slack's agent design guide +(`https://docs.slack.dev/concepts/agent-design.md`, "Confirmation and control") and governance +guide (`https://docs.slack.dev/ai/agent-governance.md`). Apply these principles unless the +developer explicitly asks otherwise. + +## Decide when to ask + +- **Ask before anything that creates, sends, deletes, or spends**, and before acting as the user + in a way other people will see. Reads and drafts don't need a gate. +- **Ask when the request is ambiguous** and more than one reasonable path exists. Offer the paths + as choices; don't guess. +- **Don't ask about everything.** Confirming every step teaches users to click through without + reading. Save gates for actions that matter, and let users stop being asked about a class of + action once they trust it (see **Earn trust over time** below). +- **Match the gate to the stakes.** A reversible, low-impact action can go ahead and offer Undo + afterwards. An irreversible or high-impact one needs approval first, and possibly a `confirm` + dialog on top. +- **Write the policy down as lists, not case-by-case judgment.** An agent's gate is easiest to + trust when it's predictable: + - **Always ask** for destructive actions (delete, cancel, archive, revoke, forget) and for + outbound actions that reach other people (send, post, share, invite, forward). + - **Never ask** for cheap, reversible, or self-scoped actions (add a reaction, pin a message, + save a note to the user's own memory, create a draft). + - **For tools you don't know in advance**, such as tools from a connected MCP server, check the + tool name for the same verbs (`gmail_send_email`, `calendar_event_delete`), and ask when one + appears. + +## Pick the pattern + +| The decision is… | Use | +|---|---| +| go / don't go on one action | **Approval gate**: a preview, then Approve / Edit / Cancel | +| several proposed actions at once | **Approval set**: one message that lists every item, with a way to choose which to approve | +| which of a few paths to take | **Clarifying choice**: one button per option, each with a line of context | +| the content itself, before it's sent | **Edit before send**: a modal pre-filled with the draft | +| a sign-off from someone else | **Request to an approver**: a message to the approver, with the outcome sent back to the requester | + +### Approval gate + +- **Preview exactly what will happen**, so approval is an informed choice: the message that will be + posted, the issue that will be filed, the recipients. Use a `section` with `fields` for + key/value details, a `card` for a single entity, or a `rich_text` quote for draft text. +- **State the action and its scope in the first line**: "Send this summary to #eng (212 members)?". Not "Ready to proceed?" or "Confirm this action". +- **Describe the target by name, not by ID**: "Delete the canvas Q3 planning", not "Delete + `F0123ABC`". Let each tool supply its own preview text when it knows the human-readable names, + and fall back to a generic description built from the arguments only when it doesn't. +- **Use specific verbs on the buttons**: "Send Summary", "Edit", "Cancel". Mark only the + approving button `primary`. If the main action is destructive, mark it `danger` and add a + `confirm` dialog. Leave Reject or Cancel unstyled: declining is the safe choice, and a red + button suggests it's the dangerous one. +- **Offer a way to change it, not just yes or no.** An Edit button that opens a pre-filled modal + (see **Edit before send**) prevents a reject-and-retry loop. + +### Approval set + +When an agent proposes several actions ("Create these 5 issues", "Send these 3 replies"), put them +in one message rather than one message per item. Slack's guidance is to batch related +notifications. + +- **List every item with enough detail to judge it**, one item per line: a `section` per item + with the key details in `fields` for a handful of items, or a `table` for many items with the + same columns. +- **Let the user choose which items to approve.** Two layouts work well: + - **Select, then approve once** (best for 2–10 items): a `checkboxes` element with one option per + item, every item checked by default (`initial_options`), followed by an `actions` block with + "Approve Selected" (`primary`) and "Cancel". Each checkbox change sends its own `block_actions` + payload, which the handler can just acknowledge. Read the final selection from `state.values` + in the button's payload. + - **Decide per item**: a `section` per item with an `overflow` accessory (Approve, Skip, Edit), + or a `data_table` with an `action_cell` button per row, plus "Approve All Remaining" at the + end. Update the item's line in place as each decision comes in. +- **Show the totals in the button and the fallback**: "Approve 4 of 5", and `text` "5 issues + ready to create, approval needed". +- **After the decision, replace the controls with a record** of what was approved and what was + skipped (see **Close the loop** below), so the message records exactly what was approved. + +A minimal "select, then approve once" layout: + +```json +{ + "text": "3 Linear issues ready to create, approval needed", + "blocks": [ + { + "type": "section", + "text": { "type": "mrkdwn", "text": "*I found 3 action items in this thread.* Choose which to create as Linear issues in *Platform*:" } + }, + { + "type": "actions", + "block_id": "issue_selection", + "elements": [ + { + "type": "checkboxes", + "action_id": "selected_issues", + "options": [ + { "text": { "type": "mrkdwn", "text": "*Fix flaky deploy health check*" }, "description": { "type": "plain_text", "text": "Assignee: Priya · Priority: High" }, "value": "item_1" }, + { "text": { "type": "mrkdwn", "text": "*Add retry to webhook sender*" }, "description": { "type": "plain_text", "text": "Assignee: Sam · Priority: Medium" }, "value": "item_2" }, + { "text": { "type": "mrkdwn", "text": "*Update the runbook link*" }, "description": { "type": "plain_text", "text": "Unassigned · Priority: Low" }, "value": "item_3" } + ], + "initial_options": [ + { "text": { "type": "mrkdwn", "text": "*Fix flaky deploy health check*" }, "description": { "type": "plain_text", "text": "Assignee: Priya · Priority: High" }, "value": "item_1" }, + { "text": { "type": "mrkdwn", "text": "*Add retry to webhook sender*" }, "description": { "type": "plain_text", "text": "Assignee: Sam · Priority: Medium" }, "value": "item_2" }, + { "text": { "type": "mrkdwn", "text": "*Update the runbook link*" }, "description": { "type": "plain_text", "text": "Unassigned · Priority: Low" }, "value": "item_3" } + ] + } + ] + }, + { + "type": "actions", + "block_id": "issue_decision", + "elements": [ + { "type": "button", "action_id": "create_selected_issues", "text": { "type": "plain_text", "text": "Create Selected Issues" }, "style": "primary", "value": "batch_42" }, + { "type": "button", "action_id": "cancel_issue_batch", "text": { "type": "plain_text", "text": "Cancel" }, "value": "batch_42" } + ] + }, + { + "type": "context", + "elements": [ { "type": "mrkdwn", "text": "Issues will be created as you, <@U0123456789>" } ] + } + ] +} +``` + +### Clarifying choice + +- **Offer two to four concrete options as buttons**, each labeled with what the agent will do: + "Summarize Last Week", "Summarize Since Incident". Add a line of context for each in the + `section` above (or use a `radio_buttons` element when the options need descriptions). +- **Include a way out**: "Something Else" opens a short modal or invites a reply in the thread. +- **Don't emphasize any option** unless one is clearly the recommended default. + +### Edit before send + +- **Open a modal pre-filled with the draft** (`initial_value` on a `plain_text_input` or + `rich_text_input`) from the Edit button. Name the submit label after the action ("Send Summary"), so editing and approving happen in one step. +- **Show the edited version in the message once it's sent**, so the record reflects what went out + and not the original draft. + +### Request to an approver + +When the person who approves isn't the person who asked (expense sign-off, access requests, +deploy gates): + +- **Send the request where the approver will act on it**: a DM to a named approver, or a post in an + approvals channel for a group. Give the requester a separate message showing that the request is + pending. +- **Name the requester and the reason up front**: "<@U123> requests prod database access for + INC-482". Put supporting details in `fields`. +- **Record each approval in place** for N-of-M sign-offs: a `context` line such as "Approved by + <@U234> · 1 of 2 needed", updated as each approver responds. +- **Send the outcome back to the requester**, whichever way the decision went, and include the + approver's reason when rejecting. + +## Close the loop + +- **Replace the controls once a decision is made.** Update the message (`chat.update`, or + `replace_original` via `response_url`) so the `actions` block becomes a `context` line: "Created + 2 of 3 issues · Approved by <@U123> · 10:42". Buttons that stay up after the decision invite + duplicate clicks. For a declined action, keep the preview but strike it through, followed by the + outcome: `~Delete the canvas Q3 planning~ Rejected, I won't run it.` +- **Give every request a way to end without an answer.** An agent waiting on approval holds up the + whole run. Every pending approval should settle exactly once, in one of these ways: + + | Ending | What happens | Message becomes | + |---|---|---| + | approved | the action runs | "Approved, running it now", then the result | + | rejected | the action is skipped | "Rejected, I won't run it." | + | timed out (minutes for an agent's in-run gate, longer for a human sign-off) | the action is skipped | "Timed out, I didn't run it." | + | run stopped | the action is skipped | "Cancelled, the request was stopped." | + +- **Show the result, not just the decision.** Link to what was created or sent. If an item failed + after approval, say which one and why. +- **Tell everyone else who saw the request.** In a channel, update the original message rather + than replying with a new one, so nobody approves something that was already handled. +- **Expire stale requests.** If the decision no longer matters (the deploy window passed, the + draft was replaced), update the message to say so and remove the buttons. A `response_url` only + works for 30 minutes (up to 5 uses), so use `chat.update` for decisions that may take longer. + +## Make approvals safe + +These are handler responsibilities, but the layout has to support them: + +- **When in doubt, don't run it.** If the approval prompt fails to post, the request times out, or + the run is cancelled, treat it as a rejection. An unanswered gate must never become a yes. +- **Check who clicked.** Anyone who can see a message can click its buttons. Check that the + `user.id` in the interaction payload is allowed to approve, and if not, respond with an + ephemeral message ("Only <@U234> can approve this request") without changing the original. +- **Make the decision idempotent.** Two approvers, or one double-click, can send two payloads. + Put a unique request ID in the button's `value` (or `private_metadata` in a modal), settle that + ID once, and ignore later clicks, including ones that arrive after a timeout. +- **Approve exactly what was shown.** If the proposal changes, post or update it with a new + `block_id`, so a click on the old version can be recognized and rejected. +- **Show whose identity the action uses**: "Will be sent as you" or "Posted by the app on behalf + of <@U123>", in a `context` block next to the actions. +- **Use ephemeral messages for personal approvals in a shared channel**, so other members don't + see or click them. Use `response_type: "ephemeral"` via `response_url`, or `chat.postEphemeral`. + +## Earn trust over time + +- **Offer Undo after reversible actions** that ran without a gate: a "Created LIN-204 · Undo" + `context` line, or a button that expires after a short window. +- **Offer "Always Allow" for a class of action** once the user has approved it a few times, as a + secondary button next to the main approval ("Approve" and "Always Allow in #eng"). Honor it, and + give users a place to revoke it, such as the App Home. +- **Let users review what the agent did on their behalf**, especially for asynchronous or bulk + work. An App Home log of recent actions works well for this. + +## Quick self-review + +1. Does this action need a gate, and does the gate match the stakes? +2. Does the preview show exactly what will happen, with the action and scope in the first line? +3. Are the buttons specific verbs, with one `primary`, and is there a way to edit rather than only + reject? +4. For several items, is it one message where the user can approve some and not others? +5. After the decision, are the controls replaced by a record of what happened? +6. Does every request end, by timeout or cancellation if not by a click, and does that ending + default to not running the action? +7. Does the handler check who clicked, ignore duplicate clicks, and reject clicks on outdated + versions? diff --git a/.claude/skills/block-kit/references/modal-design.md b/.claude/skills/block-kit/references/modal-design.md new file mode 100644 index 0000000..ac8df87 --- /dev/null +++ b/.claude/skills/block-kit/references/modal-design.md @@ -0,0 +1,150 @@ +# Modal and Form Design + +Guidance on modals and forms that are quick to fill in and hard to get wrong. Like +`design-principles.md`, this covers _appropriateness_, not validity: `blocks.validate` tells you +whether a view parses, and this tells you whether it works for the person filling it in. For the +view object's fields and the full modal lifecycle, see `https://docs.slack.dev/surfaces/modals.md` +and `https://docs.slack.dev/reference/views/modal-views.md`. Apply these principles unless the +developer explicitly asks otherwise. + +## Decide whether it should be a modal at all + +A modal interrupts the user. Use one only for short, focused work that the user started: + +- **Use a modal** to collect structured input (a form), to confirm a consequential action with + more context than a `confirm` dialog can hold, or to show details on demand. +- **Use a message** for a decision one or two buttons can capture (Approve / Reject). A modal + adds a click and hides the decision from everyone else in the channel. +- **Use the App Home** for persistent settings or a dashboard the user returns to. Modals are + short-lived and their state is lost when they close. +- **Never open a modal the user didn't ask for.** A modal needs a `trigger_id` from the user's + own interaction, and that trigger expires after 3 seconds. Open the modal right away, and show a + loading view if the data isn't ready yet (see **Loading, success, and failure** below). +- **Never ask for passwords or other credentials.** Send the user to your own sign-in flow. + +## Frame the modal + +- **Title says what the form is**, in 24 characters or fewer: "New incident", "Request time off". + Leave out the app name; Slack already shows it. +- **Submit label is the outcome, as a verb**: "Create Incident", "Send Request", "Save". Never + "Submit" or "OK" when a specific verb fits. It is limited to 24 characters, and `submit` is + required whenever the view contains an `input` block. +- **Close label is "Cancel"** unless closing does something other than discard the form. Use + "Done" for a modal that only shows information, and "Save" (never "Done") for one that commits + changes. +- **Let Submit be the only emphasized button.** Slack renders it as the modal's main action, so + leave buttons inside the view's blocks unstyled (or `danger` for a destructive one). +- **Say what submitting will do** when it isn't obvious from the label, especially if it sends + something on the user's behalf: "This sends a message to #incidents and pages the on-call + engineer." Put it in a + `context` block just above the inputs, or in the modal's first `section`. +- **Lead with a short `section`** only when the user needs instructions. A form whose labels are + clear doesn't need a paragraph introducing it. + +## Inputs + +Each `input` block holds one field: a label, an element, and optionally a hint. + +- **Every input gets a label that names the value**, in sentence case: "Due date", "Affected + service". Not a question, and not "Please enter…". +- **Use `hint` for constraints and format** ("Use the service's PagerDuty name"). It stays visible + below the field. Use `placeholder` only for an example value ("Ex. api-gateway"). Placeholders + disappear as soon as the user starts typing, so they must never carry instructions the user + needs. +- **Mark optional fields as `optional: true`** rather than putting "(optional)" in the label. + Inputs are required by default, so think about each field: if your handler can work without it, + make it optional. +- **Pre-fill what you already know** with `initial_value`, `initial_option(s)`, `initial_date`, + `initial_user`, or `initial_conversation`. Reviewing a pre-filled value is faster than typing + it. For a conversation picker opened from a channel, set `default_to_current_conversation`. +- **Put `focus_on_load` on the first field** the user should fill in (at most one per view). +- **Pick the element that constrains the answer** so you don't have to validate free text: + + | The answer is… | Use | + |---|---| + | one of 2–5 visible choices | `radio_buttons` | + | one of many | `static_select` (up to 100 options), or `external_select` for a large or live list | + | several from a list | `checkboxes` (up to 10 options) or `multi_static_select` | + | a person, channel, or conversation | `users_select`, `conversations_select` (and multi variants) | + | a date, time, or both | `datepicker`, `timepicker`, `datetimepicker` | + | a number, email, or URL | `number_input`, `email_input`, `url_input` | + | short or long free text | `plain_text_input` (`multiline: true` for long text, `max_length` to cap it) | + | formatted text | `rich_text_input` | + | a file | `file_input` | + +- **Order fields the way the user thinks about the task**: the most important or identifying + field first ("Title"), details after, optional fields last. + +## Keep it short + +- **Ask only for what you need now.** Every field costs the user time. Slack's guidance is to + split the form once it reaches about six inputs. +- **Split a long form into steps** with `response_action: "push"` (or `views.push` from a button + inside the modal). A modal holds at most 3 views in its stack, so plan for no more than three + steps. Carry earlier answers forward in `private_metadata` (up to 3,000 characters), not in + hidden fields. +- **Use `views.update` to show or hide dependent fields** in place. Set `dispatch_action: true` + on the controlling input so changing it sends a `block_actions` payload, then update the view. + Keep the same `block_id` and `action_id` on every input so the user's entries are kept, and pass + the payload's `hash` so a stale update can't overwrite a newer one. +- **Don't push a view for something that fits in the current one.** Each pushed view is another + screen the user has to get through, and another Cancel that might send them back. + +## Validation and errors + +- **Validate on submit and respond with `response_action: "errors"`**, keyed by the input's + `block_id`: `{ "response_action": "errors", "errors": { "due_date": "Pick a date in the future" } }`. + The error appears under that field and the modal stays open with everything the user entered. + You have 3 seconds to respond. +- **Write errors that say how to fix the problem**: "Pick a date in the future", not "Invalid + date". Don't just repeat the label. +- **Don't blame the user or apologize.** "This email address doesn't look quite right", not "You + entered an invalid email address" or "Sorry, that's invalid". "You don't have permission…" is + fine. +- **Show every field error at once**, not one per submit. +- **Constrain input before you validate it.** A `datepicker`, `number_input` with `min_value`, or + a select prevents errors that a free-text field would need a message for. +- **For a problem with the whole form**, not one field (for example "That incident was already + closed"), update the view with `response_action: "update"` and put an `alert` block at the top + with `level: "error"`. `alert` is available only in modals. + +## Loading, success, and failure + +- **For slow work, open the modal first with a loading view.** Show a short `section` such as + "Loading your projects…", then fill it in with `views.update` when the data arrives. Don't + hold the `trigger_id` while you fetch data: it expires after 3 seconds. +- **For slow submissions**, acknowledge with `response_action: "update"` to a "Creating + incident…" view, do the work, then `views.update` that view to the result. +- **Confirm what happened after submit.** Either close the modal and post the result where the + user will see it (an ephemeral message, a DM, or the thread the flow started in, with a link to + what was created), or update the modal to a success view with an `alert` at `level: "success"` + and a link. Don't close silently. +- **When submission fails on your side**, keep the user's input. Return `errors` or an `update` + with an `alert` that says what went wrong and what to try next. Never close the modal and + throw the form away. +- **Close the whole stack when the flow is done** with `response_action: "clear"`, so the user + doesn't land back on an earlier step of a form they already finished. +- **Handle Cancel gracefully.** Set `notify_on_close: true` if you need to clean up (release a + lock, delete a draft). Don't reopen the modal or nag the user to finish. + +## Destructive and consequential actions + +- **Use a `confirm` dialog** on a button for a single irreversible action. Keep its title to the + action, with no end punctuation ("Delete incident"), its text to the consequence, and its confirm label to the + verb ("Delete"). Set `style: "danger"` on the confirm dialog itself. +- **Use a review view instead** when the user needs to see what will happen before confirming, + such as a bulk change, a message that will be posted, or anything that sends on their behalf. + Push a view that summarizes the result, with the Submit label stating the action ("Send to 42 People"). + +## Quick self-review + +Before handing back a modal, check: + +1. Is a modal the right surface, and does the title say what the form is in 24 characters or + fewer? +2. Does the Submit label name the outcome, and is it clear what submitting will do? +3. Does every input have a clear label, constraints in `hint` (not `placeholder`), and the right + `optional` setting? +4. Are known values pre-filled, and does the element limit the possible answers wherever it can? +5. Is the form six inputs or fewer per view, and three views or fewer in the stack? +6. What does the user see while loading, on a validation error, on success, and on failure? diff --git a/.claude/skills/create-slack-app/SKILL.md b/.claude/skills/create-slack-app/SKILL.md new file mode 100644 index 0000000..7b28854 --- /dev/null +++ b/.claude/skills/create-slack-app/SKILL.md @@ -0,0 +1,274 @@ +--- +name: create-slack-app +description: 'Use when a developer wants to create, scaffold, or bootstrap a new Slack app or agent from scratch with the Slack CLI, or scaffold the project for a new app just created in App Settings (`--app`, `--template`, `--team`). Covers prerequisites, authentication, choosing a workspace to install into, and creating a project from a Bolt (JS or Python) template locally. Trigger on "create a Slack app", "new Bolt app", "start a Slack agent".' +argument-hint: "[bolt-js | bolt-python]" +--- + +# Create Slack App + +Help the developer create a Slack app or agent using Bolt. If `$0` is exactly `bolt-js` or `bolt-python`, treat it as the chosen framework and skip asking. Otherwise (including if it's empty or any other value), ignore it and ask the developer which framework they want before continuing. + +This skill walks through the full setup: prerequisites, authentication, choosing a workspace to install into, project scaffolding from a template, and running the app locally. + +## Existing App from App Settings + +The developer may already have created and installed the app in App Settings, which hands off with arguments in the developer's message, for example `--app A0123456789 --template slack-samples/bolt-js-starter-agent --team T0123456789`. The agent setup prompt passes them along, after turning the App Settings template name into a template repo: + +| Argument | Meaning | Accept only | +|----------|---------|-------------| +| `--app` | The existing app's ID | `A` followed by uppercase letters and digits | +| `--template` | The template repo to create the project from | `org/repo`, each part letters, digits, dots, hyphens, and underscores | +| `--team` | The workspace (or Enterprise org) the app is installed in | `T` or `E` followed by uppercase letters and digits | +| `--subdir` (optional) | The template subdirectory to use | lowercase letters, digits, and hyphens | + +When `--app` is present, follow this skill as an **existing app**. The app ID, template, and team are already decided, so do not ask about them again. The framework is the template's language: `bolt-js` for a `slack-samples/bolt-js-*` repo and `bolt-python` for `slack-samples/bolt-python-*`, so do not ask for it either. Each step below says what changes. Check every value against the table before putting it in a command. If a value doesn't match, or `--app` comes without `--template` and `--team`, tell the developer which value is wrong and ask for it rather than guessing. + +--- + +## Step 1: Check Prerequisites + +### 1a. Detect the Slack CLI command + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public Slack CLI is installed and resolve its command name. Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. The fingerprint check, alias fallback, and install instructions all live there; do not duplicate them here. + +Once resolved, use the detected command name for **all** CLI commands throughout the rest of this skill. We refer to it as `SLACK_CMD` below — substitute the actual resolved command name everywhere you see `SLACK_CMD`. + +### 1b. Verify the CLI version + +Run `SLACK_CMD version` and print the version to confirm everything is working before continuing. + +### 1c. Check language runtime + +- **If `$0` is `bolt-js`**: Run `node --version` to verify Node.js is installed (v18+ required). If not installed, suggest `brew install node` or point to . +- **If `$0` is `bolt-python`**: Run `python3 --version` to verify Python is installed (3.6+ required). If not installed, suggest `brew install python3` or point to . + +--- + +## Step 2: Authenticate with the Slack CLI + +Use the `slack-cli` skill — **Step 5: Authentication (`slack auth`)** — to check the developer's auth status and walk them through `SLACK_CMD login` if they're not already authenticated. + +Wait for confirmation that authentication succeeded before proceeding. + +**Existing app:** the CLI must be logged in to the team from `--team`. Check that `SLACK_CMD auth list` shows that team ID. If it doesn't, log in to that workspace with the same flow. + +--- + +## Step 3: Choose Where to Install the App + +**Existing app:** skip this step. The app is already installed in the team from `--team`. + +The app needs a Slack workspace to install into. Three targets work and they are not equivalent. Use AskUserQuestion to let the developer pick, presenting them in this order: + +| Target | Best for | Cost of entry | +|--------|----------|---------------| +| **Developer sandbox** (recommended) | Anything the developer plans to keep building on. A free Enterprise Grid org isolated from real users, so org-level features are testable. | Needs a Slack Developer Program account, which is free to join. Every account can create a basic sandbox, with no paid plan or payment method. | +| **Free Team** (second choice) | Starting right now, when Developer Program signup is the thing in the way. A free workspace the developer creates and owns. | Capped at 10 apps per workspace, and no Enterprise Grid org features. | +| **Existing production workspace** (last resort) | Only when the app must reach real data or real coworkers. | Usually gated by admin approval, and the developer may not be the admin. | + +Then follow the matching sub-step below. Whichever target they pick, authentication is the same Step 2 flow: the `/slackauthticket` command works in any workspace the developer belongs to, so there is no sandbox-specific login. + +Whichever sub-step you follow, wait for confirmation that a target workspace exists and is authenticated before proceeding. + +### 3a. Developer sandbox (recommended) + +List existing sandboxes. Pass `--team` so the CLI does not stop to ask which authentication to use (get the team ID from `SLACK_CMD auth list`): + +```bash +SLACK_CMD sandbox list --team +``` + +**If the developer has no Developer Program account**, `sandbox list` returns nothing useful, because sandboxes belong to the developer program account whose email matches the authenticated user rather than to the workspace. If they say they do have an account, check that the email they are logged in with matches it before sending them to sign up, and log into a workspace under that email if not. Point them at , and offer the Free Team path in 3b as a way to start building now rather than waiting on signup. + +- **If a sandbox exists**: Show it and confirm they want to use it. +- **If no sandbox exists**: Create one. Ask the developer for a name and a password with AskUserQuestion, then run: + + ```bash + SLACK_CMD sandbox create --team --name --password + ``` + + **Important**: the password is a credential. Do NOT echo it, restate it, or write it into a summary. Pass it straight to the command, the same rule Step 4c applies to API keys. + + Sandboxes can also be created in the browser at . + +Once the sandbox exists, have the developer log into it with the Step 2 flow before continuing. + +**Basic sandboxes.** A developer who is not on a paid plan and has not added a payment method gets a basic sandbox. It works for everything this skill builds, with stricter limits: it is archived after 1 month of inactivity, has no Slack Connect, and does not support deploying apps to Slack infrastructure (ROSI). If the developer needs more, they can add a payment method (they are not charged) or join a paid plan, then upgrade the sandbox from without losing their apps or data. Limits are listed at . + +### 3b. Free Team (second choice) + +A Free Team is an ordinary Slack workspace on the free plan. The developer creates one at , then logs into it with the Step 2 flow. + +What to tell them: + +- Everything this skill builds works there. Bolt apps install and run fine on the free plan. +- The workspace is capped at **10 apps**. Past that the CLI reports `service_limits_exceeded`. +- **It is a standalone workspace, not an Enterprise Grid org**, unlike a developer sandbox. Anything org-level is therefore untestable: org-wide app installs and org-level app grants, the `admin.*` API methods (which need Business+ or Enterprise Grid), and multi-workspace behaviour generally. If the app targets those, use a sandbox instead. +- Do not invite coworkers into it. A Free Team with real users in it is a production workspace for the purposes of 3c. + +### 3c. Existing production workspace (last resort) + +Only when the app genuinely needs real data or real users. Warn the developer before they log in: + +- **Admin app approval (AAA) is likely to block the install.** It is always on for Enterprise Grid organizations and can be switched on in standalone workspaces. When it applies, the install in Step 5 stops and asks whether to request approval, and then the developer waits on an admin. +- To send that request without the prompt, set `SLACK_AUTO_REQUEST_AAA=1` in the environment. It is an environment variable, not a CLI flag. +- If approval is denied or slow, fall back to 3a or 3b instead of fighting it. + +--- + +## Step 4: Create the App from a Template + +Ask the developer what kind of app they want to build. Present the available templates based on their chosen framework (`$0`): + +### bolt-js templates + +| Template | Repo | Description | +|----------|------|-------------| +| Starter Template | `slack-samples/bolt-js-starter-template` | Basic Bolt JS app — great starting point | +| Starter Agent | `slack-samples/bolt-js-starter-agent` | Minimal AI agent using Claude/OpenAI | +| Support Agent | `slack-samples/bolt-js-support-agent` | AI-powered IT helpdesk agent | +| Getting Started | `slack-samples/bolt-js-getting-started-app` | Official getting started tutorial app | +| Examples | `slack-samples/bolt-js-examples` | Unified showcase of Slack features | + +### bolt-python templates + +| Template | Repo | Description | +|----------|------|-------------| +| Starter Template | `slack-samples/bolt-python-starter-template` | Basic Bolt Python app — great starting point | +| Starter Agent | `slack-samples/bolt-python-starter-agent` | Minimal AI agent using Claude/OpenAI/Pydantic AI | +| Support Agent | `slack-samples/bolt-python-support-agent` | AI-powered IT helpdesk agent | +| Assistant Template | `slack-samples/bolt-python-assistant-template` | Agents & Assistants template | +| Examples | `slack-samples/bolt-python-examples` | Unified showcase of Slack features | + +Use AskUserQuestion to let the developer pick a template. Recommend the **Starter Template** for first-timers or the **Starter Agent** if they want to build an AI agent. + +**Existing app:** do not ask which template. Use the repo from `--template`. + +### 4a. Choose an AI provider (agent templates only) + +If the developer picks **Starter Agent** or **Support Agent**, these templates contain subdirectories for different AI providers. Ask the developer which provider they want to use via AskUserQuestion, offering only the subdirectories for their framework (`$0`) from the tables below. + +The provider list depends on the framework, so the framework must be settled before you ask. If it isn't yet, ask for the framework first and wait for the answer. Do not batch the framework and provider questions into one AskUserQuestion call. + +**bolt-js subdirectories:** + +| Subdir | Description | +|--------|-------------| +| `claude-agent-sdk` | Uses Anthropic's Claude Agent SDK | +| `openai-agents-sdk` | Uses OpenAI's Agents SDK | + +**bolt-python subdirectories:** + +| Subdir | Description | +|--------|-------------| +| `claude-agent-sdk` | Uses Anthropic's Claude Agent SDK | +| `openai-agents-sdk` | Uses OpenAI's Agents SDK | +| `pydantic-ai` | Uses Pydantic AI (supports multiple LLM backends) | + +Recommend **Claude Agent SDK** as the default option. + +**Existing app:** the same rule applies when `--template` is a Starter Agent or Support Agent repo. If `--subdir` was given, use it and skip the question. + +### 4b. Name and create the project + +Ask what they want to name their project (suggest a default like `my-slack-app`), then run: + +**For templates WITHOUT subdirectories** (Starter Template, Getting Started, Assistant Template, Examples): + +```bash +SLACK_CMD create -t +``` + +**For agent templates WITH subdirectories** (Starter Agent, Support Agent): + +```bash +SLACK_CMD create -t --subdir +``` + +For example: + +```bash +# Non-agent template +SLACK_CMD create my-slack-app -t slack-samples/bolt-js-starter-template + +# Agent template with provider subdir +SLACK_CMD create my-slack-agent -t slack-samples/bolt-js-starter-agent --subdir claude-agent-sdk +``` + +**Existing app:** link the project to the app instead of creating a new one. Add `--app`, `--team`, and `--environment local`, and `--subdir` for agent templates: + +```bash +SLACK_CMD create -t [--subdir ] --app --team --environment local +``` + +For example: + +```bash +SLACK_CMD create my-slack-agent -t slack-samples/bolt-js-starter-agent --subdir claude-agent-sdk --app A0123456789 --team T0123456789 --environment local +``` + +The CLI saves the app ID to the project's local environment and updates the project's manifest to match the app in App Settings, so keep the scopes and events the developer picked there. Don't change the manifest back to the template's. + +If `SLACK_CMD create` fails with `invalid_app_id`, the CLI has created the project folder but not linked the app, so stop before Step 5. Tell the developer that the app ID and team don't match a workspace they are logged in to, delete the new project folder, and ask them to check both values in App Settings. + +Confirm the project was created successfully by checking that the directory exists and listing its contents. + +### 4c. Set required environment variables (agent templates only) + +If the developer chose an agent template (Starter Agent or Support Agent), they need to set the required API key for their chosen AI provider. Ask for the key value using AskUserQuestion, then set it using the Slack CLI from within the project directory. + +**Required environment variables by provider:** + +| Provider | Env Variable | Description | +|----------|-------------|-------------| +| `claude-agent-sdk` | `ANTHROPIC_API_KEY` | Anthropic API key | +| `openai-agents-sdk` | `OPENAI_API_KEY` | OpenAI API key | +| `pydantic-ai` | `OPENAI_API_KEY` | OpenAI API key (required). Optionally also `ANTHROPIC_API_KEY` if using Anthropic as the backend — if both are set, Anthropic is used by default. | + +Use AskUserQuestion to ask the developer for their API key value(s). Then set each one: + +```bash +cd && SLACK_CMD env set +``` + +For example: + +```bash +cd my-slack-agent && SLACK_CMD env set ANTHROPIC_API_KEY sk-ant-... +``` + +**Important**: Do NOT store or echo API key values in logs or output. Only pass them directly to `SLACK_CMD env set`. + +--- + +## Step 5: Run the App Locally + +Use the `slack-cli` skill — **Step 6: Running an App Locally (`slack run`)** — to resolve the app or team target and start the dev server in the background. + +Tell the developer their app is now running and installed in the workspace they chose in Step 3, and that file changes will auto-reload it. + +**Existing app:** the app runs as the app from `--app`, in the team from `--team`, so the developer can try it where App Settings installed it. + +If the install stops on an admin approval request, they picked a workspace with AAA turned on: see Step 3c for the options. + +--- + +## Step 6: Next Steps + +After the app is running, suggest next steps: + +1. **Explore the code**: Read through the project files together — offer to explain the app structure, manifest, listeners, etc. +2. **Make a change**: Suggest a small modification (like changing a message response) to see hot-reload in action. +3. **Add features**: Based on the template, suggest relevant Slack features to add (slash commands, events, modals, AI capabilities, etc.). For any Block Kit UI (a message layout, a modal, or a Home tab), use the `block-kit` skill rather than building the JSON here. +4. **Check the docs**: Point to for the full Slack Platform documentation. + +--- + +## Notes + +- `SLACK_CMD` is a placeholder — always substitute the actual command name resolved in Step 1a (typically `slack`, but may be an alias). +- This skill focuses on **Bolt for JavaScript** and **Bolt for Python** only. Do not suggest Deno, workflow apps, or `slack deploy` (hosted deployment). +- This skill scaffolds and runs the app. It does not own Block Kit JSON. If the developer asks to build or edit a message, modal, or Home tab layout (now or in Step 6), use the `block-kit` skill instead of writing the blocks here from memory. +- `SLACK_CMD sandbox create` prompts for a name and password only when those flags are missing. Supply `--team`, `--name`, and `--password` and it runs non-interactively, so you can run it yourself rather than handing it to the developer. `SLACK_CMD sandbox list` needs `--team` for the same reason: without it the CLI prompts for which authentication to use. +- Free Teams and developer sandboxes both support everything this skill builds. The CLI's `free_team_not_allowed` error is scoped to low-code workflow and function apps, which this skill does not create. +- If the developer hits issues, suggest `SLACK_CMD doctor` to diagnose their setup. diff --git a/.claude/skills/deploy-slack-app/SKILL.md b/.claude/skills/deploy-slack-app/SKILL.md new file mode 100644 index 0000000..d1d1ad1 --- /dev/null +++ b/.claude/skills/deploy-slack-app/SKILL.md @@ -0,0 +1,200 @@ +--- +name: deploy-slack-app +description: Use when a developer wants to deploy, host, or run a Slack app somewhere it keeps working after the local process stops, or mentions Railway, Heroku, `railway up`, `git push heroku`, `slack deploy`, a `deploy` hook in `.slack/hooks.json`, hosting a Socket Mode or Request URL (HTTP) Bolt app, deploying from Windows, graduating an app out of a developer sandbox, or tearing down a deployed app. +--- + +# Deploy Slack App + +Take a Slack app that already works locally and deploy it to a hosting provider as a separate Slack app, with its own app ID, that keeps running without the developer's machine. The local development app is unchanged, and **Step 5: Deploy** explains how the two coexist. This is the step after the `test-slack-app` skill confirms the app responds. + +The mechanism is the Slack CLI's `deploy` hook. Adding a `deploy` key to the project's `.slack/hooks.json` replaces Slack's own hosted deployment with a script of your choosing, and the CLI runs that script _after_ it has created and installed the deployed app. That ordering is the whole reason this approach is worth using: the app's bot and app-level tokens are already in the script's environment by the time it runs, so nothing here has to prompt for a secret or store one. + +Two supported providers, both running the app as a long-lived worker process: + +| Provider | Process type | Deploys from | Secrets | Current pricing | +| --- | --- | --- | --- | --- | +| Railway | Service, no port binding required | The working directory | Passed on stdin | | +| Heroku | `worker` dyno | A git push of committed code | Passed as arguments | | + +Railway is the better default, and the reasons are in **Step 2a: Choose a Provider**. + +--- + +## Step 1: Check Prerequisites + +### 1a. Detect the Slack CLI + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public Slack CLI is installed and resolve its command name. Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. The fingerprint check, alias fallback, and install instructions all live there; do not duplicate them. Refer to the resolved command as `SLACK_CMD` throughout. + +This matters more than it looks. Some machines have an unrelated internal tool named `slack` on the path, and running that instead produces confusing failures well into the deploy. + +### 1b. Confirm the App Uses Socket Mode + +**Read the app's manifest rather than asking.** The project already declares which mode it uses, so a question here is redundant. Check `manifest.json` for `settings.socket_mode_enabled`. If `.slack/config.json` sets the manifest source to `remote`, there is no local file, so read it with `SLACK_CMD manifest info` instead. + +- **Socket Mode enabled:** continue. The app opens an outbound websocket to Slack, needs no public URL, and binds no HTTP port. +- **Socket Mode disabled, or the app uses a Request URL:** **stop here.** This skill does not cover Request URL apps yet, because a hosted Request URL app also needs a public address captured after the deploy and written back into the app manifest. Tell the developer plainly that this is the gap, and that converting the app to Socket Mode is the supported path today. Support may have shipped in a newer version of the Slack Skills Plugin, so ask the developer to update the plugin and try again. If they are already on the latest version, point them to to add a reaction or comment. + +If the manifest is ambiguous, read the app's entrypoint. A Bolt for JavaScript app constructed with `socketMode: true` and an `appToken`, or a Bolt for Python app started through `SocketModeHandler`, is a Socket Mode app. + +### 1c. Confirm the Runtime Is Supported + +This flow is verified on macOS and Linux. The deploy hook is a shell script, so a Windows developer needs a PowerShell equivalent that does not exist yet. On Windows, say so rather than letting the deploy fail partway through. WSL is a workable path in the meantime. Support may have shipped in a newer version of the Slack Skills Plugin, so ask the developer to update the plugin and try again. If they are already on the latest version, point them to to add a reaction or comment. + +--- + +## Step 2: Choose a Provider and a Team + +Ask the developer two things the project cannot tell you: which provider to deploy to, and which Slack team to deploy into. + +### 2a. Choose a Provider + +Ask which provider, because cost is the thing the developer cannot infer from the project. Give the developer both pricing links from the table above so they can check current terms. **Do not fetch the pages or quote prices, plan names, or trial terms.** Providers change them often, and this skill can be installed long after it was written. + +What does not change with the price list, and is worth saying: + +- **Railway** is the default recommendation. It accepts secrets on stdin, so the tokens never appear in process arguments. It deploys the working directory, so a re-deploy needs no commit, and it needs no `Procfile`. +- **Heroku** fits when the developer already has an account, or a team standard that points there. It builds from git, so only committed code is deployed. Some accounts, including enterprise-managed ones, cannot own a personal app and must create it on a Heroku team. Personal apps and team apps can have different plans and billing, so ask which team to use rather than picking one: a shared team has a shared budget. + +Say plainly that **both providers keep the app running continuously**, which is what a Socket Mode app requires. Always-on hosting is a paid service in the end, so expect it to cost something once any trial runs out. + +Once the developer picks one, read that provider's reference file and follow it: `references/railway.md` or `references/heroku.md`. Each holds the install and authentication commands, the provider's own requirements for the project, and the environment variables its deploy script reads. **Step 4: Wire Up the Deploy Hook** works through them. + +### 2b. Choose a Team + +Run `SLACK_CMD auth list`. If it lists one team, use it. If it lists more than one, show the developer each team's name and ID and ask which one to deploy into. + +**Never pick the team yourself.** Do not assume the standalone workspace or the Enterprise org, and do not reuse the team from `.slack/apps.dev.json`, which is often a developer sandbox. A wrong guess installs the app into a team the developer did not intend, and a later deploy to the right team creates a second Slack app. + +--- + +## Step 3: Confirm It Works Locally First + +**Do not deploy an app that has not been seen working.** A broken deploy and a broken app look identical in a provider's logs, and separating them afterwards costs far more than checking first. + +Use the `test-slack-app` skill to run the app with `SLACK_CMD run` and exercise at least one real surface, so there is a known-good behaviour to re-check after the deploy. Note which surface was used: the same one is the check in **Step 6: Verify the Deployment**. + +--- + +## Step 4: Wire Up the Deploy Hook + +Three things to set up. **Check whether each already exists before writing it**, because re-deploying an app is the common case and clobbering a developer's edited script is not recoverable. + +### 4a. Prepare the Provider + +Work through the chosen provider's reference file before writing anything, because the deploy script only checks these and stops. It cannot fix them. + +- **Install and authenticate the provider's CLI.** Run its `whoami` check. Logging in opens a browser, so if the check fails, ask the developer to run the login command in their own terminal rather than running it yourself. +- **Settle the names and ownership with the developer.** For Heroku: a distinctive app name, and whether the app belongs to a team (`heroku teams`). For Railway: the workspace, if the account has more than one. These become environment variables on the deploy command in **Step 5: Deploy**. +- **Meet the provider's project requirements.** For Heroku, write the `Procfile` and commit it. For Railway, confirm the start command it will detect. + +### 4b. Write the Deploy Script + +Copy the provider's deploy script into the project's `.slack/` directory under the same name, then make it executable: + +- Railway: `references/deploy-railway.sh` to `.slack/deploy-railway.sh` +- Heroku: `references/deploy-heroku.sh` to `.slack/deploy-heroku.sh` + +For example, `chmod +x .slack/deploy-railway.sh`. + +Each script is self-contained. It validates that both tokens arrived, reads the deployed app ID from `.slack/apps.json` for its log line, and then runs the provider's preflight, provision, configure, and deploy steps in order. There is nothing else to copy. The CLI runs the hook from the project root, so the script's relative paths resolve there even though the file lives in `.slack/`. + +**If the script already exists**, show the developer that it is there and ask before overwriting. A developer may have adjusted it. + +### 4c. Register the Hook + +Add a `deploy` key inside the existing `hooks` object in `.slack/hooks.json`, pointing at the provider's script. For Railway: + +```json +"deploy": "./.slack/deploy-railway.sh" +``` + +For Heroku, the value is `./.slack/deploy-heroku.sh`. **Leave the `get-hooks` entry exactly as it is.** Its value differs between Bolt for JavaScript and Bolt for Python projects, so do not copy one from elsewhere. + +**If a `deploy` key is already present, do not add a second one.** A duplicate key produces invalid JSON, and the CLI will reject the project rather than deploy it. If the existing key already points at the chosen provider's script, leave it. If it points somewhere else, such as the other provider's script, show the developer and ask before changing it. + +--- + +## Step 5: Deploy + +Run `SLACK_CMD deploy` from the project root and watch the output. The CLI creates the deployed app, installs it, and then runs the hook script, so the first part of the output is app installation and the second is the provider's build. + +Four flags matter when running this outside an interactive terminal, which includes most agent sessions. The CLI asks four questions, and each one is fatal unanswered: a non-interactive shell gets `The input device is not a TTY or does not support interactivity` and nothing is deployed. + +- `--skip-update` stops the CLI pausing to offer an upgrade. +- `--team ` picks the workspace or organization. Use the team the developer chose in **Step 2b: Choose a Team**. +- `--app deployed` selects the deployed app environment, and creates that app on a first deploy. Without it the CLI asks the developer to choose between an existing app and a new one. This is the flag most easily missed, because the prompt it answers only appears on a project that has never been deployed. +- `--org-workspace-grant all` answers the workspace-grant prompt for an org-installed app. + +So the full command is `SLACK_CMD deploy --skip-update --team --app deployed --org-workspace-grant all`. + +Put any provider variables settled in **Step 4a: Prepare the Provider** in front of it. The hook inherits the CLI's environment, so this is how they reach the script: + +```sh +HEROKU_TEAM= HEROKU_APP_NAME= SLACK_CMD deploy --skip-update --team --app deployed --org-workspace-grant all +``` + +**The deployed app is a different app from the one `SLACK_CMD run` uses.** The CLI writes the deployed app to `.slack/apps.json` and the local development app to `.slack/apps.dev.json`, keyed by team. Both keep working independently, which is the intended design, not a mistake to correct. + +**Commit `.slack/apps.json` after the first deploy.** It holds app and team IDs, not secrets, and the project's `.slack/.gitignore` leaves it tracked on purpose. Committing it keeps every later deploy pointed at the same app. On Heroku it also stops the deploy script warning about uncommitted changes on each re-deploy. + +One consequence to warn the developer about: the two apps declare the same slash commands in the same workspace. Running `SLACK_CMD run` while the deployed app is live makes it ambiguous which one answers a slash command. Stop the local process when checking the deployed app, which **Step 6: Verify the Deployment** does anyway. + +--- + +## Step 6: Verify the Deployment + +Check all three of these. The first two can pass while the app is silent in Slack. + +### 6a. The Service Is Running + +Use the status and log commands from the provider's reference file. Look for the app's own startup logging and the Socket Mode websocket connecting. A build that succeeded and a process that then exited look very different here, so read the logs rather than trusting the build result. + +### 6b. The App Answers in Slack, With Nothing Running Locally + +**Stop the local process first.** This is the only check that proves the deployed app is doing the work rather than the developer's laptop. Exercise the surface noted in **Step 3: Confirm It Works Locally First**, and confirm the response appears in Slack and the corresponding request appears in the provider's logs. + +### 6c. Both Apps Are Distinct + +Show the developer the app ID in `.slack/apps.json` and the one in `.slack/apps.dev.json` and confirm they differ. Then confirm `SLACK_CMD run` still drives the development app. + +--- + +## Step 7: Re-deploy + +Shipping a change is the same `SLACK_CMD deploy` command, with the same flags as **Step 5: Deploy**. Everything in **Step 4: Wire Up the Deploy Hook** is already in place, so skip it and go straight to the deploy, and expect the same app rather than a second one. + +Two provider differences to know about, both handled by the deploy scripts: + +- **Railway** uploads the working directory and rebuilds every time, so no commit is needed. +- **Heroku** builds from a git push, so uncommitted changes are not deployed. A push with no new commit builds nothing, so the script restarts the dynos instead, which picks up any changed tokens. Commit code changes before re-deploying. + +If a re-deploy creates a second Slack app, the deployed app entry in `.slack/apps.json` was lost. Before deploying again, confirm `.slack/apps.json` has an entry for the `--team` ID, rather than deleting apps afterwards. + +--- + +## Step 8: Tear Down a Deployment + +Use this when the developer is done with the deployed app, for example after trying the skill out. It deletes the host's copy and the deployed Slack app, and leaves the development app alone. + +**Name every resource and ask once before deleting anything.** These deletes are permanent. Say which provider project or app goes, and which Slack app ID from `.slack/apps.json`, then wait for a yes. + +1. **Delete the provider's copy first**, so nothing is left holding a connection to Slack with tokens that are about to stop working. The commands are in the provider's reference file, under "Tearing down". +2. **Delete the deployed Slack app** with `SLACK_CMD app delete --team --app deployed --force`. Read the team ID from `.slack/apps.json`. `--force` skips the confirmation prompt, which would otherwise fail in a non-interactive shell. When it was the only deployed app, the CLI removes `.slack/apps.json` as well, so commit that deletion. +3. **Leave the development app** unless the developer asks for it too. It is the app `SLACK_CMD run` uses, and they will usually keep working on it. If they ask, the same command with `--app local` deletes it. + +Leave `.slack/hooks.json` and the deploy script in place, so a later `SLACK_CMD deploy` sets everything up again from the start. + +--- + +## Notes + +**Serverless providers cannot host a Socket Mode app.** A Socket Mode app is a process that stays resident and holds an outbound websocket open. Vercel, AWS Lambda, and similar platforms run per-request functions with a maximum duration and no always-on process type, so there is nothing for the websocket to live in. When a developer asks for one of these, explain the constraint rather than attempting it. Hosting a Slack app on a serverless platform means a Request URL app, which this skill does not cover yet. + +**Other providers.** When a developer asks about a provider this skill does not cover, the two things to check are whether it offers an always-on background worker process type and how that process is billed. + +**The token handoff is not a documented contract.** The Slack CLI does not pass the tokens to the deploy hook explicitly. It sets them on its own process during app installation, and the hook script inherits them because it runs later in that same process. It works, and it only works for apps with no Slack-hosted function runtime, which covers every Bolt app. That is why each deploy script checks for both tokens and stops with a readable message instead of assuming they are present. + +**Not `slack deploy` without a hook.** With no `deploy` key in `.slack/hooks.json`, `SLACK_CMD deploy` targets Slack's own hosted infrastructure, which is a different product for a different kind of app. The `slack-cli` skill covers the CLI's commands generally. + +**Building the app comes first.** If there is no app yet, start with the `create-slack-app` skill and come back here once it runs locally. diff --git a/.claude/skills/deploy-slack-app/references/deploy-heroku.sh b/.claude/skills/deploy-slack-app/references/deploy-heroku.sh new file mode 100755 index 0000000..91c711d --- /dev/null +++ b/.claude/skills/deploy-slack-app/references/deploy-heroku.sh @@ -0,0 +1,186 @@ +#!/usr/bin/env bash +# +# Deploy a Socket Mode Bolt app to Heroku, as a Slack CLI `deploy` hook. +# +# Installed as .slack/deploy-heroku.sh and registered as the `deploy` hook in +# .slack/hooks.json by the deploy-slack-app skill. The CLI runs it from the +# project root after installing the deployed app, so relative paths resolve +# there and SLACK_BOT_TOKEN and SLACK_APP_TOKEN are inherited from its +# environment. That handoff is not a documented contract, which is why the +# checks below exist. +# +# Supported on macOS and Linux. + +set -euo pipefail + +say() { printf '%s\n' "$*"; } +die() { printf 'error: %s\n' "$*" >&2; exit 1; } + +# The Heroku app name. When unset, reuse the app the `heroku` git remote already +# points at, so a re-deploy targets the same app even though an environment +# variable set on the first deploy is gone by the next one. The directory name +# is only the default for a first deploy. Heroku app names are global, so a +# generic one is often taken. +remote_app=$( + git remote get-url heroku 2>/dev/null \ + | sed -n 's#.*/\([^/]*\)\.git$#\1#p' \ + || true +) +HEROKU_APP_NAME="${HEROKU_APP_NAME:-${remote_app:-$(basename "$PWD")}}" + +# Set HEROKU_TEAM when the app has to belong to a Heroku team rather than to the +# account personally. Some accounts, including enterprise-managed ones, cannot +# own personal apps at all: `apps:create` refuses with "All apps must belong to +# a team. Create the app on a team instead." Leave empty for a personal app. +HEROKU_TEAM="${HEROKU_TEAM:-}" + +# --------------------------------------------------------------------------- +# 1. Preconditions +# --------------------------------------------------------------------------- + +# Both tokens are required. A Socket Mode app cannot open a websocket without an +# app-level token carrying connections:write, so a missing SLACK_APP_TOKEN is a +# hard stop rather than something to warn about and continue past. +[ -n "${SLACK_BOT_TOKEN:-}" ] || die \ + "SLACK_BOT_TOKEN is not set. It is normally supplied by 'slack deploy' during app install. If you are running this script directly, export it first." +[ -n "${SLACK_APP_TOKEN:-}" ] || die \ + "SLACK_APP_TOKEN is not set. Socket Mode needs an app-level token with connections:write. It is normally supplied by 'slack deploy' during app install." + +command -v heroku >/dev/null 2>&1 || die \ + "the heroku CLI is not installed. Install it with 'brew tap heroku/brew && brew install heroku' (macOS) or see https://devcenter.heroku.com/articles/heroku-cli, then re-run 'slack deploy'." +heroku auth:whoami >/dev/null 2>&1 || die \ + "the heroku CLI is not authenticated. Run 'heroku login' (or set HEROKU_API_KEY), then re-run 'slack deploy'." +git rev-parse --git-dir >/dev/null 2>&1 || die \ + "this project is not a git repository. Heroku builds from a git push, so run 'git init' and commit the project first." +# A project created inside another repository passes the check above on the +# parent's .git, and the push below would then deploy the parent's code. Compare +# physical paths, because macOS reports some directories through symlinks. +repo_root=$(cd "$(git rev-parse --show-toplevel)" && pwd -P) +[ "${repo_root}" = "$(pwd -P)" ] || die \ + "this project is inside another git repository (${repo_root}) rather than being its own. Heroku would deploy that repository's code instead of this app. Run 'git init' in the project directory and commit the project there." +git rev-parse --verify HEAD >/dev/null 2>&1 || die \ + "this repository has no commits yet. Heroku builds from a git push, so commit the project first." +[ -z "$(git status --porcelain)" ] || say \ + "warning: there are uncommitted or untracked changes. Heroku deploys committed code only, so those changes will not go live." +git ls-files --error-unmatch Procfile >/dev/null 2>&1 || die \ + "Procfile is missing or not committed. Heroku needs it to run this app as a worker rather than a web process. Create it with one line, such as 'worker: npm start' (Bolt for JavaScript) or 'worker: python app.py' (Bolt for Python), and commit it." + +# --------------------------------------------------------------------------- +# 2. Report which app is being deployed +# --------------------------------------------------------------------------- + +# The deploy hook receives no app ID, so read it off disk. .slack/apps.json holds +# deployed apps keyed by team ID; .slack/apps.dev.json holds the local dev app +# and is deliberately not touched here. +# +# Parsed with grep and sed rather than a language runtime: this script has to +# work in a Bolt for Python project as readily as a Bolt for JavaScript one. +app_id="unknown" +if [ -f .slack/apps.json ]; then + found=$( + tr -d '\n' < .slack/apps.json \ + | grep -o '"app_id"[[:space:]]*:[[:space:]]*"[^"]*"' \ + | sed 's/.*"\([^"]*\)"$/\1/' \ + | paste -sd , - \ + || true + ) + [ -n "${found}" ] && app_id="${found}" +fi + +say "Deploying Slack app ${app_id} to Heroku" + +# --------------------------------------------------------------------------- +# 3. Provision the Heroku app +# --------------------------------------------------------------------------- + +# apps:create fails outright when the app already exists, so check first. This +# is what lets a re-deploy target the same app instead of erroring. +# +# apps:info reports "Couldn't find that app" both for an app that does not exist +# and for one that exists under another account, because Heroku app names are +# globally unique across all of Heroku. A generic name taken by a stranger +# therefore reaches apps:create below and fails there on the name rather than +# here. Set HEROKU_APP_NAME to something distinctive to avoid it. +if heroku apps:info --app "${HEROKU_APP_NAME}" >/dev/null 2>&1; then + say "Reusing the Heroku app ${HEROKU_APP_NAME}" +else + say "Creating the Heroku app ${HEROKU_APP_NAME}" + if [ -n "${HEROKU_TEAM}" ]; then + heroku apps:create "${HEROKU_APP_NAME}" --team "${HEROKU_TEAM}" >/dev/null + else + heroku apps:create "${HEROKU_APP_NAME}" >/dev/null + fi +fi + +# Sets or resets the `heroku` git remote to point at this app. Safe to repeat. +heroku git:remote --app "${HEROKU_APP_NAME}" >/dev/null + +# --------------------------------------------------------------------------- +# 4. Configure secrets +# --------------------------------------------------------------------------- + +# heroku config:set takes values as arguments only, so these two tokens are +# visible to `ps` while the command runs. The Heroku CLI offers no alternative. +say "Setting SLACK_BOT_TOKEN and SLACK_APP_TOKEN on ${HEROKU_APP_NAME}" +heroku config:set \ + "SLACK_BOT_TOKEN=${SLACK_BOT_TOKEN}" \ + "SLACK_APP_TOKEN=${SLACK_APP_TOKEN}" \ + --app "${HEROKU_APP_NAME}" >/dev/null + +# --------------------------------------------------------------------------- +# 5. Deploy +# --------------------------------------------------------------------------- + +# Push the current HEAD to the app's main branch, whatever local branch the +# developer is on. The output is captured rather than piped so that a failed +# push is distinguishable from an up-to-date one. +# +# A push with no new commit reports "Everything up-to-date" and builds nothing. +# In that case the dynos are restarted below instead, which picks up any +# changed tokens. The code itself has not changed, so there is nothing to +# rebuild, and an empty commit would also sweep up anything the developer had +# staged. +say "Pushing to Heroku" +push_out=$(git push heroku HEAD:refs/heads/main 2>&1) \ + || die "the git push to Heroku failed: +${push_out}" +printf '%s\n' "${push_out}" + +up_to_date=false +if printf '%s' "${push_out}" | grep -q 'Everything up-to-date'; then + up_to_date=true +fi + +# Run exactly one worker and no web dyno, in one call. +# +# The Node buildpack adds a default `web` process type even though the Procfile +# only declares `worker`, and Heroku starts it on the first release. It runs the +# same start command, so it is a second copy of the app holding a second Socket +# Mode connection, stuck in a restart loop because it never binds $PORT, and +# billed as a second dyno. The worker's own logs look healthy throughout. +# +# The release starts it before this step can run, so for a few seconds after a +# first deploy both copies are connected. After this scale, web stays at 0 on +# every later release. +# +# The Python buildpack adds no `web` type, and scaling one that does not exist +# is an error, so only scale web when the formation has it. +formation=$(heroku ps:scale --app "${HEROKU_APP_NAME}" 2>/dev/null || true) +if printf '%s' "${formation}" | grep -qE '(^|[[:space:]])web='; then + say "Scaling the worker dyno to 1 and the web dyno to 0" + heroku ps:scale worker=1 web=0 --app "${HEROKU_APP_NAME}" +else + say "Scaling the worker dyno to 1" + heroku ps:scale worker=1 --app "${HEROKU_APP_NAME}" +fi + +if [ "${up_to_date}" = true ]; then + say "No new commit to deploy. Restarting the dynos to pick up the current config." + heroku ps:restart --app "${HEROKU_APP_NAME}" +fi + +say "" +say "Deployed. A successful build does not prove the app started, so check for" +say "the Socket Mode connection in the app's logs:" +say " heroku logs --num 100 --app ${HEROKU_APP_NAME}" +say " heroku ps --app ${HEROKU_APP_NAME}" diff --git a/.claude/skills/deploy-slack-app/references/deploy-railway.sh b/.claude/skills/deploy-slack-app/references/deploy-railway.sh new file mode 100755 index 0000000..140aade --- /dev/null +++ b/.claude/skills/deploy-slack-app/references/deploy-railway.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# +# Deploy a Socket Mode Bolt app to Railway, as a Slack CLI `deploy` hook. +# +# Installed as .slack/deploy-railway.sh and registered as the `deploy` hook in +# .slack/hooks.json by the deploy-slack-app skill. The CLI runs it from the +# project root after installing the deployed app, so relative paths resolve +# there and SLACK_BOT_TOKEN and SLACK_APP_TOKEN are inherited from its +# environment. That handoff is not a documented contract, which is why the +# checks below exist. +# +# Supported on macOS and Linux. + +set -euo pipefail + +say() { printf '%s\n' "$*"; } +die() { printf 'error: %s\n' "$*" >&2; exit 1; } + +RAILWAY_PROJECT_NAME="${RAILWAY_PROJECT_NAME:-$(basename "$PWD")}" +RAILWAY_SERVICE_NAME="${RAILWAY_SERVICE_NAME:-$(basename "$PWD")}" + +# Set RAILWAY_WORKSPACE when the account belongs to more than one workspace. +# `railway init` otherwise asks which one to use, and that prompt fails outside +# an interactive terminal. Only read when a new project is created. +RAILWAY_WORKSPACE="${RAILWAY_WORKSPACE:-}" + +# --------------------------------------------------------------------------- +# 1. Preconditions +# --------------------------------------------------------------------------- + +# Both tokens are required. A Socket Mode app cannot open a websocket without an +# app-level token carrying connections:write, so a missing SLACK_APP_TOKEN is a +# hard stop rather than something to warn about and continue past. +[ -n "${SLACK_BOT_TOKEN:-}" ] || die \ + "SLACK_BOT_TOKEN is not set. It is normally supplied by 'slack deploy' during app install. If you are running this script directly, export it first." +[ -n "${SLACK_APP_TOKEN:-}" ] || die \ + "SLACK_APP_TOKEN is not set. Socket Mode needs an app-level token with connections:write. It is normally supplied by 'slack deploy' during app install." + +command -v railway >/dev/null 2>&1 || die \ + "the railway CLI is not installed. Install it with 'brew install railway' (macOS) or see https://docs.railway.com/guides/cli, then re-run 'slack deploy'." +railway whoami >/dev/null 2>&1 || die \ + "the railway CLI is not authenticated. Run 'railway login' in a terminal (or export RAILWAY_API_TOKEN, an account token), then re-run 'slack deploy'." + +# --------------------------------------------------------------------------- +# 2. Report which app is being deployed +# --------------------------------------------------------------------------- + +# The deploy hook receives no app ID, so read it off disk. .slack/apps.json holds +# deployed apps keyed by team ID; .slack/apps.dev.json holds the local dev app +# and is deliberately not touched here. +# +# Parsed with grep and sed rather than a language runtime: this script has to +# work in a Bolt for Python project as readily as a Bolt for JavaScript one. +app_id="unknown" +if [ -f .slack/apps.json ]; then + found=$( + tr -d '\n' < .slack/apps.json \ + | grep -o '"app_id"[[:space:]]*:[[:space:]]*"[^"]*"' \ + | sed 's/.*"\([^"]*\)"$/\1/' \ + | paste -sd , - \ + || true + ) + [ -n "${found}" ] && app_id="${found}" +fi + +say "Deploying Slack app ${app_id} to Railway" + +# --------------------------------------------------------------------------- +# 3. Provision the Railway project and service +# --------------------------------------------------------------------------- + +# `railway status` fails when the directory is not linked to a project. Reusing +# an existing link is what makes a re-deploy update the same service instead of +# creating a second project on every run. The status is printed so a link to +# the wrong project is visible in the deploy output. +if status_out=$(railway status 2>&1); then + say "Reusing the Railway project already linked to this directory:" + printf '%s\n' "${status_out}" +else + say "No linked Railway project. Creating ${RAILWAY_PROJECT_NAME}" + if [ -n "${RAILWAY_WORKSPACE}" ]; then + railway init -n "${RAILWAY_PROJECT_NAME}" --workspace "${RAILWAY_WORKSPACE}" + else + railway init -n "${RAILWAY_PROJECT_NAME}" + fi +fi + +# A fresh `railway init` leaves the project with no service at all, and every +# variable command fails with "Project has no services" until one exists. So +# create the service explicitly before setting anything on it. +# +# `railway add -s NAME` on its own still prompts ("Enter a variable") and hangs +# in a non-interactive shell even though the name was supplied. Passing +# --variables answers that prompt. The value here is a harmless marker, not a +# secret: the two tokens go over stdin below, never on a command line. +if railway variable list --service "${RAILWAY_SERVICE_NAME}" >/dev/null 2>&1; then + say "Reusing the Railway service ${RAILWAY_SERVICE_NAME}" +else + say "Creating the Railway service ${RAILWAY_SERVICE_NAME}" + railway add --service "${RAILWAY_SERVICE_NAME}" --variables "SLACK_DEPLOY_HOOK=1" >/dev/null +fi + +# --------------------------------------------------------------------------- +# 4. Configure secrets +# --------------------------------------------------------------------------- + +# --stdin keeps the token values out of the command line, so they never reach +# `ps` output or a shell history file. --skip-deploys stops each set from +# triggering its own build; the single `railway up` below is the deploy. +say "Setting SLACK_BOT_TOKEN and SLACK_APP_TOKEN on ${RAILWAY_SERVICE_NAME}" +printf '%s' "${SLACK_BOT_TOKEN}" \ + | railway variable set SLACK_BOT_TOKEN --service "${RAILWAY_SERVICE_NAME}" --stdin --skip-deploys >/dev/null +printf '%s' "${SLACK_APP_TOKEN}" \ + | railway variable set SLACK_APP_TOKEN --service "${RAILWAY_SERVICE_NAME}" --stdin --skip-deploys >/dev/null + +# --------------------------------------------------------------------------- +# 5. Deploy +# --------------------------------------------------------------------------- + +# --ci streams the build logs and exits when the build ends, so a failed build +# shows up here rather than after the hook has already reported success. +# --detach would return before the build starts. +say "Uploading and building" +railway up --service "${RAILWAY_SERVICE_NAME}" --ci + +say "" +say "Build finished. A successful build does not prove the app started, so check" +say "for the Socket Mode connection in the app's logs:" +say " railway logs --service ${RAILWAY_SERVICE_NAME} --lines 100" +say " railway service status --service ${RAILWAY_SERVICE_NAME}" diff --git a/.claude/skills/deploy-slack-app/references/heroku.md b/.claude/skills/deploy-slack-app/references/heroku.md new file mode 100644 index 0000000..103baec --- /dev/null +++ b/.claude/skills/deploy-slack-app/references/heroku.md @@ -0,0 +1,129 @@ +# Heroku + +Heroku runs the app as a `worker` dyno, a process type that binds no HTTP port. +Only `web` dynos have to listen on `$PORT`, so a Socket Mode app fits the `worker` +type exactly. + +The deploy script for this provider is `deploy-heroku.sh`, alongside this file. +Copy it to `.slack/deploy-heroku.sh` as described in the parent skill's Step 4. + +**Cost.** Current pricing is at . Point the developer +there rather than quoting or fetching it. Two things hold whatever the price list +says: + +- **Who owns the app changes the bill.** Personal apps and team apps can have + different plans available and be billed differently, and a shared team has a + shared budget. Confirm with the developer which one they are creating. +- **Every running dyno counts.** That is why the deploy script makes sure no `web` + dyno runs alongside the worker. + +**Three things to know before choosing Heroku.** + +- **Some accounts cannot own an app personally.** Enterprise-managed Heroku accounts + are one case: `heroku apps:create` refuses with "All apps must belong to a team." + Run `heroku teams` to see which teams the account belongs to, ask the developer + which one to use, and set `HEROKU_TEAM` to it. +- **Tokens go on the command line.** `heroku config:set` has no stdin or file + input, so `SLACK_BOT_TOKEN` and `SLACK_APP_TOKEN` appear as process arguments and + are visible to `ps` while the command runs. The deploy hook runs the command + rather than a person typing it, so it stays out of shell history, but the `ps` + exposure is real. Mention it to the developer. +- **Deploying means pushing a commit.** Heroku builds from git, not from the + working directory, so the project must be a git repository with at least one + commit, and the code being deployed must be committed. Uncommitted changes are + not deployed. + +--- + +## Install and authenticate + +```sh +brew tap heroku/brew && brew install heroku +heroku auth:whoami # confirms the CLI is authenticated +``` + +If `heroku auth:whoami` fails, ask the developer to run `heroku login` in their +own terminal. It waits for a keypress and opens a browser, so it cannot complete +inside an agent session. For a headless setup, create a token with +`heroku authorizations:create` and export it as `HEROKU_API_KEY`. + +--- + +## What Heroku needs from the project + +A committed `Procfile` in the project root declaring the `worker` process type. +Without it Heroku infers a `web` process from the start command, which is the +wrong shape: it would expect the app to bind a port and mark the deploy as failed +when it does not. Write it with the project's own start command: + +```text +worker: npm start +``` + +For Bolt for Python, use the project's entrypoint, for example +`worker: python app.py`. Commit the file before deploying: the deploy script stops +if the `Procfile` is not in git, because an uncommitted one never reaches Heroku. + +The project must be its own git repository, not a directory inside another one. +`slack create` does not run `git init`, so check with `git rev-parse --show-toplevel` +and run `git init` in the project if it names a parent directory. The deploy script +stops in that case, because the push would deploy the parent repository's code. + +For Bolt for Python, also commit a `.python-version` file holding the major and minor +version the app runs on locally, such as `3.13`. Without one, Heroku picks its own +default version and warns that a missing file will become an error. + +--- + +## Environment variables + +- `HEROKU_APP_NAME` (optional): the Heroku app name. When unset, the script reuses + the app the project's `heroku` git remote points at, and on a first deploy falls + back to the project directory name. Names are globally unique across all of + Heroku and may only contain lowercase letters, digits, and dashes, so on a first + deploy pick something distinctive with the developer. +- `HEROKU_TEAM` (optional, sometimes required): the Heroku team to create the + app under. Required when the account cannot own personal apps. Leave empty for + a personal app. Only read when the app is first created. + +Pass them on the deploy command, as shown in the parent skill's Step 5. + +--- + +## Verifying + +```sh +heroku ps --app # expect one worker dyno, state "up" +heroku logs --num 100 --app # look for the Socket Mode connection +heroku config --app | cut -d: -f1 # confirms both tokens are set, without printing them +``` + +Do not use `heroku logs --tail`: it streams until it is stopped, which hangs an +agent session. Do not run a bare `heroku config`: it prints the token values. + +**Confirm only one dyno is running.** `heroku ps` should list `worker` at 1 and no +`web` process at all. If a `web` dyno appears, the app has two copies of itself +connected to Slack and the second one is in a restart loop. Run +`heroku ps:scale web=0 --app `. The worker's own logs will not reveal this: +they look healthy either way. + +**Two connections right after a first deploy are expected.** For Bolt for +JavaScript, Heroku starts a `web` dyno with the first release, before the deploy +script scales it to 0. The worker's first log line can show `num_connections: 2` +while that `web` dyno shuts down. If `heroku ps` lists only the worker, there is +one copy running. + +**If the chosen plan's documentation mentions dynos sleeping**, leave the app idle +for longer than the stated period, then message it. A sleeping dyno drops the +websocket and the app goes quiet in Slack. + +## Tearing down + +Read the app name from the `heroku` git remote, then destroy the app. +`--confirm` takes the same name and skips the confirmation prompt, and the command +also removes the `heroku` git remote: + +```sh +git remote get-url heroku # https://git.heroku.com/.git +heroku apps:destroy --app --confirm +``` diff --git a/.claude/skills/deploy-slack-app/references/railway.md b/.claude/skills/deploy-slack-app/references/railway.md new file mode 100644 index 0000000..a5eb1a7 --- /dev/null +++ b/.claude/skills/deploy-slack-app/references/railway.md @@ -0,0 +1,96 @@ +# Railway + +Railway runs the app as a long-lived service built from the uploaded working +directory. It suits a Socket Mode app well: the service binds no HTTP port, and +Railway does not require one. + +The deploy script for this provider is `deploy-railway.sh`, alongside this file. +Copy it to `.slack/deploy-railway.sh` as described in the parent skill's Step 4. + +**Cost.** Current pricing is at . Point the developer +there rather than quoting or fetching it. Railway bills by resource usage, so a +long-running service costs something for every hour it is up. + +--- + +## Install and authenticate + +```sh +brew install railway # macOS; see https://docs.railway.com/guides/cli +railway whoami # confirms the CLI is authenticated +``` + +If `railway whoami` fails, ask the developer to run `railway login` in their own +terminal. It opens a browser, so it cannot complete inside an agent session. For +a headless setup, export `RAILWAY_API_TOKEN` with an account token. A +project-scoped `RAILWAY_TOKEN` cannot create projects, so it is not enough for a +first deploy. + +--- + +## What Railway needs from the project + +No `Procfile`, `Dockerfile`, or config file. Railway's builder detects the +language and picks a start command, so check that it will pick the right one: + +- **Bolt for JavaScript:** it runs `npm start`, so `package.json` needs a + `scripts.start` entry that starts the app. +- **Bolt for Python:** it runs the first of `main.py`, `app.py`, `start.py`, or + `bot.py` that exists. The Bolt templates use `app.py`, which works unless a + `main.py` is also present. For any other entrypoint, set a start command in a + `railway.json` file (see ). + +--- + +## Environment variables + +- `RAILWAY_PROJECT_NAME` (optional): the Railway project name. Defaults to the + project directory name. +- `RAILWAY_SERVICE_NAME` (optional): the Railway service name. Defaults to the + project directory name. +- `RAILWAY_WORKSPACE` (optional, sometimes required): the workspace to create the + project in. Required when the account belongs to more than one workspace, + because `railway init` otherwise prompts, and the prompt fails in a deploy + hook. `railway whoami --json` lists the account's workspaces. If there is more + than one, ask the developer which to use. + +Pass them on the deploy command, as shown in the parent skill's Step 5. + +--- + +## Verifying + +```sh +railway service status --service # deployment state +railway logs --service --lines 100 # look for the Socket Mode connection +railway logs --build --service --lines 100 # build output, if the build failed +``` + +Always pass `--lines`. Without it `railway logs` streams until it is stopped, +which hangs an agent session. + +**Two connections right after a re-deploy are expected.** Railway starts the new +deployment before removing the old one, so the new one's logs can show +`"num_connections":2` for a moment. `railway deployment list --service ` +should then show the new deployment as `SUCCESS` and the old one as `REMOVED`. +If two deployments stay `SUCCESS`, two copies of the app are connected to Slack. + +Expect the build to take a few minutes on the first deploy. Railway injects a +`PORT` variable even when nothing listens on it, which is harmless for a Socket +Mode app. + +## Tearing down + +Read the project name from `railway status`, then delete the project and unlink +the directory: + +```sh +railway status # shows the linked project +railway delete --project --yes +railway unlink --yes +``` + +Railway stops the service right away but schedules the project's removal for +later, so the project stays in `railway list` for a while. `railway list --json` +shows the scheduled date as `deletedAt`. The project being listed does not mean +the delete failed. diff --git a/.claude/skills/slack-api/SKILL.md b/.claude/skills/slack-api/SKILL.md new file mode 100644 index 0000000..32eafbf --- /dev/null +++ b/.claude/skills/slack-api/SKILL.md @@ -0,0 +1,207 @@ +--- +name: slack-api +description: "Use when a developer asks which Slack Web API method does something, needs a method's OAuth scopes or token type, wants to call or test a family.method endpoint (chat.postMessage, conversations.history, users.info, views.open), is handling cursor pagination (next_cursor) or rate limits (tier/ratelimited/Retry-After), or is debugging errors like missing_scope, invalid_auth, or channel_not_found. Also trigger on a pasted slack.com/api/ URL or docs.slack.dev/reference/methods link." +argument-hint: "[method.name | family]" +--- + +# Slack Web API + +Help the developer **discover** the right Web API method, **read its contract**, and **call** it correctly. Slack exposes hundreds of methods named in `family.method` dot notation (e.g. `chat.postMessage`, `conversations.history`) at `https://slack.com/api/`. Every method's doc page follows a fixed URL pattern, so the contract for any method is always one fetch away. + +If `$0` is provided, it is either a full `method.name` (jump to Step 2 to read its contract) or a `family` name (go to Step 1 and find it in the index). + +> **Critical rules:** +> +> - Verify a method name and its required scopes against its doc page **before** calling it — never invent method names or guess scopes. Method names use `family.method` dot notation. +> - Every response has a top-level `ok` boolean. **Always check `ok`** before using the result; on `ok: false`, read the `error` string. +> - Method names, scopes, rate tiers, and arguments come from the **live doc page** (`https://docs.slack.dev/reference/methods/.md`). The docs are the source of truth — discover from the live index, read the contract from the method's own page. + +> **DO NOT rules:** +> +> - DO NOT assume a method is GET — many are POST. Check the doc page. +> - DO NOT hardcode bearer tokens into committed code or share them in plain text. +> - DO NOT use deprecated methods (`files.upload`, `dialog.open`, `rtm.*`, `oauth.access`, `search.*`, `stars.*`, `reminders.*`) without checking the replacement — a deprecated method's own doc page names what supersedes it; prefer the replacement for new apps. +> - DO NOT paginate by incrementing a page number — Slack uses opaque cursors (see Step 5). + +> **Execution posture — run reads, confirm writes:** +> +> - **Read-only methods** (`*.list`, `*.info`, `*.history`, `conversations.members`, `auth.test`, etc.) may be run directly to help the developer. +> - **State-changing or destructive methods** (`chat.postMessage`/`update`/`delete`, any `*.delete`/`*.remove`/`*.kick`/`*.archive`, and all `admin.*`) — prepare the exact command and **confirm with the developer before running it**. + +--- + +## Fast Path (for clear, specific requests) + +If the developer already knows the method — they named it, pasted a `https://slack.com/api/` URL or a `docs.slack.dev/reference/methods/` link, or gave a `family.method` — skip discovery: + +1. Go to **Step 2** to read the method's contract. +2. Go to **Step 4** to call it (honoring the execution posture above). + +**Full-workflow indicators** (start at Step 1): + +- "Which method does X?" / "How do I list/fetch/post … via the API?" +- The capability is known but the method name is not. +- Exploratory questions about what the API can do. + +--- + +## Step 1: Identify the Method (Discover) + +Map the developer's intent to a family, then to a candidate method. + +### Browsing the index + +WebFetch the live method index: + +```text +https://docs.slack.dev/reference/methods.md +``` + +It lists every Web API method in `family.method` notation with a one-line description and a link to that method's own doc page. It is complete and always current — scan it for a candidate, then follow the method's link into Step 2 to read the contract (the index has descriptions only; rate tier, scopes, token type, and pagination all live on the per-method page). + +Never publish or call a method name you have not seen on a live page. + +### Searching the docs + +When you would rather search by keyword than scan the index, and the Slack CLI is available, use the `slack-cli` skill — **Step 3: Searching Documentation (`slack docs search`)** — to query Slack's docs from the terminal. That step covers the command and flags; results will point you to the method's reference page, which you then read in Step 2. Without the CLI, WebFetch the index (`https://docs.slack.dev/reference/methods.md`) and scan it instead. + +--- + +## Step 2: Read the Method Contract (Navigate) + +Fetch the method's doc page with WebFetch. Either follow the method's link from the index (Step 1) or construct the URL — the path segment is **all-lowercase** and ends in `.md`: + +```text +https://docs.slack.dev/reference/methods/.md +``` + +For example, `conversations.members` → `https://docs.slack.dev/reference/methods/conversations.members.md`, and `chat.postMessage` → `https://docs.slack.dev/reference/methods/chat.postmessage.md`. When in doubt about casing, follow the index link rather than building the URL by hand. + +Every method page documents, consistently: + +- **HTTP method** (GET / POST) and the endpoint `https://slack.com/api/` +- **Required OAuth scopes** and the **token type** (bot `xoxb-` vs user `xoxp-`) +- **Arguments** — required vs optional, with types +- An **example request and response** +- An **errors table** (method-specific codes) +- The **rate-limit tier** + +Extract the **required arguments** and **required scopes** before calling. For what these cross-cutting concepts _mean_ in general — beyond what the method page states — the canonical references are: the response envelope, POST bodies, and auth at `https://docs.slack.dev/apis/web-api.md`; pagination at `https://docs.slack.dev/apis/web-api/pagination.md`; and rate-limit tiers at `https://docs.slack.dev/apis/web-api/rate-limits.md`. + +--- + +## Step 3: Authenticate and Scope + +Calling any non-public method requires a token with the right scopes and type. This skill's job here is to determine, from the contract you read in Step 2, **which token type and scopes** the method needs — independent of how you ultimately send the token. + +From the contract you read in Step 2: + +- Confirm the **token type** — a bot token cannot call a user-only method (the method's doc page states which token types it accepts), and vice versa. For what each token prefix (`xoxb-`, `xoxp-`, `xapp-`) is and when to use it, see `https://docs.slack.dev/authentication/tokens.md`. +- Note the **required scopes**. If a call later fails with `missing_scope`, the response's `needed` and `provided` fields name the gap — add the `needed` scope to the app manifest and reinstall the app. +- `admin.*` methods require an Enterprise Grid **org-level** token. + +A couple of methods need no auth: `api.test` (connectivity), `auth.test` (validates whatever token you do send) and `blocks.validate`. + +You need a token only when the method requires one. There are two ways to get one — pick whichever fits the developer's setup. **The Slack CLI is optional**: if the developer does not have it and prefers not to install it, take Path B rather than forcing an install. + +### Path A: Use the Slack CLI (if installed or wanted) + +The CLI supplies an authenticated session, so once the developer is logged in you can call methods without handling a token yourself (Step 4, "Via the Slack CLI"). + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public Slack CLI is installed and resolve its command name. Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. That step also proposes installing the CLI when it is absent. The fingerprint check, alias fallback, and install instructions all live there; do not duplicate them here. + +Once resolved, use the detected command name for **all** CLI commands in this skill. We refer to it as `SLACK_CMD` — substitute the actual resolved command name everywhere you see `SLACK_CMD`. + +Use the `slack-cli` skill — **Step 5: Authentication (`slack auth`)** — to check the developer's login state and, if needed, walk them through `slack login`. Authentication mechanics live there. + +### Path B: No CLI — bring your own token + +You do not need the CLI to call a method. Get a token of the type you determined above from the app's **OAuth & Permissions** page in the Slack app config (`https://api.slack.com/apps` → your app → **OAuth & Permissions** → **OAuth Tokens**): the **Bot User OAuth Token** (`xoxb-…`) or the **User OAuth Token** (`xoxp-…`). That page also lists the scopes currently granted — confirm the ones from Step 2 are present. Then send that token with curl or an SDK in Step 4 ("Via raw HTTP" / "Via an SDK"). + +--- + +## Step 4: Call the Method (Manage) + +First apply the **execution posture**: if the method changes state (post/update/delete/archive/kick, or any `admin.*`), show the developer the exact command and get a yes before running it. Read-only calls can be run directly. + +### Via the Slack CLI (if installed) + +To call a method from the terminal, use the `slack-cli` skill — **Step 4: Calling Web API Methods (`slack api`)**. That step covers the `SLACK_CMD api key=value …` syntax so that it is not repeated here. Pass the required arguments you gathered from the method's doc page in Step 2. + +The CLI uses the developer's authenticated session, so it is the simplest path once they are logged in (Step 3). + +### Via raw HTTP (curl) + +Use the **Bash tool** when the developer wants a raw request or isn't using the CLI. Send the token in the `Authorization` header — the bot or user token from Step 3 (Path B, or the CLI session). + +**Form-encoded** (the default for most methods): + +```bash +curl -s -X POST 'https://slack.com/api/conversations.list' \ + -H 'Authorization: Bearer xoxb-YOUR-TOKEN' \ + -d 'types=public_channel&limit=200' +``` + +**JSON body** (for methods taking complex arguments like `blocks`, `view`, `attachments`, `metadata`): + +```bash +curl -s -X POST 'https://slack.com/api/chat.postMessage' \ + -H 'Authorization: Bearer xoxb-YOUR-TOKEN' \ + -H 'Content-Type: application/json' \ + -d '{"channel":"C0123456789","text":"Hello from the API"}' +``` + +Check the method's page for which content type it expects. With form encoding, a structured argument is passed as a JSON-encoded string value (e.g. `blocks=[...]`). + +### Via an SDK + +In Bolt and the Slack SDKs, each method is a client function whose arguments match the doc page's argument table: + +- **JavaScript:** `await client.chat.postMessage({ channel, text, blocks })` +- **Python:** `client.chat_postMessage(channel=channel, text=text, blocks=blocks)` + +(Note the JS dot form `chat.postMessage` vs the Python underscore form `chat_postMessage`.) To construct the `blocks`/`view` payload these calls take, use the `block-kit` skill — this skill treats that payload as an opaque argument and focuses on the method call around it. + +--- + +## Step 5: Handle Pagination + +Methods that return collections use **cursor pagination**, not page numbers. A method's doc page states whether it paginates, and the full list of cursor-paginated methods is under _Methods supporting cursor-based pagination_ at `https://docs.slack.dev/apis/web-api/pagination.md`: + +1. Call with a `limit` (page size — check the method's max). +2. Read `response_metadata.next_cursor` from the response. +3. If it is **non-empty**, call again with `cursor=`. +4. Repeat until `next_cursor` comes back empty. + +```bash +# First page +curl -s -X POST 'https://slack.com/api/conversations.history' \ + -H 'Authorization: Bearer xoxb-YOUR-TOKEN' \ + -d 'channel=C0123456789&limit=200' + +# Next page — pass the cursor from response_metadata.next_cursor +curl -s -X POST 'https://slack.com/api/conversations.history' \ + -H 'Authorization: Bearer xoxb-YOUR-TOKEN' \ + -d 'channel=C0123456789&limit=200&cursor=dXNlcjpVMDYxTkZUVDI=' +``` + +Cursors are opaque — never construct, parse, or reuse an old one. + +--- + +## Step 6: Handle Rate Limits and Errors + +When `ok` is `false`, branch on the `error` string: + +- For method-specific codes, read the **errors table** on the method's doc page (Step 2) — it lists every error that method returns, including cross-cutting ones like `not_authed`, `invalid_auth`, `missing_scope`, `channel_not_found`, and `invalid_arguments`. +- For what the envelope itself means (`ok`, `error`, `warning`, `response_metadata`), see _Evaluating responses_ at `https://docs.slack.dev/apis/web-api.md`. +- `response_metadata.messages` often pinpoints a malformed argument. + +**Rate limits:** on HTTP `429` / `error: "ratelimited"`, honor the `Retry-After` response header (seconds) — wait, then retry. Do not retry in a tight loop. Each method's tier (1–4 or special) caps calls per minute; the tier table is at `https://docs.slack.dev/apis/web-api/rate-limits.md`, and newer non-Marketplace apps face stricter caps on some methods, so trust the method's own page for the exact number. + +--- + +## Notes + +- **Slack Lists** methods use the `slackLists.*` prefix — a bare `lists.*` name does not exist. +- **Scope:** this skill owns the method layer — which method, its contract, and the call around it. CLI auth and calls are delegated to the `slack-cli` skill; Block Kit payloads to the `block-kit` skill. diff --git a/.claude/skills/slack-cli/SKILL.md b/.claude/skills/slack-cli/SKILL.md new file mode 100644 index 0000000..47d857f --- /dev/null +++ b/.claude/skills/slack-cli/SKILL.md @@ -0,0 +1,253 @@ +--- +name: slack-cli +description: "Use when a developer works with the Slack CLI (slack command) to create, run, or manage a Slack app from the terminal: logging in or authenticating (slack login), adding a team or switching workspaces, running locally (slack run), deploying, editing the app manifest, calling Web API methods (slack api), or searching Slack docs (slack docs search)." +--- + +# Slack CLI + +Use the Slack CLI to create, run, and manage Slack apps — including calling Web API methods directly and searching Slack developer documentation from the terminal. + +For initial setup (sandbox creation, project scaffolding from templates), use the `create-slack-app` skill instead. + +--- + +## Step 1: Detect the Slack CLI + +Resolve the path to the **public** Slack CLI before running any other command. We refer to the resolved value as `SLACK_CMD` — substitute it everywhere below. **Try 1a → 1b → 1c in order; do not skip ahead.** + +### 1a. Standard install path (preferred — no verification needed) + +The official install scripts place the binary at a fixed per-user path. If the file exists, use it directly: only the install script writes to that path. + +- macOS / Linux: `~/.slack/bin/slack` +- Windows: `%USERPROFILE%\AppData\Local\slack-cli\bin\slack.exe` (or `%USERPROFILE%\.slack-cli\bin\slack.exe` as a fallback) + +POSIX shell: + +```bash +[ -x "$HOME/.slack/bin/slack" ] && echo "$HOME/.slack/bin/slack" +``` + +PowerShell: + +```powershell +$p = "$env:USERPROFILE\AppData\Local\slack-cli\bin\slack.exe" +if (Test-Path $p) { $p } elseif (Test-Path "$env:USERPROFILE\.slack-cli\bin\slack.exe") { "$env:USERPROFILE\.slack-cli\bin\slack.exe" } +``` + +If a path is returned, set `SLACK_CMD` to that **absolute path** and proceed to Step 2. Do not also run `_fingerprint`. + +### 1b. `slack` on PATH (verify with fingerprint) + +If 1a found nothing, try `slack` on PATH: + +```bash +slack _fingerprint 2>/dev/null +``` + +If it outputs `d41d8cd98f00b204e9800998ecf8427e`, set `SLACK_CMD=slack` and proceed. + +### 1c. Ask about an alias, or install + +If 1b fails or returns a different value, ask the developer using AskUserQuestion: + +- "The `slack` command on your system doesn't appear to be the public Slack CLI. Do you have it installed under a different name or alias?" +- Options: "Yes, it's aliased as..." (let them provide the alias), "No, I need to install it" +- If they provide an alias, verify it with ` _fingerprint 2>/dev/null` and set `SLACK_CMD=`. +- If they need to install it, run: + + ```text + curl -fsSL https://downloads.slack-edge.com/slack-cli/install.sh | bash + ``` + + Then re-run **1a** — the install script will have written `~/.slack/bin/slack`. + +**Common mistakes:** Don't use `which slack` to discover the binary — `which` resolves any shell alias and defeats the point of 1a. In Git Bash on Windows, use the POSIX probe form, not PowerShell. + +--- + +## Step 2: Command Discovery via Help + +**Always run `SLACK_CMD --help` before constructing a command you have not used in the current session.** Do not guess at flags — the help output is the source of truth. + +- `SLACK_CMD help` — lists all available command groups +- `SLACK_CMD --help` — shows subcommands, flags, and usage examples + +If a command or flag in this skill is missing from the help output, the installed CLI is older than this skill. Ask the developer to run `SLACK_CMD upgrade`, then check the help output again. + +### Resolving `--app` and `--team` values + +When a command requires `--app` or `--team`: + +- **App ID**: Run `SLACK_CMD app list` from the project directory to see installed apps and their IDs. +- **Team ID**: Run `SLACK_CMD auth list` to see authenticated workspaces and their team IDs. + +--- + +## Step 3: Searching Documentation (`slack docs search`) + +Search Slack's developer documentation directly from the terminal. + +```bash +SLACK_CMD docs search "" --output=text --limit=5 +``` + +Use `--output=text` for concise terminal-readable results. Use this when you are already running CLI commands and want to: + +- Check a Slack feature before implementing it +- Verify API behavior or required scopes +- Look up Block Kit elements, event types, or method parameters + +--- + +## Step 4: Calling Web API Methods (`slack api`) + +Call any Slack Web API method directly. Run `SLACK_CMD api --help` for full details and examples. + +Parameters are passed as positional `key=value` pairs (NOT `--key=value` flags): + +```bash +SLACK_CMD api chat.postMessage channel=C0123456789 text="Hello from the CLI" +``` + +**Important distinction**: `--team`, `--token`, `--json`, and `--data` are meta-flags (prefixed with `--`). API method parameters use positional `key=value` syntax without dashes. + +**Reference**: Full method list at . + +--- + +## Step 5: Authentication (`slack auth`) + +### When to run this flow + +Slack auth is **per-team**, not a single boolean. Run the seamless login flow below whenever any of these is true: + +- The developer is not authenticated to any team yet. +- The developer wants to **add a new team / workspace / sandbox**, even if `SLACK_CMD auth list` already shows other teams. +- The developer asks to log in, switch teams, or re-authenticate. + +`SLACK_CMD auth list` showing other teams is **not** a reason to skip login — those are different teams. Ask the developer which team they want, then run the flow. + +The flow below is the same for every kind of workspace. `/slackauthticket` works in any workspace the developer belongs to, whether that is a developer sandbox, a Free Team, or a production workspace, so there is no sandbox-specific login. Which target to prefer is the `create-slack-app` skill's call (**Step 3: Choose Where to Install the App**). + +### Inspect existing auth (optional) + +```bash +SLACK_CMD auth list +``` + +Use this to show the developer which teams are already authenticated, or to confirm a successful login. Do not treat a non-empty list as "auth complete" when the developer asked to log in to a new team. + +### Run the seamless login flow + +The agent drives this end-to-end — **no separate terminal window, no browser confirmation**. + +`SLACK_CMD login --no-prompt` makes the CLI emit a single-use ticket and exit immediately instead of waiting on stdin. Slack itself renders the challenge code **inside a workspace modal** when the developer sends the `/slackauthticket` slash command — there is no browser step. The agent submits the challenge back to the CLI to complete login. + +**1. Start login and capture the ticket** + +```bash +SLACK_CMD login --no-prompt +``` + +The CLI prints a `/slackauthticket ` slash command and exits. Capture the ticket — you will need it in step 4. Sample output: + +```text +📋 Run the following slash command from any Slack channel in the workspace + you'd like to authenticate + + /slackauthticket eyJ0eXAiOiJKV1QiLCJh… + +? Slack will then show you a challenge code. Submit it via: + slack login --ticket --challenge +``` + +**2. Hand the slash command to the developer** + +Show the full `/slackauthticket …` line and ask the developer to paste it into the message box of the Slack workspace they want to authenticate, then send it. Slack responds with a modal containing a short challenge code (e.g. `JDt1IK7X`). + +**3. Collect the challenge code** + +Use `AskUserQuestion` to ask the developer for the challenge code shown in the Slack modal. Wait for their answer — do not guess or default. + +**4. Complete login** + +```bash +SLACK_CMD login --ticket --challenge +``` + +On success the CLI returns the team name and ID. Verify with `SLACK_CMD auth list` and report the team back to the developer. + +**Troubleshooting**: tickets are single-use and time-limited. If step 4 fails with an invalid/expired ticket or wrong challenge, restart from step 1 with a fresh `SLACK_CMD login --no-prompt` — do not retry the same ticket. + +Use `--team ` on individual commands to target a specific workspace without switching globally. + +### Red flags — STOP + +If you catch yourself thinking any of these, you are about to regress to the old broken flow: + +| Rationalization | Reality | +|---|---| +| "`auth list` already shows teams, so login isn't needed." | Auth is per-team. The developer asked for a _new_ team — drive the flow. | +| "`slack login` needs browser confirmation, so I can't drive it." | False with `--no-prompt`. The challenge code appears in Slack's modal, not a browser. The agent runs both `slack login` invocations itself. | +| "I should tell the developer to run `slack login` in a separate terminal." | Never. Step 5 is the agent's job from start to finish. | + +**All of these mean: run `SLACK_CMD login --no-prompt` yourself and follow the four numbered steps above.** + +--- + +## Step 6: Running an App Locally (`slack run`) + +Run `SLACK_CMD run --help` for all available flags. + +### Resolve the app or team target + +Run `SLACK_CMD app list` from the project directory to check for installed apps: + +- **If an app exists**: Use `--app=` in the run command. +- **If no apps are listed**: Use `--team=` instead (get the team ID from `SLACK_CMD auth list`). + +### Start the dev server in the background + +Run this command as a **background process** so the developer can continue working: + +**If an app ID was found:** + +```bash +cd && SLACK_CMD run --org-workspace-grant=all --app= +``` + +**If no apps — use the team ID:** + +```bash +cd && SLACK_CMD run --org-workspace-grant=all --team= +``` + +Tell the developer the app is running in the background. They can ask: + +- "What's the status of the dev server?" — to check on it +- "Show me the output from slack run" — to see activity logs +- "Stop the dev server" — to terminate the process + +--- + +## Step 7: Managing the Manifest + +Run `SLACK_CMD manifest --help` for subcommands (`validate`, `info`) and the `--source local|remote` flag. + +Use `SLACK_CMD manifest validate` before deploying or when something seems wrong with the app configuration. + +--- + +## Step 8: Other Commands + +For any other command group (e.g., `trigger`, `datastore`, `env`, `collaborator`, `external-auth`, `deploy`), run `SLACK_CMD --help` to discover subcommands and flags. Run `SLACK_CMD help` to see all available command groups. + +--- + +## Notes + +- `SLACK_CMD` is a placeholder — always substitute the actual command name resolved in Step 1. +- **Always run `--help`** before constructing a command you have not used in the current session. +- Interactive commands (e.g., `slack trigger create` without `--trigger-def`) cannot be run in the background. Tell the developer to run these in a **new terminal window**. `slack login` is **not** in this category — drive it inline using the `--no-prompt` / `--ticket` / `--challenge` flow in Step 5. +- `slack run` runs locally for development. `slack deploy` deploys to Slack's hosted infrastructure, unless `.slack/hooks.json` defines a `deploy` hook, in which case it runs that hook instead (see the `deploy-slack-app` skill). These are different operations, so do not confuse them. diff --git a/.claude/skills/slack-docs/SKILL.md b/.claude/skills/slack-docs/SKILL.md new file mode 100644 index 0000000..2b79ecb --- /dev/null +++ b/.claude/skills/slack-docs/SKILL.md @@ -0,0 +1,145 @@ +--- +name: slack-docs +description: "Use when answering a conceptual or how-to question about Slack platform features, or when asked to look up, fetch, or summarize a docs.slack.dev page, including a pasted docs.slack.dev link. Covers finding and reading official Slack docs as clean markdown." +argument-hint: "[topic or docs.slack.dev URL]" +--- + +# Slack Platform Documentation + +Help the developer **find** the right page on the official Slack documentation site (`https://docs.slack.dev`) and **read** it as clean markdown, so answers come from the live docs rather than memory. The site exposes three machine-readable surfaces an agent can use directly, with no authentication and no Slack workspace: + +- A **search API method**: `GET https://docs.slack.dev/api/v1/search?query=&category=&pin=false` returns ranked page hits as JSON. Scope every search with a `category` (guides, reference, a specific SDK, etc.); an uncategorized search skews heavily toward SDK pages. Always pass `pin=false`, which stops the API from putting this plugin's own page first for searches about coding agents; you already have the plugin. +- **Per-page markdown**: every page is available at its URL **+ `.md`** (e.g. `/quickstart.md`). +- **Index files**: `/llms.txt` (a curated overview) and `/llms-sitemap.md` (a list of every markdown page). + +If `$0` is provided, it is either a `docs.slack.dev` URL (jump to the **Fast Path**) or a topic to search (start at **Step 1**). For a broad "how do I build X on Slack?" question rather than one specific page, read `https://docs.slack.dev/llms.txt` first; it is a curated, LLM-oriented overview of the platform and the recommended build path. + +> **Critical rules:** +> +> - The docs are the **source of truth**. Do not answer a factual question about the Slack platform from memory; discover the page, fetch it, then answer from what it says. +> - Prefer the **`.md` version** of any page over the HTML version. It is cleaner for reading and quoting. +> - Every fetched markdown page begins with a `Source: ` line. Keep that URL so you can cite the page back to the developer. + +> **DO NOT rules:** +> +> - DO NOT invent documentation URLs. Get them from the search API, the sitemap, or a link the developer gave you then verify by fetching. +> - DO NOT paraphrase a page you have not actually fetched. If a fetch fails, say so rather than filling the gap from memory. +> - DO NOT assume every URL has a `.md` version. If a fetch returns an error, fall back to the search API or the sitemap (Step 1) rather than guessing another URL. + +--- + +## Fast Path (the developer already has a URL) + +If the developer pasted a `https://docs.slack.dev/...` link, skip discovery and go straight to **Step 2** to fetch and read it. + +--- + +## Step 1: Discover the Page (search) + +**If the Slack CLI is installed, search from the terminal.** Load the `slack-cli` skill (with your skill tool, if you have one) and follow **1a** and **1b** of its **Step 1: Detect the Slack CLI** to check whether the public CLI is installed and resolve its command (`SLACK_CMD`). Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. Stop there: don't ask the developer about an alias or offer to install the CLI just to search the docs. If neither finds it, use the search API below. + +```bash +SLACK_CMD docs search '' --category= --limit=5 --hide-pinned +``` + +Keep the query in single quotes, so the shell doesn't run anything inside it, and leave any `'` out of the query (`whats socket mode`). Search ignores punctuation. It calls the same search API and takes the same categories as below. On a current CLI, each result links to the page's `.md` version, ready for **Step 2**. An older CLI returns the page URL, which Step 2 turns into its `.md` version. `--hide-pinned` leaves out the Slack MCP and Skills Plugin page that the API pins to the top of searches about coding agents. You already have the plugin. + +Check `SLACK_CMD docs search --help` first. If `search` or its `--category` flag is missing, use the search API below. If only `--hide-pinned` is missing, the CLI is older than this skill: search without it and skip the plugin page (`https://docs.slack.dev/ai/slack-skills-plugin/`) if it comes first. Suggest `SLACK_CMD upgrade` once, as the `slack-cli` skill's **Step 2: Command Discovery via Help** does for a missing command or flag. + +**Otherwise, use the search API.** WebFetch this URL, with the query URL-encoded and a `category` to scope the results: + +```text +https://docs.slack.dev/api/v1/search?query=&category=&limit=5&pin=false +``` + +**Always start with a `category`.** An uncategorized search is dominated by SDK reference pages (a query like `socket mode` or `oauth` can return a top 10 that is entirely Bolt/Node pages), which buries the conceptual and reference content most questions are actually about. Pick the starting category from the developer's intent: + +- **`guides`** — the default for "how do I…", "what is…", and conceptual platform questions (Events API, OAuth, Socket Mode, manifests, modals, App Home). Start here when in doubt. +- **`reference`** — for a specific method, event, scope, object, or Block Kit element, especially an exact name like `chat.postMessage`. +- **A tool/SDK category** (`python`, `javascript`, `java`, `slack_cli`, `slack_github_action`, `deno_slack_sdk`) — only once you know the developer's tool. See **Step 3**. + +So `socket mode` as a concept → `https://docs.slack.dev/api/v1/search?query=socket%20mode&category=guides&limit=5&pin=false`. + +The response is JSON: + +```json +{ + "total_results": 12, + "results": [ + { "url": "/apis/events-api/using-socket-mode", "title": "Using Socket Mode" } + ], + "limit": 5 +} +``` + +Scan `results` for the best `title`/`url` match, then read it in **Step 2**. A query is **required**; calling the endpoint with no `query` returns a `400` with an `error` field. + +Full set of categories: + +| Category | Scopes results to | +|----------|-------------------| +| `guides` | Conceptual and how-to guides | +| `reference` | API reference: methods, events, scopes, objects, Block Kit | +| `changelog` | Changelog and release notes | +| `python` | Python tools (Bolt for Python, Python Slack SDK) | +| `javascript` | JavaScript tools (Bolt for JS, Node Slack SDK) | +| `java` | Java tools (Bolt for Java, Java Slack SDK) | +| `slack_cli` | Slack CLI docs | +| `slack_github_action` | Slack Send GitHub Action docs | +| `deno_slack_sdk` | Deno Slack SDK docs | + +If a categorized search returns no good hit, widen it: try the other likely category (`guides` ⇄ `reference`), then drop `category` entirely as a last resort. An unrecognized value returns a `400` with an `error` field listing the valid categories, so re-run with one of those or with no category. + +**Fallbacks** when search does not surface a good hit, or returns a `500`/temporary error (the endpoint is rate-limited and cached ~5 minutes): + +- WebFetch `https://docs.slack.dev/llms-sitemap.md`, a flat list of every documentation page's `.md` URL, and scan it for the relevant path. +- For API reference lookups, the enriched index pages are often faster: `https://docs.slack.dev/reference/methods.md`, `.../events.md`, `.../scopes.md`, `.../objects.md`, and `.../block-kit.md` each list every item with a one-line description and a `.md` link. + +--- + +## Step 2: Read the Page (fetch markdown) + +Given a page reference (a `url` from Step 1, or a link the developer pasted), read its markdown. + +**If the Slack CLI is installed, print the page from the terminal.** Use the `SLACK_CMD` from Step 1. When you came here from the Fast Path with a pasted link, resolve it the same way first, with **1a** and **1b** of the `slack-cli` skill's **Step 1: Detect the Slack CLI**. + +```bash +SLACK_CMD docs get '' +``` + +It accepts a link from `SLACK_CMD docs search`, a pasted docs.slack.dev URL, or a site path, with or without `.md` or an `#anchor`, and prints the page's markdown. If `SLACK_CMD docs --help` doesn't list `get`, the CLI is older than this skill: suggest `SLACK_CMD upgrade` once and fetch the page as below. + +Generated SDK reference pages end in `.html` and have no markdown version, so `docs get` reports that and appending `.md` fails too. WebFetch a `.html` link as it is. + +**Otherwise, fetch the markdown:** + +1. Normalize the reference to its `.md` URL: + - A site-relative path from Step 1 (e.g. `/apis/events-api/using-socket-mode`): prepend `https://docs.slack.dev`. + - A full URL the developer pasted, or a link from `SLACK_CMD docs search`: drop any `#anchor` first. + - Unless it already ends in `.md`, drop a trailing `/`, then append `.md`, e.g. `…/using-socket-mode/` → `https://docs.slack.dev/apis/events-api/using-socket-mode.md`. Keeping the slash (`…/using-socket-mode/.md`) returns a 404. + The server lowercases `.md` requests, so casing does not matter: `chat.postMessage.md` and `chat.postmessage.md` both resolve. +2. **WebFetch** it. The page opens with `Source: `; the rest is the page body in markdown. +3. Answer the developer from the fetched content, and cite the `Source` URL. + +If a page is long and the developer asked something narrow, fetch it and quote only the relevant section rather than dumping the whole page. + +--- + +## Step 3: Tool and SDK Documentation + +Implementation details differ significantly between the official tools, so **establish which one the developer is using first**, then scope your reading to that tool's doc subtree. Each lives under `https://docs.slack.dev/tools/` and its pages are fetchable as `.md` like any other (e.g. `https://docs.slack.dev/tools/bolt-js/concepts.md`). If the developer has not said, ask before assuming. + +| Tool | Docs path | Search `category` | Use when the developer… | +|------|-----------|-------------------|--------------------------| +| **Slack CLI** | `/tools/slack-cli` | `slack_cli` | scaffolds, runs, or manages an app from the terminal; mentions `slack` commands or app manifests | +| **Bolt for JavaScript** | `/tools/bolt-js` | `javascript` | builds an app in Node/TypeScript with the Bolt framework | +| **Bolt for Python** | `/tools/bolt-python` | `python` | builds an app in Python with the Bolt framework | +| **Bolt for Java** | `/tools/java-slack-sdk` | `java` | builds an app in Java with Bolt (Bolt for Java lives in the Java SDK docs) | +| **Node Slack SDK** | `/tools/node-slack-sdk` | `javascript` | wants lower-level Node clients (`@slack/web-api`, `@slack/socket-mode`) without the full Bolt framework | +| **Python Slack SDK** | `/tools/python-slack-sdk` | `python` | wants the lower-level Python client without Bolt | +| **Java Slack SDK** | `/tools/java-slack-sdk` | `java` | wants Java clients, or is using Bolt for Java | +| **Slack Send GitHub Action** | `/tools/slack-github-action` | `slack_github_action` | sends data to Slack from a GitHub Actions workflow | + +Once you know the tool, narrow discovery with the matching `category` from Step 1, e.g. `…?query=middleware&category=javascript`. Note the languages group: both Bolt for JavaScript and the Node Slack SDK fall under `javascript` (likewise `python` and `java` each cover their Bolt framework plus lower-level SDK), so the category scopes to the language family, not a single subtree. + +**Bolt** is the framework built upon the matching language **SDK**. When unsure which subtree a topic lives in, fall back to the search API (Step 1) as it indexes all of these. diff --git a/.claude/skills/slack-messaging/SKILL.md b/.claude/skills/slack-messaging/SKILL.md new file mode 100644 index 0000000..71ee92e --- /dev/null +++ b/.claude/skills/slack-messaging/SKILL.md @@ -0,0 +1,84 @@ +--- +name: slack-messaging +description: "Use when writing, drafting, scheduling, or improving a Slack message, announcement, or reply sent via the Slack MCP tools (slack_send_message, slack_send_message_draft, slack_schedule_message). Covers Slack markdown formatting, message structure, thread etiquette, reactions, and scheduling, and points to the right dialect for canvases and Block Kit." +--- + +# Slack Messaging Best Practices + +This skill provides guidance for composing well-formatted, effective Slack messages. + +## When to Use + +Apply this skill whenever composing, drafting, or helping the user write a Slack message, including when using `slack_send_message`, `slack_send_message_draft`, or `slack_schedule_message`. The formatting rules below cover these message tools. `slack_create_canvas` uses a different, richer markdown dialect — see the Canvas note below. + +## Formatting + +The message tools (`slack_send_message`, `slack_send_message_draft`, `slack_schedule_message`) accept **standard markdown** and convert it to Slack formatting on send. Write normal markdown. Do **not** use Slack's legacy `mrkdwn` syntax (`*bold*`, `~strike~`); those single-character forms mean something different in standard markdown. Each text element is limited to ~5000 characters. + +| Format | Syntax | +| ------------- | ---------------------- | +| Bold | `**text**` | +| Italic | `_text_` (or `*text*`) | +| Strikethrough | `~~text~~` | +| Code (inline) | `` `code` `` | +| Quote | `> text` | +| Link | `[display text](url)` | +| Bulleted list | `- item` | +| Numbered list | `1. item` | + +Block elements also work. Write them as literal markdown: + +- **Code block** with an optional language for syntax highlighting: + + ````text + ```python + print("hello") + ``` + ```` + +- **Table** with `|` delimiters (escape a literal pipe inside a cell as `\|`): + + ```text + | Feature | Status | + |---------|--------| + | Tables | works | + ``` + +- **Headers** with `#` / `##` / `###`: + + ```text + ## Section title + ``` + +The one thing that does **not** embed in a message: inline images (`![alt](url)`) typically render as a plain link rather than an inline image. For rich embedded layouts (buttons, images, structured cards) you need Block Kit; for a document-style surface where images do embed, use a canvas. See the Notes below. + +## Message Structure Guidelines + +- **Lead with the point.** Put the most important information in the first line. Many people read Slack on mobile or in notifications where only the first line shows. +- **Keep it short.** Aim for 1-3 short paragraphs (the ~5000-character limit is a ceiling, not a target). If the message is long or structured, consider a Canvas instead. +- **Use line breaks generously.** Walls of text are hard to read. Separate distinct thoughts with blank lines. +- **Use bullet points for lists.** Anything with 3+ items should be a list, not a run-on sentence. +- **Bold key information.** Use `**bold**` for names, dates, deadlines, and action items so they stand out when scanning. + +## Thread vs. Channel Etiquette + +- **Reply in threads** when responding to a specific message to keep the main channel clean. +- **Use `reply_broadcast`** (also post to channel) only when the reply contains information everyone needs to see. +- **Post in the channel** (not a thread) when starting a new topic, making an announcement, or asking a question to the whole group. +- **Don't start a new thread** to continue an existing conversation; find and reply to the original message. + +## Tone and Audience + +- Match the tone to the channel: `#general` is usually more formal than `#random`. +- For simple acknowledgments, add an emoji reaction with `slack_add_reaction` instead of a reply message (use `slack_get_reactions` to read existing reactions). +- When writing announcements, use a clear structure: context, key info, call to action. + +## Scheduling + +- Use `slack_schedule_message` to post later. `post_at` is a Unix timestamp that must be at least 2 minutes in the future and at most 120 days out; the message body uses the same standard markdown as above. +- Scheduled messages can't be edited via the API once set — the user manages them from **Drafts & sent** in Slack. + +## Notes + +- **Canvas formatting is different.** `slack_create_canvas` uses Canvas-flavored Markdown, a richer dialect than the message tools: headers, tables, checklists, and inline images (`![alt](url)`) all embed, and it also supports user/channel reference cards, callouts, and columns. Do **not** assume the message rules above apply — follow the `slack_create_canvas` tool's own formatting guidance when composing a canvas. +- **Scope:** this skill owns composing and formatting the _text_ of messages sent through the Slack MCP message tools. For interactive layouts (buttons, menus, modals, Home tabs, or any Block Kit JSON), use the `block-kit` skill, which composes and validates the block payload. For calling the Slack Web API directly (`chat.postMessage` and friends) rather than the MCP tools, use the `slack-api` skill. diff --git a/.claude/skills/slack-search/SKILL.md b/.claude/skills/slack-search/SKILL.md new file mode 100644 index 0000000..6015eb9 --- /dev/null +++ b/.claude/skills/slack-search/SKILL.md @@ -0,0 +1,123 @@ +--- +name: slack-search +description: "Use when locating messages, files, channels, or people across Slack, or gathering context before answering, with the search MCP tools (slack_search_public, slack_search_public_and_private, slack_search_channels, slack_search_users). Covers search modifiers (in:, from:, before:), file-type filters, natural-language vs. keyword search, and reading results in context." +--- + +# Slack Search + +This skill provides guidance for effectively searching Slack to find messages, files, and information. + +## When to Use + +Apply this skill whenever you need to find information in Slack, including when a user asks you to locate messages, conversations, files, or people, or when you need to gather context before answering a question about what's happening in Slack. + +## Search Tools Overview + +| Tool | Use When | +| --------------------------------- | ------------------------------------------------------------------------------------ | +| `slack_search_public` | Searching public channels only. Does not require user consent. | +| `slack_search_public_and_private` | Searching all channels including private, DMs, and group DMs. Requires user consent. | +| `slack_search_channels` | Finding channels by name or description. | +| `slack_search_users` | Finding people by name, email, or role. | + +## Search Strategy + +### Start Broad, Then Narrow + +1. Begin with a simple keyword or natural language question. +2. If too many results, add filters (`in:`, `from:`, date ranges). +3. If too few results, remove filters and try synonyms or related terms. + +### Choose the Right Search Mode + +- **Natural language questions** (e.g., "What is the deadline for project X?"): Best for fuzzy, conceptual searches where you don't know exact keywords. +- **Keyword search** (e.g., `project X deadline`): Best for finding specific, exact content. + +### Use Multiple Searches + +Don't rely on a single search. Break complex questions into smaller searches: + +- Search for the topic first +- Then search for specific people's contributions +- Then search in specific channels + +## Search Modifiers Reference + +### Location Filters + +- `in:channel-name`: Search within a specific channel +- `in:<#C123456>`: Search in channel by ID +- `-in:channel-name`: Exclude a channel +- `in:<@U123456>` or `in:@username`: Search in DMs with a user + +### User Filters + +- `from:<@U123456>`: Messages from a specific user (by ID) +- `from:username`: Messages from a user (by Slack username) +- `to:<@U123456>`: Messages sent to a specific user +- `to:me`: Messages sent directly to you +- `creator:@username`: Canvases created by a specific person + +### Content Filters + +- `is:thread`: Only threaded messages +- `is:saved`: Only your saved messages +- `has:pin`: Pinned messages +- `has:link`: Messages containing links +- `has:file`: Messages with file attachments +- `has::emoji:`: Messages with a specific reaction +- `hasmy::emoji:`: Messages you reacted to with a specific reaction + +### Date Filters + +- `before:YYYY-MM-DD`: Messages before a date +- `after:YYYY-MM-DD`: Messages after a date +- `on:YYYY-MM-DD`: Messages on a specific date +- `during:month`: Messages during a specific month (e.g., `during:january`) + +### Text Matching + +- `"exact phrase"`: Match an exact phrase +- `-word`: Exclude messages containing a word +- `wild*`: Wildcard matching (minimum 3 characters before `*`) + +## File Search + +To search for files, set the `content_types="files"` parameter and use a `type:` filter in the query: + +- `type:images`, `type:documents`, `type:pdfs`, `type:spreadsheets`, `type:presentations` +- `type:canvases`, `type:lists`, `type:emails`, `type:audio`, `type:videos` + +Example: `content_types="files" type:pdfs budget after:2025-01-01` + +All the standard modifiers above (`in:`, `from:`, dates, etc.) work with file searches too. + +## Useful Parameters + +Beyond the query string, the search tools accept parameters that materially improve results: + +- `sort`: `score` (relevance, default) or `timestamp` (newest first); pair with `sort_dir` (`asc`/`desc`). +- `content_types`: `messages` (default) or `files`. +- `only_my_channels`: restrict to channels you're a member of. +- `limit`: results per page (capped at 20); paginate with the returned `cursor`. + +## Following Up on Results + +After finding relevant messages: + +- Use `slack_read_thread` to get the full thread context for any threaded message. +- Use `slack_read_channel` with `oldest`/`latest` timestamps to read surrounding messages for context. +- Use `slack_read_user_profile` to identify who a user is when their ID appears in results. +- Use `slack_read_file` to read the contents of a file surfaced by a file search. +- Use `slack_list_channel_members` to see who is in a channel you found. + +## Common Pitfalls + +- **Boolean operators don't work.** `AND`, `OR`, `NOT` are not supported. Use spaces (implicit AND) and `-` for exclusion. (Repeating the same modifier, e.g. two `from:`, ORs those values together.) +- **Parentheses don't work.** Don't try to group search terms with `()`. +- **Search is not real-time.** Very recent messages (last few seconds) may not appear in search results. Use `slack_read_channel` for the most recent messages. +- **Private channel access.** Use `slack_search_public_and_private` when you need to include private channels, but note this requires user consent. + +## Notes + +- **Scope:** this skill owns searching _workspace content_: messages, files, channels, and people inside Slack. To search and read the official Slack _platform documentation_ at docs.slack.dev (conceptual and how-to questions about Slack features), use the `slack-docs` skill instead. diff --git a/.claude/skills/test-slack-app/SKILL.md b/.claude/skills/test-slack-app/SKILL.md new file mode 100644 index 0000000..69f08ff --- /dev/null +++ b/.claude/skills/test-slack-app/SKILL.md @@ -0,0 +1,111 @@ +--- +name: test-slack-app +description: Use when a developer wants to test, try out, smoke-test, verify, or confirm that a Slack app built with the Slack CLI (or a plain Bolt app) actually works, by running it in a developer sandbox or a Free Team, never a workspace with real users, with `slack run` and exercising its real slash commands, shortcuts, events, actions, modals, App Home, and assistant surfaces. Also covers `slack doctor` and `slack manifest validate` health checks before hands-on testing. +--- + +# Test Slack App + +Help a developer confirm that a Slack app they already built actually works. This is the last step of the build loop, after the `create-slack-app` skill scaffolds an app and the `slack-cli` skill runs it. + +The approach is simple and safe: + +1. **Run the app in a developer sandbox or a Free Team:** a sandbox for preference, or a Free Team the developer created for this. Never a workspace with real coworkers in it. +2. **Read the app's source** to learn what it actually listens for. +3. **Hand the developer concrete steps** to perform in Slack, then help them confirm the app responds. + +This is guided manual checking, not an automated test suite: you drive the setup and tell the developer what to type or click, and they confirm what they see. It works best for apps managed by the Slack CLI; there is a best-effort path for plain Bolt apps in Step 2. + +--- + +## Step 1: Set Up a Safe Place to Test + +### 1a. Detect the Slack CLI + +Load the `slack-cli` skill (with your skill tool, if you have one) before running any command, and follow its **Step 1: Detect the Slack CLI** to check whether the public Slack CLI is installed and resolve its command name. Don't check for the CLI yourself first: a `slack` on `PATH` isn't always the public CLI, and that step tells them apart. The fingerprint check, alias fallback, and install instructions all live there; do not duplicate them here. Refer to the resolved command as `SLACK_CMD` throughout. If the CLI is not installed, guide the developer through that same step to install it, since running the app needs it. + +### 1b. Make sure there is a safe workspace to test in + +Testing belongs in a workspace nobody is working in: a developer sandbox for preference, or a Free Team the developer created for this. Never a workspace with real coworkers in it. + +- **Explain it from the live docs, not from here.** Use the `slack-docs` skill to fetch and summarize , so the recommendation always reflects the current docs rather than a copy that drifts out of date. Tell the developer that Slack recommends a sandbox for building and testing apps. +- **Find the current target.** Run `SLACK_CMD auth list` for the authenticated workspaces and their team IDs, and, from the project directory, `SLACK_CMD app list` for the apps already installed and their IDs. +- **Confirm the target is safe.** The CLI cannot tell a sandbox, a Free Team, and a workspace full of real users apart, so ask the developer which one they are pointed at. A sandbox or a Free Team they created for this is fine. A workspace with coworkers in it is not: stop and get them onto one of the other two. +- **If there is no safe target yet**, set one up with the `create-slack-app` skill (**Step 3: Choose Where to Install the App**), which owns the ranked targets, the `sandbox list` / `sandbox create` flow, and the Developer Program links. Either path finishes in the browser, so have the developer come back here once the workspace exists and they have logged into it. + +### 1c. Quick health check + +Catch obvious setup problems with the CLI's own validation before the slower hands-on checks: + +- `SLACK_CMD doctor`: checks the CLI, language runtime, and authentication. +- `SLACK_CMD manifest validate`: run from the project directory if the app has a manifest, to confirm the app configuration is well-formed. + +Surface anything these flag before moving on. + +--- + +## Step 2: Run the App + +Whichever path you use below, first turn the app's log level up to debug so you have the most context while testing. Prefer a way that leaves the developer's code untouched: read the logger setup to see whether it reads a log-level environment variable (some templates wire one such as `SLACK_LOG_LEVEL` or `LOG_LEVEL`). If it does, set that variable instead of editing source. For a CLI-managed app, `SLACK_CMD env set debug` stores it in the project `.env` that `slack run` reads; for a plain Bolt app, set it in the environment or `.env` the app already reads. Only when the logger reads no such variable should you edit the source, finding where the log level is set and switching it to debug for this run. + +### CLI-managed apps (recommended) + +Follow **Step 6: Running an App Locally (`slack run`)** in the `slack-cli` skill to start the local dev server in the background. This also installs the app into the target workspace, which matters for a fresh sandbox or Free Team where nothing is installed yet. Once it is running, file changes auto-reload. + +### Plain Bolt apps without the CLI (best-effort) + +If the app is a plain Bolt app started with `node` or `python` rather than the Slack CLI, this skill can still help, but the run path is best-effort and not the primary flow: + +- Point the app at the test workspace: set its bot and app-level tokens (from that workspace's app settings) in the environment or the `.env` file the app reads. +- Prefer socket mode so the app needs no public URL. This works only if the app is coded for socket mode and the app-level token has `connections:write`; adding tokens to an app scaffolded for HTTP will not deliver events. +- Start the app with its own command (for example `npm start` or `python app.py`) and watch its logs. + +Say plainly that this path is best-effort, and that the smoothest experience comes from a CLI-managed app. + +--- + +## Step 3: Try It Out in Slack and Confirm It Works + +This is the heart of the skill. Do not hand the developer a generic checklist. Ground every step in what _this_ app actually registers. + +### 3a. Read the source to find what the app listens for + +Read the app's listener code and list the interactions it registers. Depending on the framework these look like: + +- **[Slash commands](https://docs.slack.dev/interactivity/implementing-slash-commands.md):** a registered command name such as `/ship`. +- **[Shortcuts](https://docs.slack.dev/interactivity/implementing-shortcuts.md):** global or message shortcuts with a callback ID. +- **[Events](https://docs.slack.dev/apis/events-api.md):** subscribed events such as `app_mention`, `message`, or `reaction_added`. +- **[Actions](https://docs.slack.dev/interactivity/handling-user-interaction.md):** interactive components (buttons, selects) with an action ID. +- **[View submissions](https://docs.slack.dev/surfaces/modals.md):** modal submit handlers (`view_submission`). +- **[App Home](https://docs.slack.dev/surfaces/app-home.md):** an `app_home_opened` handler or a published Home tab. +- **[Assistant / agent](https://docs.slack.dev/ai.md):** an assistant or `assistant_thread_started` handler, common in the agent templates. + +Name the concrete identifiers you find (the actual command and callback names), not placeholders. + +### 3b. Turn each into a "do this, expect that" step + +For every registered interaction, give the developer a concrete step and what a working app should do in response. A few spots are non-obvious, so spell them out: + +- **Slash command** → type the command (for example `/ship`) in a channel or DM in the test workspace → expect the response the handler sends. +- **Global shortcut** → open the shortcuts menu (the lightning-bolt or `+` button in the message composer, depending on your client) and pick it → expect the modal or message it opens. +- **Message shortcut** → hover a message, open **More actions** (the `⋯` menu), pick the shortcut → expect its response. +- **Event** such as `app_mention` → @-mention the app in a channel it belongs to → expect its reply. +- **Button or select** → click the component in a message or modal the app posted → expect what the action handler does. +- **Modal submit** (`view_submission`) → submit the modal → expect the confirmation or side effect. +- **App Home** → click the app in the left sidebar to open its **Home** tab → expect the published view. + +### 3c. Confirm and report + +While the developer interacts, help them confirm it is working: + +- If the app runs under `slack run`, watch its logs (ask "show me the output from slack run") to confirm events arrive and to read any errors. +- If a response looks wrong (a malformed message or Block Kit view, or an API error), use the `block-kit` and `slack-api` skills to dig into the payload or method. + +Close with a short summary: what you and the developer confirmed working, and what they should eyeball themselves. Remember this is manual checking: you are helping the developer watch the app respond, not producing an automated pass or fail. + +--- + +## Notes + +- `SLACK_CMD` is a placeholder: always substitute the actual command name resolved in Step 1a. +- Scope: this skill tests an app that already exists. To create or scaffold one, use the `create-slack-app` skill; for raw CLI mechanics, use the `slack-cli` skill; for message or Block Kit formatting, use the `slack-messaging` and `block-kit` skills. +- Out of scope for now: automated test frameworks for Bolt, programmatically simulating user interactions, and driving the Slack UI with a browser. Today the developer performs the interactions; this skill makes sure they know exactly what to do and what to expect. diff --git a/.gitignore b/.gitignore index 1636de3..0a316bd 100644 --- a/.gitignore +++ b/.gitignore @@ -39,4 +39,5 @@ logs/ .pytype/ .vscode .cursor -.claude/ +.claude/* +!.claude/skills/