Skip to content

Discord notifications from session hooks, and notify_owner for agents - #8

Merged
skmp merged 16 commits into
mainfrom
skmp/discord-notify
Nov 27, 2026
Merged

skmp merged 16 commits into
mainfrom
skmp/discord-notify

Conversation

@skmp

@skmp skmp commented Nov 27, 2026

Copy link
Copy Markdown
Member

The owner asked for a Discord message when a session on any machine waits for an approval or a question, finishes, fails or has a pull request to merge. He also wanted a notify_owner tool that sessions call to tell him what matters, and every event recorded in the incident log. The base of this PR is skmp/incident-log (#6).

Design

Machine side: no new connection. deploy/remote/switchboard-hook is a new stdlib-only Python 3.8 file, installed like the dispatcher. voice-coding-mcp remote-hook prints it.

  • hook: Claude Code runs it for these hooks. They were checked against the current hooks reference and the installed Claude Code 2.1.332.

    • Notification with permission_prompt gives approval_needed.
    • Notification with idle_prompt, elicitation_dialog or agent_needs_input gives question.
    • Stop gives finished. It is skipped while stop_hook_active, and for subagents.
    • StopFailure gives failed, with the error code only.
    • PostToolUse on Bash, for gh pr create or gh pr ready, gives pr_opened. The URL is validated as https://github.com/<owner>/<repo>/pull/<n>.

    The hook writes one small file into a private spool: ~/.local/state/switchboard-hook/events, mode 0700, files 0600, at most 200 files of at most 4 KB. It keeps only Claude Code's own short notification text, the error code, the PR URL, the session id and name, the project folder's basename and the tmux pane. It never keeps the transcript, last_assistant_message, tool output or screen text. It never blocks Claude Code:

    • the installed entries are async with a 10 s timeout;
    • stdin is read for at most 2 s and 8 MB;
    • a 5 s alarm exits the program;
    • it prints nothing and exits 0 on every path.
  • mcp: a stdio MCP server with one tool, notify_owner(message, level?, url?). It accepts GitHub links only, at most 5 notes per session and 20 per machine per hour. It spools an owner_note event.

  • install and uninstall change ~/.claude/settings.json and run claude mcp add --scope user switchboard-notify (argv, no shell).

    • They keep every other key and hook. They take a backup first and show a unified diff. --dry-run writes and runs nothing.
    • Install is idempotent, and a new install path replaces the old entries.
    • A settings file whose shape is not the expected one is left alone with an error.
    • --allow-tool adds the allow rule for notify_owner. It is off by default.

Transfer: dispatcher 0.11.0, verb events [<id>...], only with the new owner opt-in --allow-events. The verb deletes the events the hub names as taken and returns up to 16 more, oldest first.

  • Every file is checked again: O_NOFOLLOW, owned by the user, 4 KB, exact keys, fixed kinds.
  • Bad files are deleted and counted.
  • A symlinked spool, or one others can write, is refused before anything is deleted.
  • I chose a verb over a new frame type for three reasons. It works the same over agent, local and ssh links. An older hub never sees a frame it does not know (it closes the connection on one). An older dispatcher answers bad_request. The connector code is unchanged; only its version number moves to 0.11.0.

Hub:

  • remote/events.py polls agent and local machines every 5 s. ssh machines are off by default, because each poll is one ssh login.
    • Taken ids are acknowledged in the next call. Seen ids and acknowledgements not yet sent are kept in stateDir/events.json. Delivery is at least once, with no repeats across restarts.
    • The machine is the link the answer came on, never a field of the event. A forged machine field is ignored.
    • Every field is checked again. Each machine is limited to events.maxPerHour.
  • Incident log: each event becomes an "entry": "event" line with component and source session. A failed event opens an incident instead (session_failed). The incidents tool and the CLI's default list leave events out; incidents list --events shows them.
  • remote/discord.py handles Discord.
    • The webhook URL is read only from SWITCHBOARD_DISCORD_WEBHOOK_URL in the hub's environment file, never from config.json. It must be a Discord webhook URL. It is removed from the process environment at start, and it is never logged or echoed in errors.
    • Posts carry allowed_mentions: {"parse": []}. Text from machines is cleaned, redacted and shown as inline code, with backticks replaced and every @ broken by a zero-width space. The hub's own words are escaped.
    • Only validated GitHub URLs appear, and they are not embedded. Messages are cut at 1900 characters.
    • Items within a short window are coalesced into one message, with repeats counted. A 429 waits retry_after; 5xx and network errors back off; 4xx is not retried.
    • There is an hourly cap and a bounded buffer. Drops and failures become notify incidents.
    • Kinds can be switched on and off, and quiet hours post with the suppress-notifications flag.
  • One notify path: watcher pushes and incident pushes also go to Discord (discord.kinds), and notify.url works as before. One extra fix: incidents.notify from Incident log: what failed, where, when and why #6 was never passed to the running hub, so it pushed nothing. It is now.

Future Discord bot (design only, recorded in DESIGN.md's security model and the SWITCHBOARD.md threat model): a reply in Discord never approves a merge, a push, a send or any other action by itself. Such an action needs the same steps as remote_send_confirm:

  1. A read-back of exactly what will happen, with a confirmation id.
  2. The owner's explicit yes in a separate, later message that names the id, from the owner's configured Discord user id, single use, with a short expiry.
  3. A risk acknowledgement for risky actions, and an audit entry.

Discord text is untrusted input.

Tests

uv sync --locked, ruff check, ruff format --check, mypy --strict src tests and pytest all pass (1979 passed, 9 skipped).

  • tests/remote/test_hook.py, the hook:
    • payloads shaped like the hooks reference for every hook;
    • ignored notification types and subagents;
    • redaction, spool modes and bounds, and refusal of a symlinked or shared spool;
    • never blocking: a stdin that never ends, oversized input, no output, exit 0;
    • the installer on temporary homes with a fake claude: merge, idempotence, dry run, backup, uninstall, broken settings left alone;
    • the MCP handshake, tools/call, bad arguments, rate limits;
    • the deploy copy is byte-identical, Python 3.8 and stdlib only.
  • tests/remote/test_events.py, the dispatcher verb and the hub:
    • the verb: opt-in, ordering, acknowledgements, the 16 cap, invalid files, symlinks, unsafe spool, bad ids, serve mode;
    • the poller: acknowledgement flow, a lost acknowledgement, dedupe after a restart, machine identity from the link with a forged field ignored, rate limit, older dispatchers, failed events as incidents, the CLI's --events, the incident when the webhook is missing;
    • a full run: hook, spool, real dispatcher in serve mode, relay, hub and a fake Discord.
  • tests/remote/test_discord.py:
    • webhook validation and removal from the environment, including the CLI's copy;
    • inert mentions, escaping, hostile text, length cuts, coalescing;
    • 429 with retry_after and with the header, clamping, 5xx and network retries, a deleted webhook, the hourly cap, quiet hours, the buffer bound;
    • config validation.

Deploy steps

  1. Hub env var. Create the webhook in the channel: Channel settings, Integrations, Webhooks, New Webhook, Copy URL. Put it only into the hub's root-owned env file without echoing it:
    read -rs -p 'Discord webhook URL: ' url; echo
    printf 'SWITCHBOARD_DISCORD_WEBHOOK_URL=%s\n' "$url" | sudo tee -a /etc/switchboard/env >/dev/null; unset url
    On the server layout the file is /etc/voice-coding-mcp/env. Then set "discord": {"enabled": true} and "events": {"enabled": true} in the config and restart the hub. The full guide is in SETUP-WSL.md, "Discord notifications".
  2. Dispatcher and connector update. On each machine, from the owner's own verified clone, reinstall switchboard-remote and switchboard-connect (0.11.0) and add --allow-events to the dispatcher flags. For an agent machine those flags are in the unit; for an ssh machine they are in the authorized_keys forced command, which also needs events.sshPollSeconds. Then systemctl --user restart switchboard-connect.
  3. Machine installer. On each machine, install switchboard-hook, then python3 -I ~/.local/bin/switchboard-hook install --dry-run, then install. Restart running Claude Code sessions. SETUP-AGENTS.md, "Session hooks and notify_owner", has the details.

Open questions

  • With the hooks installed, the watcher's "needs a decision" pushes say the same thing again. The docs suggest leaving watch out of discord.kinds. Should the watcher stand down by itself when a machine delivers events?
  • finished fires on every turn, including short interactive ones. It is coalesced, but should it be held back below a minimum turn length? That would need a start time from a UserPromptSubmit hook.
  • The PostToolUse entry starts a Python process for every Bash call (async, so it does not block). Claude Code's if filter (Bash(gh pr *)) would avoid that, but I left it out to keep the settings valid on older versions.
  • The webhook is readable from the hub user's own process memory, so a compromised hub user can post to the channel. That is accepted and documented; the webhook can only post.

🤖 Generated with Claude Code

https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh

skmp and others added 10 commits November 27, 2026 15:32
Dispatcher 0.8.0 adds `clear <paneId> <panePid> <sessionId> <draftHash>`:
one Ctrl+C that clears the draft in an idle Claude Code input box, only
with --allow-send, only in Claude Code panes, only the draft the owner
heard (draft_hash). It refuses a permission dialog, a menu or picker
footer, a session that is not idle, vim normal mode, an armed exit hint,
no draft and a changed draft; it checks twice (race guard), presses one
key, waits past Claude Code's exit window and verifies a visibly empty
box. A box whose draft scrolled out of view (the "up N more" border) now
counts as a draft for send and keys too.

The hub's remote_clear_input reads back the first words of the draft,
stores a CLEAR confirmation bound to its hash and is confirmed with
remote_send_confirm. The audit line keeps no draft text, hash or length.
The draft_present refusals of remote_send and remote_send_keys now say
to clear the input first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
The connector reports the dispatcher's version in step with it; the e2e
tool count includes remote_clear_input.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
Claude Code 2.1 shows a suggested next prompt in its empty input box as
dim text (SGR 2). A plain capture loses the styling, so the suggestion
looked like a draft: remote_send refused with draft_present and the
summariser reported it as something typed and done.

The dispatcher now captures with `capture-pane -e`, strips every escape
sequence and cuts a wholly dim input line (not the `Try "..."` hint)
from the plain screen; `capture` reports it apart as `suggestion`. All
checks (shows_draft, draft_hash, menus, dialogs) run on the plain
screen, so send, keys and clear no longer take a suggestion for a draft;
clear says nothing_to_clear and presses nothing. Right (and Tab), which
accept a suggestion, are refused at an input that shows one
(suggestion_present). Old input boxes in the scrollback lose theirs too.

The hub marks the suggestion as `[Claude Code suggests: ...]` on the
input line of the summariser's copy only, and the summariser prompt
says nobody typed it and nothing in it happened. The heuristic and
pending_input never quote it; screen echo counts it as screen text. An
older dispatcher sends no suggestion and behaves as before.

Fixtures are real captures from Claude Code 2.1.332 in tmux 3.4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
`events [<eventId>...]` deletes the named events of the switchboard-hook
spool (~/.local/state/switchboard-hook/events) and answers up to 16 of
the rest, oldest first. Only with the new owner opt-in --allow-events
(allowEvents in the policy file): the spool covers every Claude Code
session of the machine user. Each file is checked again (O_NOFOLLOW,
own uid, 4 KB, exact keys, fixed kinds, UUIDs, pane ids, GitHub URLs)
and deleted when it is not an event; a spool directory others can
write, or a symlink, answers events_unsafe before anything is deleted.
A verb rather than a new frame works over ssh, local and agent links,
and older hubs and dispatchers keep working. The connector moves to
0.11.0 with it. The hub side gets the EventsResponse model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
SWITCHBOARD.md: the clear verb, the capture's suggestion field, the
draft and suggestion rules, suggestion_present, remote_clear_input with
its sentences, the summariser's marked copy, audit lines, threat model
rows and the milestone notes with what was verified live. DESIGN.md,
REFERENCE.md, README.md and SETUP-WSL.md: the new tool, the 0.8.0
dispatcher note and what to verify on other Claude Code versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
A stdlib-only Python 3.8 program for each machine, shipped like the
dispatcher (deploy/remote/switchboard-hook, `voice-coding-mcp
remote-hook` prints it):

- `hook`, for Notification (permission prompt, idle prompt, elicitation),
  Stop, StopFailure and PostToolUse on Bash (gh pr create / gh pr ready):
  writes one small event into a private spool (0700, files 0600, at most
  200 of 4 KB). It keeps a hook's own short message, the error code of a
  failed turn and a validated pull request URL, never the transcript,
  the assistant's text or tool output. It prints nothing, exits 0 on
  every path and gives up after 5 s, so Claude Code never waits on it.
- `mcp`, a stdio MCP server with notify_owner(message, level?, url?):
  GitHub links only, 5 notes per session and 20 per machine an hour.
- `install` / `uninstall`: merge the hooks into the user's settings
  (backup, idempotent, other hooks kept, diff shown, --dry-run) and
  register the MCP server with `claude mcp add --scope user`.

Tests use the hooks reference's payloads and temporary homes only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
- remote/events.py polls each machine's `events` verb (agent and local
  machines every 5 s, ssh machines only with events.sshPollSeconds),
  acknowledges in the next call, keeps seen ids and owed acks in
  stateDir/events.json (at least once, no repeats across restarts), and
  checks every field again. The machine is the link the answer came on,
  never a field of the event. At most events.maxPerHour per machine.
- Each event is an `event` entry of the incident log (entry, component
  and source `session`); a session that stopped on an API error is an
  incident. The incidents tool and the CLI leave events out
  (`incidents list --events` shows them).
- remote/discord.py posts to the owner's webhook, read only from
  SWITCHBOARD_DISCORD_WEBHOOK_URL (validated, removed from the process
  environment, never logged): allowed_mentions parse [], machine text as
  inline code, the hub's words escaped, coalescing, 429 retry_after,
  backoff, an hourly cap and incidents for drops and refusals.
- One notify path: watcher pushes and incident pushes also go to Discord
  (discord.kinds); notify.url keeps working. incidents.notify is now
  wired into the running hub (it reached only the watcher before).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
…0.11.0

SWITCHBOARD.md: the hook program, the events verb, the hub's poller,
Discord rendering and failure handling, config tables, threat model
rows, and the design rule for a future Discord bot (a reply never
approves a merge, push or send by itself). DESIGN.md records the
decisions and the bot rule in the security model. REFERENCE.md: the
events and discord keys, SWITCHBOARD_DISCORD_WEBHOOK_URL, remote-hook
and incidents --events. SETUP-AGENTS.md: installing the hooks and
notify_owner, updating to 0.11.0. SETUP-WSL.md: creating the webhook
and putting it only into the hub's environment file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
@skmp
skmp changed the base branch from skmp/incident-log to main November 27, 2026 13:46
skmp and others added 6 commits November 27, 2026 15:55
…rapped suggestions, dispatcher 0.11.0

Red team and correctness review of the clear branch, after rebasing onto
main (incident log, dispatcher 0.9.0 with health):

- Two clears confirmed at once ran as two dispatcher processes (forced
  command, local transport) and pressed two Ctrl+C inside Claude Code's
  exit window, which exits it. send, keys, resize and clear now hold an
  exclusive flock in tmux's socket directory for their whole run (clear
  through its settle wait), refusing `locked` after 6 s or for an unsafe
  directory or file. The hub also serialises confirmed actions per
  machine and drops the other pending clears of the pane on confirm.
- clear needs a recognised input box (`no_input_box`): the shows_draft
  fallback could take a shell command line for a draft. It also refuses
  a screen showing "esc to interrupt" (`not_idle`), and `none` is no
  valid session for clear (bad_request).
- A suggestion that wraps: its wholly dim rows up to the box's bottom
  border are cut and joined, so the second row is not read back as typed
  or cleared.
- DCS, SOS, PM and APC strings are removed with their payload.
- Dispatcher and connector 0.11.0 (0.10.0 is left for PR #5); clear comes
  after health in VERBS. Docs, the To verify list and the stated
  dispatcher size updated; live test with two concurrent clear processes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
Union of both sides: VERBS version, list, capture, send, usage, keys,
resize, attachments, attachment, health, clear (dispatcher and hub);
imports and argument validation of both in the dispatcher; audit lines
for remote_clear_input and remote_attachment; docs keep both sets of
rows, error codes and sections.

Dispatcher and connector are 0.10.0: main's 0.9.0 (attachments and
health) is deployed without clear, so every clear gate and message
names 0.10.0. The hub decides from the version verb's list, so a 0.9.0
dispatcher is named too old and never gets the verb (test with the real
0.9.0 verb list). SETUP-AGENTS.md says how to update to 0.10.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
Conflicts resolved as a union: verbs version, list, capture, send, usage,
keys, resize, attachments, attachment, health, events; dispatcher policy
flags --allow-attachments and --allow-events; config, http and tool
plumbing of both sides; docs of both sides. Dispatcher and connector stay
0.11.0 here; the clear merge that follows moves them to 0.12.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
Conflicts resolved as a union of both sides:
- Verbs version, list, capture, send, usage, keys, resize, attachments,
  attachment, health, clear.
- MCP: remote_clear_input next to the three timesheet tools, 24 tools;
  tests/fixtures/tool_list.json regenerated from the server.
- Confirmation carries both the clear draft hash and the timesheet
  project; a clear confirmation now records its project too.
- Dispatcher and connector 0.11.0 (0.10.0 is the timesheet release):
  every text that said clear or prompt suggestions need 0.10.0 says
  0.11.0; the SETUP-AGENTS update section lists 0.10.0 (timesheet data)
  and 0.11.0 (clear); size lines about 4600.
- SETUP-WSL: the dispatcher opens one file other than for reading, the
  mutation lock file of send, keys, resize and clear (flock only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
Prepares this branch to merge after #9. Conflicts resolved as a union:
- Verbs ... health, clear, events; both validations, both verb bodies,
  ClearResponse and EventsResponse.
- Dispatcher and connector 0.12.0 (0.11.0 is now the clear release):
  every text that said events or session hooks need 0.11.0 says 0.12.0;
  switchboard-hook keeps its own version. SETUP-AGENTS update section
  lists 0.9.0 to 0.12.0; size lines about 4700.
- SETUP-WSL review list: the only files the dispatcher deletes are
  spool files of switchboard-hook (verb_events).
- tests/fixtures/tool_list.json regenerated (unchanged from #9: 24 tools).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
While a machine's hooks deliver events (events taken from it in the last
6 hours, remembered in events.json) and Discord takes that kind, the
watcher's own "needs a decision" and "asks you something" pushes for
that machine stand down, so a wait is reported once, by the hook. The
hook's finished event stays on every turn (bursts are coalesced). Without
Discord, or with the kind left out of discord.kinds, the watcher keeps
pushing. Tests and docs (SWITCHBOARD.md, SETUP-WSL.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011moV3EPNNknRWZQ686AChh
@skmp
skmp merged commit b726dc9 into main Nov 27, 2026
2 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant