This commit is contained in:
Timothy Jaeryang Baek committed 2026-07-06 16:30:22 -05:00
1 parent 8d28277288
commit 2a957a39dc
6 files changed
+323 -63

No files matched your search

+204 -7
View File
@@ -1,26 +1,223 @@
"""Application event definitions."""
"""Application event definitions and internal event bus."""
from __future__ import annotations
from dataclasses import dataclass
import logging
import time
import uuid
from dataclasses import asdict, dataclass, field
from importlib.metadata import PackageNotFoundError, version as package_version
from typing import Any
logger = logging.getLogger(__name__)
MAX_STRING_LENGTH = 1000
@dataclass(frozen=True)
class EventDefinition:
name: str
label: str
description: str | None = None
message: str | None = None
@property
def label(self) -> str:
return self.message or self.name.replace(".", " ").replace("_", " ").title()
class EventDefinitions:
CHAT_FINISHED = EventDefinition("chat.finished", "Chat finished")
CHAT_FAILED = EventDefinition("chat.failed", "Chat failed")
NOTIFICATION_TEST = EventDefinition("notification.test", "Test notification")
NOTIFICATION_MANUAL = EventDefinition("manual.notify", "Notification")
CHAT_FINISHED = EventDefinition(
"chat.finished",
"A chat run finished successfully.",
"Chat finished",
)
CHAT_FAILED = EventDefinition(
"chat.failed",
"A chat run failed.",
"Chat failed",
)
NOTIFICATION_TEST = EventDefinition(
"notification.test",
"A notification target test was sent.",
"Test notification",
)
NOTIFICATION_MANUAL = EventDefinition(
"manual.notify",
"A manual notification was sent.",
"Notification",
)
EVENTS = EventDefinitions()
EVENT_DEFINITIONS = tuple(
value for value in vars(EventDefinitions).values() if isinstance(value, EventDefinition)
)
EVENT_DEFINITIONS_BY_NAME = {definition.name: definition for definition in EVENT_DEFINITIONS}
EVENT_CATALOG = tuple(definition.name for definition in EVENT_DEFINITIONS)
EVENT_CATALOG_SET = set(EVENT_CATALOG)
CHAT_NOTIFICATION_EVENTS = (
EVENTS.CHAT_FINISHED,
EVENTS.CHAT_FAILED,
)
SENSITIVE_KEYS = {
"password",
"hashed_password",
"token",
"access_token",
"refresh_token",
"id_token",
"api_key",
"secret",
"key",
"authorization",
"cookie",
"webhook_token",
}
SAFE_ACTOR_FIELDS = ("id", "name", "email", "role", "created_at", "updated_at")
@dataclass
class Event:
schema: str
id: str
event: str
resource: str
operation: str
created_at: int
source: str
actor: dict[str, Any] | None = None
subject: dict[str, Any] | None = None
data: dict[str, Any] = field(default_factory=dict)
message: str | None = None
def model_dump(self) -> dict[str, Any]:
return asdict(self)
def _sanitize(value: Any) -> Any:
if hasattr(value, "model_dump"):
value = value.model_dump()
if isinstance(value, dict):
sanitized = {}
for key, item in value.items():
normalized = str(key).lower().replace("-", "_")
if (
normalized in SENSITIVE_KEYS
or normalized.endswith("_token")
or normalized.endswith("_secret")
or normalized.endswith("_api_key")
or normalized.endswith("_key")
):
continue
sanitized[key] = _sanitize(item)
return sanitized
if isinstance(value, (list, tuple, set)):
return [_sanitize(item) for item in value]
if isinstance(value, str) and len(value) > MAX_STRING_LENGTH:
return f"{value[:MAX_STRING_LENGTH]}..."
return value
def build_event(
event: EventDefinition | str,
*,
actor: Any | None = None,
subject_id: Any | None = None,
subject_type: str | None = None,
source: str = "api",
data: dict | None = None,
message: str | None = None,
) -> Event:
event_name_value = event.name if isinstance(event, EventDefinition) else str(event)
if event_name_value not in EVENT_CATALOG_SET:
raise ValueError(f"Unknown event: {event_name_value}")
parts = event_name_value.split(".")
resource = ".".join(parts[:-1])
subject = (
{"type": subject_type or resource, "id": subject_id}
if subject_id is not None or subject_type is not None
else None
)
actor = _sanitize(actor)
actor_payload = None
if actor:
get = actor.get if isinstance(actor, dict) else lambda key: getattr(actor, key, None)
actor_payload = {field: get(field) for field in SAFE_ACTOR_FIELDS if get(field) is not None}
if actor_payload:
actor_payload["type"] = get("type") or "user"
try:
schema = package_version("cptr")
except PackageNotFoundError:
schema = "dev"
return Event(
schema=schema,
id=str(uuid.uuid4()),
event=event_name_value,
resource=resource,
operation=parts[-1],
created_at=int(time.time()),
source=source,
actor=actor_payload,
subject=_sanitize(subject) if subject else None,
data=_sanitize(data or {}),
message=message,
)
def get_event_catalog() -> list[dict[str, str]]:
return [
{
"event": definition.name,
"label": definition.label,
"description": definition.description or "",
}
for definition in EVENT_DEFINITIONS
]
class NotificationEventSink:
async def handle_event(self, event: Event) -> None:
from cptr.utils.notifications import dispatch_notification_event
await dispatch_notification_event(event)
EVENT_SINKS = [NotificationEventSink()]
async def publish_event(
event: EventDefinition | str,
*,
actor: Any | None = None,
subject_id: Any | None = None,
subject_type: str | None = None,
source: str = "api",
data: dict | None = None,
message: str | None = None,
) -> Event:
event_payload = build_event(
event,
actor=actor,
subject_id=subject_id,
subject_type=subject_type,
source=source,
data=data,
message=message,
)
for sink in EVENT_SINKS:
try:
await sink.handle_event(event_payload)
except Exception:
logger.exception("Event sink failed for %s", event_payload.event)
return event_payload
@@ -10,6 +10,12 @@ export type ChatNotificationEvent =
export type NotificationDelivery = 'away' | 'always';
export type NotificationTargetType = 'webhook' | 'bot';
export interface NotificationEventOption {
event: ChatNotificationEvent;
label: string;
description: string;
}
export interface NotificationTarget {
id: string;
type: NotificationTargetType;
@@ -47,6 +53,11 @@ export async function listNotificationTargets(): Promise<NotificationTarget[]> {
return data.targets;
}
export async function listNotificationEvents(): Promise<NotificationEventOption[]> {
const data = await fetchJSON<{ events: NotificationEventOption[] }>('/api/notifications/events');
return data.events;
}
export function createNotificationTarget(payload: NotificationTargetPayload) {
return fetchJSON<NotificationTarget>('/api/notifications/targets', jsonBody(payload));
}
@@ -8,11 +8,13 @@
CHAT_NOTIFICATION_EVENTS,
deleteNotificationTarget,
listNotificationBotOptions,
listNotificationEvents,
listNotificationTargets,
testNotificationTarget,
updateNotificationTarget,
type BotOption,
type ChatNotificationEvent,
type NotificationEventOption,
type NotificationDelivery,
type NotificationTarget,
type NotificationTargetType
@@ -21,12 +23,21 @@
import Modal from '../Modal.svelte';
import ToggleSwitch from '../common/ToggleSwitch.svelte';
const eventOptions: { value: ChatNotificationEvent; label: string }[] = [
{ value: CHAT_NOTIFICATION_EVENTS.FINISHED, label: 'general.chatFinished' },
{ value: CHAT_NOTIFICATION_EVENTS.FAILED, label: 'general.chatFailed' }
const fallbackEventOptions: NotificationEventOption[] = [
{
event: CHAT_NOTIFICATION_EVENTS.FINISHED,
label: 'Chat finished',
description: 'A chat run finished successfully.'
},
{
event: CHAT_NOTIFICATION_EVENTS.FAILED,
label: 'Chat failed',
description: 'A chat run failed.'
}
];
let targets = $state<NotificationTarget[]>([]);
let eventOptions = $state<NotificationEventOption[]>(fallbackEventOptions);
let botOptions = $state<BotOption[]>([]);
let loadingTargets = $state(false);
let savingTarget = $state(false);
@@ -53,12 +64,14 @@
async function loadNotificationTargets() {
loadingTargets = true;
try {
const [nextTargets, bots] = await Promise.all([
const [nextTargets, bots, events] = await Promise.all([
listNotificationTargets(),
listNotificationBotOptions()
listNotificationBotOptions(),
listNotificationEvents()
]);
targets = nextTargets;
botOptions = bots;
eventOptions = events.length ? events : fallbackEventOptions;
} catch {
toast.error($t('general.notificationTargetsLoadFailed'));
} finally {
@@ -256,15 +269,15 @@
</div>
{#if target.events.length}
<div class="flex flex-wrap gap-1">
{#each eventOptions.filter((event) => target.events.includes(event.value)) as event}
{#each eventOptions.filter((event) => target.events.includes(event.event)) as event}
<button
class="h-6 rounded-md bg-gray-200/60 px-2 text-[0.6875rem] text-gray-900 transition-colors hover:bg-gray-200 dark:bg-white/10 dark:text-white dark:hover:bg-white/15"
onclick={() =>
patchTarget(target, {
events: target.events.filter((item) => item !== event.value)
events: target.events.filter((item) => item !== event.event)
})}
>
{$t(event.label)}
{event.label}
</button>
{/each}
</div>
@@ -407,12 +420,12 @@
{#each eventOptions as event}
<button
class="h-6 rounded-md px-2 text-[0.6875rem] transition-colors
{form.events.includes(event.value)
{form.events.includes(event.event)
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
onclick={() => toggleFormEvent(event.value)}
onclick={() => toggleFormEvent(event.event)}
>
{$t(event.label)}
{event.label}
</button>
{/each}
</div>
+7
View File
@@ -9,6 +9,7 @@ from cptr.utils.notifications import (
NotificationError,
create_target,
delete_target,
get_notification_event_catalog,
get_bot_options,
list_targets,
test_target,
@@ -51,6 +52,12 @@ async def api_list_targets(request: Request):
return {"targets": await list_targets(_user_id(request))}
@router.get("/events")
async def api_list_events(request: Request):
_user_id(request)
return {"events": get_notification_event_catalog()}
@router.post("/targets")
async def api_create_target(request: Request, body: TargetPayload):
try:
+18 -17
View File
@@ -11,7 +11,7 @@ import logging
import re
import uuid
from cptr.events import EVENTS
from cptr.events import EVENTS, publish_event
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS
from cptr.utils.context import resolve_compact_token_threshold, should_compact
from cptr.utils.skills import discover_skills, load_skill, format_skill_content
@@ -1183,25 +1183,26 @@ async def run_chat_task(
workspace_name=ws_name,
)
async def _notify_chat(event: str, message: str | None = None):
async def _publish_chat_event(event, message: str | None = None):
try:
from cptr.utils.notifications import EVENT_LABELS, send_chat_event
ws_name = workspace.rstrip("/").rsplit("/", 1)[-1] if workspace else ""
body = message if message is not None else content
await send_chat_event(
user_id,
preview = body[:300] if body else ""
await publish_event(
event,
{
"title": EVENT_LABELS.get(event, "Chat"),
"message": body[:300] if body else "",
"chat_id": chat_id,
actor={"id": user_id},
subject_id=chat_id,
subject_type="chat",
source="chat_task",
data={
"workspace": {"id": workspace, "name": ws_name} if workspace else None,
"preview": preview,
},
message=preview,
)
except Exception:
logger.debug(
"[notifications] Error sending chat notification for %s", chat_id[:8], exc_info=True
"[events] Error publishing chat event for %s", chat_id[:8], exc_info=True
)
# Load existing state so continuations don't overwrite previous output
@@ -1517,7 +1518,7 @@ async def run_chat_task(
)
_task_state.pop(message_id, None)
await _emit_done()
await _notify_chat(EVENTS.CHAT_FINISHED.name)
await _publish_chat_event(EVENTS.CHAT_FINISHED)
return
flushed_item = _flush_text()
@@ -1526,7 +1527,7 @@ async def run_chat_task(
await _save_message("agent stream ended", content=content, output=output_items, done=True)
_task_state.pop(message_id, None)
await _emit_done()
await _notify_chat(EVENTS.CHAT_FINISHED.name)
await _publish_chat_event(EVENTS.CHAT_FINISHED)
return
try:
@@ -1821,7 +1822,7 @@ async def run_chat_task(
)
_task_state.pop(message_id, None)
await _emit_done()
await _notify_chat(EVENTS.CHAT_FINISHED.name)
await _publish_chat_event(EVENTS.CHAT_FINISHED)
return
# ── Process collected tool calls ────────────────────
@@ -2038,7 +2039,7 @@ async def run_chat_task(
)
_task_state.pop(message_id, None)
await _emit_done()
await _notify_chat(EVENTS.CHAT_FINISHED.name)
await _publish_chat_event(EVENTS.CHAT_FINISHED)
return
# Max iterations reached
@@ -2051,7 +2052,7 @@ async def run_chat_task(
)
_task_state.pop(message_id, None)
await _emit_done()
await _notify_chat(EVENTS.CHAT_FAILED.name, "Max iterations reached.")
await _publish_chat_event(EVENTS.CHAT_FAILED, "Max iterations reached.")
except asyncio.CancelledError:
_flush_text()
@@ -2093,7 +2094,7 @@ async def run_chat_task(
)
_task_state.pop(message_id, None)
await emit(done=True, error=error_msg)
await _notify_chat(EVENTS.CHAT_FAILED.name, error_msg)
await _publish_chat_event(EVENTS.CHAT_FAILED, error_msg)
finally:
# Guarantee the gateway SSE stream terminates. If emit()
# already pushed a done/error event the sentinel is harmless
+59 -28
View File
@@ -10,7 +10,7 @@ from urllib.parse import urlparse
import httpx
from cptr.events import CHAT_NOTIFICATION_EVENTS, EVENTS
from cptr.events import CHAT_NOTIFICATION_EVENTS, EVENT_DEFINITIONS_BY_NAME, EVENTS, Event
from cptr.models import UserStates
from cptr.socket.main import is_user_active
@@ -20,8 +20,6 @@ VALID_EVENTS = {event.name for event in CHAT_NOTIFICATION_EVENTS}
VALID_TYPES = {"webhook", "bot"}
VALID_DELIVERY = {"away", "always"}
EVENT_LABELS = {event.name: event.label for event in CHAT_NOTIFICATION_EVENTS}
class NotificationError(ValueError):
pass
@@ -330,32 +328,65 @@ async def test_target(user_id: str, target_id: str) -> dict:
return {"ok": True}
async def send_chat_event(user_id: str, event: str, context: dict) -> None:
if event not in VALID_EVENTS:
def get_notification_event_catalog() -> list[dict[str, str]]:
return [
{
"event": event.name,
"label": event.label,
"description": event.description or "",
}
for event in CHAT_NOTIFICATION_EVENTS
]
async def dispatch_notification_event(event: Event) -> None:
if event.event not in VALID_EVENTS:
return
data = await _state(user_id)
active = is_user_active(user_id)
for target in list(_targets(data)):
if not target.get("enabled", True):
continue
if event not in target.get("events", []):
continue
if target.get("delivery", "away") == "away" and active:
continue
try:
await _deliver(
target,
event,
str(context.get("title") or EVENT_LABELS[event]),
str(context.get("message") or ""),
{**context, "user_id": user_id},
)
except Exception:
logger.exception(
"[notifications] failed to deliver %s to %s",
event,
target.get("id"),
)
definition = EVENT_DEFINITIONS_BY_NAME[event.event]
actor = event.actor or {}
subject = event.subject or {}
event_data = event.data or {}
user_ids = set()
if actor.get("id"):
user_ids.add(str(actor["id"]))
if subject.get("type") == "user" and subject.get("id"):
user_ids.add(str(subject["id"]))
if event_data.get("user_id"):
user_ids.add(str(event_data["user_id"]))
for user_id in event_data.get("user_ids") or []:
if user_id:
user_ids.add(str(user_id))
message = str(event.message or event_data.get("preview") or event_data.get("message") or "")
chat_id = event_data.get("chat_id") or (
subject.get("id") if subject.get("type") == "chat" else None
)
workspace = event_data.get("workspace")
for user_id in user_ids:
data = await _state(user_id)
active = is_user_active(user_id)
for target in list(_targets(data)):
if not target.get("enabled", True):
continue
if event.event not in target.get("events", []):
continue
if target.get("delivery", "away") == "away" and active:
continue
try:
await _deliver(
target,
event.event,
definition.label,
message,
{"chat_id": chat_id, "workspace": workspace, "user_id": user_id},
)
except Exception:
logger.exception(
"[notifications] failed to deliver %s to %s",
event.event,
target.get("id"),
)
async def notify_target(