The parser cuts a trailing ```notify JSON block out of a main-thread assistant message (closing_notify.split) and keeps it on the thread item (notify) and the summary (closingNotify); the indexer hands it to notifications/closing.maybe_push, which pushes it once — id from the block's time and words, skipped when already logged or older than 15 min — with final: true and the CLI's cost line rebuilt from the summary. The push now leaves once the message it announces is in the transcript, instead of ~11 s (p90 24 s) before it, and the closing tool call (one full-context request) is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
108 lines
4.0 KiB
Python
108 lines
4.0 KiB
Python
"""Push the ```notify block a run ended its final message on — once.
|
|
|
|
The parser finds the block (``conversations/closing_notify.py``) and the
|
|
indexer calls :func:`maybe_push` with the transcript's summary every time it
|
|
re-parses it. So the push goes out as soon as the message that carries it is
|
|
in the transcript — never before it, as the closing ``notify-done`` call did —
|
|
and it is the run's closing push: ``final`` (the session reads finished once
|
|
its turn ends) and the cost line the CLI used to add, priced by the hub.
|
|
|
|
Once means: the id is minted from the block's time and words (a fork or a
|
|
resumed copy of the transcript carries the same record, so the same id), a
|
|
block already in the notification log is skipped, and a block older than
|
|
``MAX_AGE_S`` is never pushed — a re-index after a deploy or a newly paired
|
|
worker's history must not replay old pushes.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import hashlib
|
|
import logging
|
|
import threading
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
MAX_AGE_S = 15 * 60
|
|
|
|
_lock = threading.Lock()
|
|
_seen: set[str] = set()
|
|
|
|
_HARNESS = {"opencode": "OpenCode", "agy": "Antigravity", "pi": "pi"}
|
|
|
|
|
|
def push_id(block: dict) -> str:
|
|
key = "\x1f".join(block.get(k) or "" for k in ("at", "title", "message"))
|
|
return "ntf_" + hashlib.sha1(key.encode()).hexdigest()[:12]
|
|
|
|
|
|
def _ts(s: str | None) -> datetime.datetime | None:
|
|
try:
|
|
return datetime.datetime.fromisoformat((s or "").replace("Z", "+00:00"))
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def _tokens(n: int) -> str:
|
|
return (f"{n / 1e6:.1f}M tokens" if n >= 1_000_000
|
|
else f"{n // 1000}k tokens" if n >= 1000 else f"{n} tokens")
|
|
|
|
|
|
def _duration(start: str | None, end: str | None) -> str:
|
|
a, b = _ts(start), _ts(end)
|
|
if not a or not b or b <= a:
|
|
return ""
|
|
m, s = divmod(int((b - a).total_seconds()), 60)
|
|
h, m = divmod(m, 60)
|
|
return f"{h}h {m}m {s}s" if h else (f"{m}m {s}s" if m else f"{s}s")
|
|
|
|
|
|
def cost_line(summary: dict, at: str) -> str:
|
|
"""``Claude Code · $1.57 · 78k tokens · 8m 38s`` — the line the notify CLI
|
|
appended; ``restate_cost`` then prices it on the whole run (subagents
|
|
included) and adds the share of the plan's week."""
|
|
line = (f"{_HARNESS.get(summary.get('harness') or '', 'Claude Code')}"
|
|
f" · ${float(summary.get('cost') or 0):.2f}")
|
|
if summary.get("tokens"):
|
|
line += f" · {_tokens(int(summary['tokens']))}"
|
|
dur = _duration(summary.get("startedAt"), at)
|
|
return line + (f" · {dur}" if dur else "")
|
|
|
|
|
|
def due(block: dict, now: datetime.datetime | None = None) -> bool:
|
|
"""Recent enough to push (and has a time at all)."""
|
|
at = _ts(block.get("at"))
|
|
now = now or datetime.datetime.now(datetime.timezone.utc)
|
|
return at is not None and abs((now - at).total_seconds()) <= MAX_AGE_S
|
|
|
|
|
|
def maybe_push(deps, summary: dict, block: dict) -> str | None:
|
|
"""Push ``block`` for the session behind ``summary`` unless it went out
|
|
already or is too old. Returns the push id when it starts one."""
|
|
sid = (summary.get("sessionId") or "").strip()
|
|
if not sid or summary.get("isSidechain"):
|
|
return None
|
|
nid = push_id(block)
|
|
with _lock:
|
|
if nid in _seen:
|
|
return None
|
|
_seen.add(nid)
|
|
if not due(block) or deps.notify_store.get(nid):
|
|
return None
|
|
message = block.get("message") or ""
|
|
line = cost_line(summary, block.get("at") or "")
|
|
d = {"id": nid, "sessionId": sid, "final": True,
|
|
"title": block.get("title") or "Claude Code",
|
|
"message": f"{message}\n{line}" if message else line,
|
|
**{k: block[k] for k in ("type", "url", "image", "spoken") if block.get(k)}}
|
|
from notifications.service import _create_notify
|
|
|
|
def run():
|
|
try:
|
|
_create_notify(deps, d)
|
|
except Exception:
|
|
log.exception("closing push %s failed", nid)
|
|
with _lock:
|
|
_seen.discard(nid) # the next re-parse retries it
|
|
threading.Thread(target=run, daemon=True, name="closing-push").start()
|
|
return nid
|