UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

47 lines (46 loc) • 2.88 kB
import { MAILBOX_TOMBSTONED_RECIPIENT_CODE } from "../core/mailbox-store.js"; import { peerSessionBoxHandle } from "./peer-directory.js"; import { peerIdleNoticeLabel, renderCrossSessionDeliveryNotice, renderCrossSessionDroppedNotice, renderCrossSessionIdleNotice } from "./peer-notices.js"; function noticeMeta(route, kind, notice) { const modeClass = route.self.modeClass?.(); return { fromSession: route.self.sessionId, ...(modeClass === "bypass" || modeClass === "prompting" ? { fromMode: modeClass } : {}), kind, notice, }; } async function appendNotice(route, toSession, content, peerMeta, classification) { try { await route.mailbox.append(route.scope, peerSessionBoxHandle(toSession), { from: route.self.name ?? peerSessionBoxHandle(route.self.sessionId), content, sentAt: (route.now ?? Date.now)(), hopChain: [], peerMeta, }); return true; } catch (e) { if (e?.code !== MAILBOX_TOMBSTONED_RECIPIENT_CODE) { route.onError?.(e, { phase: "degraded", sessionId: route.self.sessionId, classification }); } return false; } } export function routePeerDeliveryReceipt(route, toSession, state, refSeq) { const recipient = route.self.name ?? peerSessionBoxHandle(route.self.sessionId); const notice = { state, refSeq, recipient }; return appendNotice(route, toSession, renderCrossSessionDeliveryNotice(state, 1, [recipient]), noticeMeta(route, "delivery_notice", notice), "peer-receipt-route"); } export function routePeerDroppedReceipt(route, toSession, refSeq, dropReason) { const recipient = route.self.name ?? peerSessionBoxHandle(route.self.sessionId); const notice = { state: "dropped", refSeq, recipient, ...(dropReason !== undefined ? { dropReason } : {}) }; return appendNotice(route, toSession, renderCrossSessionDroppedNotice(1, [recipient], [dropReason]), noticeMeta(route, "delivery_notice", notice), "peer-receipt-route"); } export function routePeerIdleNotice(route, toSession, notice) { const detail = notice.detail !== undefined ? peerIdleNoticeLabel(notice.detail) : undefined; const label = notice.label ?? peerIdleNoticeLabel(route.self.name ?? peerSessionBoxHandle(route.self.sessionId)) ?? peerSessionBoxHandle(route.self.sessionId); const meta = { state: notice.kind, ...(notice.finishedAt !== undefined ? { finishedAt: notice.finishedAt } : {}), ...(detail !== undefined ? { detail } : {}), ...(notice.kind === "expired" ? { target: label } : {}) }; return appendNotice(route, toSession, renderCrossSessionIdleNotice({ kind: notice.kind, label, ...(notice.finishedAt !== undefined ? { finishedAt: notice.finishedAt } : {}), ...(detail !== undefined ? { detail } : {}) }), noticeMeta(route, "idle_notice", meta), "peer-idle-route"); }