martin1847/evolab / skills/agent-mail
agent-mail
Verified多编排者/长期 agent 身份之间的异步信箱总线——发信、收信、回信、归档、名册注册。每个身份一个 inbox,一封信只有一个去处(收件人 inbox),收信只查自己信箱。触发:给另一个编排者/CTO/agent 写信或提议、查我的信箱、跨编排者协调、看有哪些注册身份。不用于人类电子邮件(gmail/给真人同事或客户写信)或普通消息转发。可选伴随 cto-orchestration 使用(多编排者场景)。Use when writing to / reading mail from another orchestrator agent, coordinating across orchestrators, or managing the agent roster; NOT for human email.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 11.7 KB |
| agentmailexecutable | script | 16.9 KB |
| hooks.json | config | 885 B |
| mail-check.pyexecutable | script | 6.7 KB |
| mail-guard.pyexecutable | script | 3.7 KB |
agentmail
View on GitHub#!/usr/bin/env bash
# agent-mail agentmail helper — inter-orchestrator mailbox ops. Pure bash, no deps.
# Bus root = $AGENT_MAIL_DIR (default ~/.agents/mail) — USER DATA, deliberately outside
# this skill's directory so publishing/upgrading the skill never touches mail.
set -euo pipefail
# Owner-only by default: mail is untrusted data on a shared trust boundary (the fs user),
# so every dir/file this helper creates must be unreadable to other users. umask 077 makes
# mkdir→700 and file-create→600 without a chmod after each op (structural, not discipline —
# a forgotten chmod is the exact leak this prevents). Pre-existing loose perms: see SKILL 硬化节.
umask 077
BUS="${AGENT_MAIL_DIR:-$HOME/.agents/mail}"
REG="$BUS/registry.md"
usage() {
cat <<'EOF'
agentmail — agent-mail inter-orchestrator mailbox (root: $AGENT_MAIL_DIR, default ~/.agents/mail)
agentmail register <agent-id> <workdir> <focus...> add to roster + create mailbox
agentmail check <agent-id> list pending (inbox, oldest first)
agentmail send <from> <to> <slug> [subject...] deliver a letter to recipient inbox (atomic;
body optional via stdin, empty if a tty)
agentmail archive <agent-id> <id> move a handled letter to archive (gzip'd)
agentmail prune <agent-id> [days] delete archive letters older than N days (default 60)
agentmail roster print roster
agentmail wire [--project <abs-path>] idempotent hook wiring; level decided by
user-level state (duplicate = refused)
EOF
}
# Letter BODY size thresholds (bytes) — see `send`. BODY_CAP is a hard refusal with no override:
# a payload that size belongs in a file (absolute path + one-line summary in the letter), not in
# the mailbox. BODY_SOFT only warns on stderr (delivery proceeds): the owner wants letters lean —
# every byte of a letter is read by the recipient's context, so brevity is a token budget, not style.
BODY_CAP=8192
BODY_SOFT=2048
# Sourcing-reminder tuning (see the send path). CLAIMS_MIN is a coarse floor, NOT a validated
# threshold: coordination replies and questions sit well under it, a letter carrying a load-bearing
# system claim sits well over. CLAIMS_TRACE is the vocabulary senders actually cite with — the
# file:line branch requires a letter on the left so times (14:30) and ratios (1:2) are not evidence,
# and a backticked span must contain a space so an inline identifier is not mistaken for a command.
# Known and accepted: `localhost:3000` reads as a citation, and a mostly-speculative letter with one
# real citation stays silent — narrowing either one means classifying prose, which is undecidable.
CLAIMS_MIN=400
CLAIMS_TRACE='https?://|/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]|[A-Za-z0-9_/.-]*[A-Za-z][A-Za-z0-9_/.-]*:[0-9]{1,5}|`[^`]* [^`]*`|\$\(|未验|未核|未取证|推测|没验证|unverified|not verified'
# Archive retention (days; owner-set policy: 60). Every `archive` opportunistically prunes the same
# seat's expired letters — no daemon/cron needed; `prune` runs the sweep explicitly. The env var
# overrides the default; an explicit `prune <id> <days>` argument overrides both.
RETENTION_DAYS="${AGENT_MAIL_RETENTION_DAYS:-60}"
prune_archive() { # $1 agent-id $2 days -> prints deleted count; missing archive counts as 0
arc="$BUS/$1/archive"
[ -d "$arc" ] || { echo 0; return 0; }
# -mtime +N = strictly older than N days; both plain .md (pre-gzip history) and .md.gz age out.
find "$arc" -maxdepth 1 -type f \( -name '*.md' -o -name '*.md.gz' \) \
-mtime +"$2" -print -delete | wc -l | tr -d ' '
}
ensure_reg() {
mkdir -p "$BUS"
[ -f "$REG" ] || printf '# agent-mail 名册(registry)\n\n| agent-id | 工作目录 | 职责(一句话) |\n|---|---|---|\n' > "$REG"
}
cmd="${1:-}"; shift || true
case "$cmd" in
register)
id="${1:?agent-id}"; dir="${2:?workdir}"; shift 2; focus="$*"
ensure_reg
mkdir -p "$BUS/$id/inbox" "$BUS/$id/archive" "$BUS/$id/tmp"
if ! grep -q "| \`$id\` |" "$REG" 2>/dev/null; then
# insert AFTER the last table row (not file end — a trailing footer note would break the table)
row="$(printf '| `%s` | `%s` | %s |' "$id" "$dir" "$focus")"
awk -v row="$row" '{ lines[NR]=$0; if ($0 ~ /^\|/) last=NR }
END { for(i=1;i<=NR;i++){ print lines[i]; if(i==last) print row } }' "$REG" > "$REG.tmp" && mv "$REG.tmp" "$REG"
echo "registered $id -> $dir (mailbox: $BUS/$id)"
else
echo "$id already in roster (edit $REG to change)"
fi
;;
check)
id="${1:?agent-id}"; ib="$BUS/$id/inbox"
[ -d "$ib" ] || { echo "no such agent: $id (register first)"; exit 1; }
# tmp/ (in-flight `send` writes) is a SIBLING of inbox/, never inside it — this glob
# structurally never sees a half-delivered letter, no special-casing needed.
n=0
for f in $(ls "$ib"/*.md 2>/dev/null | sort); do # id 前缀含时间戳 → 文件名序 = 最旧优先
n=$((n+1))
subj="$(grep -m1 '^subject:' "$f" | sed 's/^subject:[[:space:]]*//')"
frm="$(grep -m1 '^from:' "$f" | sed 's/^from:[[:space:]]*//')"
printf ' from=%-12s %s (%s)\n' "$frm" "$subj" "$(basename "$f")"
done
[ "$n" -eq 0 ] && echo " (inbox empty)" || echo "$n pending in $id inbox — oldest first, handle ALL (先到的信不许被遮蔽)"
;;
send)
from="${1:?from}"; to="${2:?to}"; slug="${3:?slug}"; shift 3; subject="${*:-<subject>}"
base="$BUS/$to"; ib="$base/inbox"; tmpd="$base/tmp"
[ -d "$ib" ] || { mkdir -p "$ib" "$base/archive"; echo "note: $to not registered — mailbox created anyway (mail must not bounce); consider: agentmail register $to <workdir> <focus>"; }
mkdir -p "$tmpd"
id="$(date +%Y%m%d-%H%M)-$from-$slug"; dest="$ib/$id.md"
[ -e "$dest" ] && { echo "exists: $dest"; exit 1; }
# Body is read from stdin when it's not a tty (piped/redirected — the normal shape for an
# agent/CI caller, incl. this test suite); a real interactive tty is left alone (empty body)
# so a human at a shell prompt never blocks waiting on Ctrl-D. Read BEFORE touching the
# filesystem so an oversized letter never creates a tmp file at all.
body=""
if [ ! -t 0 ]; then body="$(cat)"; fi
bodylen=$(printf '%s' "$body" | wc -c | tr -d ' ')
if [ "$bodylen" -gt "$BODY_CAP" ]; then
echo "refused: body is $bodylen bytes, cap is $BODY_CAP (pointer-not-payload: write the payload to a file, put its absolute path + a one-line summary + the finding it supports in the letter instead — no override)" >&2
exit 2
fi
if [ "$bodylen" -gt "$BODY_SOFT" ]; then
echo "warning: letter is $bodylen bytes; aim for <2KB — conclusion first, only the action you need from the recipient, evidence as file paths/URLs not inline content" >&2
fi
# A letter is the one artifact that reaches another seat's decision table without passing any
# review — code, gates and PR feedback all get cold-reviewed; a letter is written and sent.
# Field case (external seat, 2026-08-12): one unsourced sentence, written as a possibility, was
# read as a finding and used to size a breaking change; a later audit measured zero exposure.
#
# Whether a claim is sourced is not machine-decidable, and a hard block would only breed fake
# markers. Trace-ABSENCE is decidable, and zero traces was the shape of the field case. But
# absence alone over-fires: a first cut warned on "received, archived", on questions, and on
# letters citing a URL or a path — the very forms the size warning two lines up recommends.
# Cold review reproduced all of them. Two independent narrowings, neither semantic:
# - a floor: coordination replies and questions are short; a letter long enough to carry a
# load-bearing claim is not. CLAIMS_MIN is a coarse cut, not a validated threshold.
# - a trace vocabulary that matches what senders actually cite: file:line (rejecting all-digit
# left sides so 14:30 and 1:2 are not evidence, and known hosts so localhost:3000 is not),
# URLs, absolute paths, a backticked span containing a space (a command, not an inline
# identifier), or an explicit unverified marker.
# Still accepted, by design: a speculation-heavy letter carrying one real citation stays silent.
# Narrowing that further means classifying which sentences are claims — back to undecidable.
if [ "$bodylen" -ge "$CLAIMS_MIN" ] && ! printf '%s' "$body" | grep -qE "$CLAIMS_TRACE"; then
echo "reminder: no evidence trace found (no file:line, URL, path, command, or unverified/推测 marker) in a ${bodylen}-byte letter. Every factual claim about a system needs its source inline or an explicit guess marker — and say what you did NOT check. If a sentence has neither, verify it or cut it, then re-send." >&2
fi
# Maildir-style atomic delivery: compose fully in tmp/, then a same-fs rename into inbox/.
# There is no window where inbox/ can contain a half-written letter.
tmpf="$tmpd/$id.md"
cat > "$tmpf" <<EOF
---
id: $id
from: $from
to: $to
thread: $slug
re:
subject: $subject
priority: normal
---
EOF
[ -n "$body" ] && printf '%s\n' "$body" >> "$tmpf"
mv "$tmpf" "$dest"
echo "delivered $dest"
;;
archive)
id="${1:?agent-id}"; mid="${2:?letter-id}"
src="$BUS/$id/inbox/$mid.md"; [ -e "$src" ] || src="$BUS/$id/inbox/$mid"
[ -e "$src" ] || { echo "not found in $id inbox: $mid"; exit 1; }
mkdir -p "$BUS/$id/archive"
dst="$BUS/$id/archive/$(basename "$src")"
mv "$src" "$dst"
# gzip on archive (2026-07-10): a wide `grep -r` over the bus was pulling whole historical
# letter BODIES into context — a 979KB SQL letter got fully re-ingested this way by a routine
# sweep. Compressed, the id/filename stays visible via `ls`/`zgrep -l`; content only surfaces
# on an explicit `zcat`/`zgrep`, so a blind grep can no longer inhale megabytes of old mail.
gzip -9 -f "$dst"
echo "archived $(basename "$dst").gz"
# Opportunistic retention sweep: archiving is the natural moment the archive grows, so prune
# this seat's expired letters here (silent; a prune failure must never fail the archive).
prune_archive "$id" "$RETENTION_DAYS" >/dev/null 2>&1 || true
;;
prune)
id="${1:?agent-id}"; days="${2:-$RETENTION_DAYS}"
case "$days" in ''|*[!0-9]*) echo "invalid days: $days (positive integer required)" >&2; exit 1;; esac
n="$(prune_archive "$id" "$days")"
echo "pruned $n letter(s) older than $days days from $id archive"
;;
roster)
[ -f "$REG" ] && cat "$REG" || echo "(no registry yet — agentmail register <agent-id> <workdir> <focus>)"
;;
wire)
# Idempotent hook wiring — the LEVEL DECISION lives in code, not prose (two live onboard
# incidents 2026-07-30 came from prose ordering: duplicate mail hooks / scope spillover).
# Decision table (condition → action):
# user-level has any mail hook + --project → REFUSE (a project copy double-reports letters)
# user-level has any mail hook (no flag) → complete missing entries at USER level
# no mail hook anywhere + --project <abs> → wire that project's settings (config isolation)
# no mail hook anywhere (no flag) → wire USER level (resident orchestrator machine)
# Entries come from hooks.json (the wiring truth source) — commands become absolute install
# paths, no interpreter prefix. Merge is entry-level idempotent; writes are backup + atomic.
proj=""
if [ "${1:-}" = "--project" ]; then
proj="${2:?--project needs an absolute path}"
case "$proj" in /*) ;; *) echo "ERR: --project must be an absolute path, got: $proj" >&2; exit 1;; esac
[ -z "${3:-}" ] || { echo "ERR: surplus wire argument: $3 (usage: agentmail wire [--project <abs-path>])" >&2; exit 1; }
elif [ -n "${1:-}" ]; then
echo "ERR: unknown wire argument: $1 (usage: agentmail wire [--project <abs-path>])" >&2; exit 1
fi
# $0 may be the ~/.local/bin symlink (mail-check.py convenience install) — follow the
# link chain before dirname, else hooks.json is looked up beside the symlink.
SELF="$0"
while [ -L "$SELF" ]; do
link="$(readlink "$SELF")"
case "$link" in /*) SELF="$link" ;; *) SELF="$(dirname "$SELF")/$link" ;; esac
done
WIRE_PROJECT="$proj" WIRE_SELF="$(cd "$(dirname "$SELF")" && pwd -P)" python3 - <<'PYW'
import json, os, sys, tempfile, time
self_dir = os.environ["WIRE_SELF"]
proj = os.environ.get("WIRE_PROJECT", "")
hooks_src = json.load(open(os.path.join(self_dir, "hooks.json"), encoding="utf-8"))
user_path = os.path.join(os.path.expanduser("~"), ".claude", "settings.json")
MAIL_BASENAMES = {"mail-check.py", "mail-guard.py"}
def load(p):
return json.load(open(p, encoding="utf-8")) if os.path.exists(p) else {}
def is_mail_cmd(cmd):
# provenance = exact basename AND an 'agent-mail' path component (every install shape —
# skills/agent-mail, ~/.agents/skills/agent-mail — carries it). Three review probes set
# the fence posts (2026-07-30): substring '/x/not-mail-check.py-wrapper' must not match,
# prior install '/old/root/agent-mail/mail-check.py' must match, and a same-named
# UNRELATED tool '/opt/calendar/mail-check.py' must not match either.
p = os.path.normpath(str(cmd).strip())
return os.path.basename(p) in MAIL_BASENAMES and "agent-mail" in p.split(os.sep)
def has_mail_hook(cfg):
return any(is_mail_cmd(h.get("command", ""))
for groups in (cfg.get("hooks") or {}).values()
for g in groups or [] for h in (g.get("hooks") or []))
try:
user_cfg = load(user_path)
except Exception as e:
sys.stderr.write(f"ERR: cannot parse {user_path}: {e} — fix it first; refusing to touch it.\n")
sys.exit(1)
if has_mail_hook(user_cfg):
if proj:
sys.stderr.write("ERR: user-level settings already carry mail hooks — a project copy would "
"double-report every letter. Remove the user-level entries first if project "
"isolation is really wanted.\n")
sys.exit(1)
target, cfg = user_path, user_cfg
else:
target = os.path.join(proj, ".claude", "settings.json") if proj else user_path
try:
cfg = load(target)
except Exception as e:
sys.stderr.write(f"ERR: cannot parse {target}: {e} — fix it first; refusing to touch it.\n")
sys.exit(1)
hooks = cfg.setdefault("hooks", {})
added, present = [], []
for ev, entries in hooks_src.items():
if ev == "//":
continue
for e in entries:
cmd = os.path.join(self_dir, e["command"])
groups = hooks.setdefault(ev, [])
# presence = agent-mail provenance + same script: another install root counts as
# wired (adding ours would double-fire, review M1), while a same-named UNRELATED
# tool does not (ours must still be added beside it, review R2)
if any(is_mail_cmd(h.get("command", ""))
and os.path.basename(os.path.normpath(h.get("command", ""))) == os.path.basename(cmd)
for g in groups for h in (g.get("hooks") or [])):
present.append(f"{ev}:{os.path.basename(cmd)}")
continue
g = {"hooks": [{"type": "command", "command": cmd}]}
if "matcher" in e:
g["matcher"] = e["matcher"]
groups.append(g)
added.append(f"{ev}:{os.path.basename(cmd)}")
if not added:
print(f"already wired ({target}) — nothing to do")
sys.exit(0)
tdir = os.path.dirname(target)
os.makedirs(tdir, exist_ok=True)
if os.path.exists(target):
# O_EXCL: never write through a pre-planted file/symlink at the backup name
bak = f"{target}.bak-{time.strftime('%Y%m%d%H%M%S')}-{os.getpid()}"
fd = os.open(bak, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(open(target, encoding="utf-8").read())
fh.flush(); os.fsync(fh.fileno())
# mkstemp, not a predictable name: a pre-planted `settings.json.tmp` symlink turned the
# "atomic" write into an arbitrary-file clobber (review M2 live probe). Same-dir keeps
# os.replace an atomic same-filesystem rename; fsync file + dir for durability.
fd, tmp = tempfile.mkstemp(dir=tdir, prefix=".settings-wire-", suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(cfg, fh, ensure_ascii=False, indent=2)
fh.write("\n")
fh.flush(); os.fsync(fh.fileno())
os.replace(tmp, target)
except BaseException:
try: os.unlink(tmp)
except OSError: pass
raise
dfd = os.open(tdir, os.O_RDONLY)
try: os.fsync(dfd)
finally: os.close(dfd)
print(f"wired {len(added)} entry(ies) at {'project' if proj else 'user'} level → {target}")
for a in added:
print(f" + {a}")
for s in present:
print(f" = {s} (already present)")
print("verify: AGENT_MAIL_SELF=<seat-id> trigger once — letters surface, empty inbox stays silent")
PYW
;;
*) usage; [ -z "$cmd" ] || exit 1;;
esac
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |