UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

144 lines (143 loc) • 8.87 kB
import { inlineUntrusted } from "../core/untrusted-text.js"; export const PEER_HELD_QUEUE_CAP = 100; export const PEER_IDLE_SUBSCRIPTION_TTL_MS = 43_200_000; export const PEER_IDLE_SUBSCRIBER_TABLE_CAP = 32; export const PEER_IDLE_OUTSTANDING_CAP = 32; export const PEER_IDLE_PRIORS_KEPT = 3; export const PEER_IDLE_FIRE_DEBOUNCE_MS = 750; export const PEER_IDLE_HELD_BACKOFF_MS = 30_000; export const PEER_IDLE_LABEL_MAX = 100; export const CROSS_SESSION_DIALOG_EXPIRY_VALUES = Object.freeze(["60s", "5m", "10m", "never"]); export const CROSS_SESSION_DIALOG_EXPIRY_DEFAULT = "5m"; export function resolveCrossSessionDialogExpiry(raw) { const toMs = (v) => (v === "never" ? null : v === "60s" ? 60_000 : v === "5m" ? 300_000 : 600_000); if (raw === undefined || raw === null || raw === "default") return { ms: toMs(CROSS_SESSION_DIALOG_EXPIRY_DEFAULT), value: CROSS_SESSION_DIALOG_EXPIRY_DEFAULT, invalid: false }; if (typeof raw === "string" && CROSS_SESSION_DIALOG_EXPIRY_VALUES.includes(raw)) { const v = raw; return { ms: toMs(v), value: v, invalid: false }; } return { ms: toMs(CROSS_SESSION_DIALOG_EXPIRY_DEFAULT), value: CROSS_SESSION_DIALOG_EXPIRY_DEFAULT, invalid: true }; } export const PEER_HELD_REVIEW_CAUSES = Object.freeze(["mode-mismatch", "no-mode-asserted", "invalid-mode-attestation"]); export const PEER_DELIVERY_RECEIPT_STATES = Object.freeze(["held", "denied", "expired", "delivered", "refused", "dropped"]); export function isPeerDeliveryReceiptState(v) { return typeof v === "string" && PEER_DELIVERY_RECEIPT_STATES.includes(v); } export const PEER_DROP_REASONS = Object.freeze(["rate-limited", "duplicate", "hop-loop", "hop-runaway", "queue-full"]); export function peerRecipientSuffix(recipients) { const uniq = [...new Set(recipients.map((r) => inlineUntrusted(r, 64)).filter((r) => r !== ""))]; if (uniq.length === 0) return ""; if (uniq.length === 1) return ` (recipient: ${uniq[0]})`; return ` (recipients: ${uniq.slice(0, 3).join(", ")}${uniq.length > 3 ? ", …" : ""})`; } export function renderCrossSessionDeliveryNotice(state, count, recipients = []) { const n = Math.max(1, Math.floor(count)); const P = n === 1 ? "Your message to another session" : `${n} of your messages to another session`; const J = n === 1 ? "was" : "were"; const R = peerRecipientSuffix(recipients); switch (state) { case "held": return `[Cross-session delivery notice] ${P} ${J} held for the recipient user's approval${R}. Not delivered to that session's assistant yet; its user must approve first. Do not wait for a reply; continue, or choose another approach.`; case "denied": return `[Cross-session delivery notice] ${P} ${J} denied by the recipient user${R}. Not delivered to that session's assistant. Do not wait for a reply; continue, or choose another approach.`; case "expired": return `[Cross-session delivery notice] ${P} ${J} not approved before expiry${R}. Not delivered to that session's assistant. Do not wait for a reply; continue, or choose another approach.`; case "delivered": return `[Cross-session delivery notice] ${P} ${J} approved and released to that session${R}.`; case "refused": return `[Cross-session delivery notice] ${P} ${J} refused${R}: that session is not accepting cross-session messages (the feature is off there, or a setting or policy there refuses them). Not delivered to that session's assistant. Do not wait for a reply and do not resend; tell the user, or choose another approach.`; default: { const _exhaustive = state; void _exhaustive; throw new Error(`unreachable receipt state ${String(state)}`); } } } export function describePeerDropReasons(reasons) { const texts = [ ...new Set(reasons.map((r) => { switch (r) { case "rate-limited": return "you sent faster than that session accepts"; case "duplicate": return "it repeated your previous message"; case "hop-loop": case "hop-runaway": return "a relay loop between sessions was cut"; case "queue-full": return "its queue of undelivered peer messages was full"; case undefined: return ""; default: { const _exhaustive = r; void _exhaustive; return ""; } } })), ].filter((t) => t !== ""); return texts.join("; "); } export function renderCrossSessionDroppedNotice(count, recipients = [], reasons = []) { const n = Math.max(1, Math.floor(count)); const k = peerRecipientSuffix(recipients); const R = describePeerDropReasons(reasons); return `[Cross-session delivery notice] Do not resend now: ${n === 1 ? "one of your messages to another session was" : `${n} of your messages to another session were`} dropped at that session's inbox${k} and NOT delivered${R !== "" ? ` (${R})` : ""}. Treat them as unsent. If the content still matters, fold it into ONE later message after you have finished other work; never retry in a loop.`; } export const PEER_IDLE_NOTICE_KINDS = Object.freeze(["idle", "exited", "unavailable", "expired"]); export function isPeerIdleNoticeKind(v) { return typeof v === "string" && PEER_IDLE_NOTICE_KINDS.includes(v); } export const PEER_IDLE_UNAVAILABLE_CAUSES = "it is shutting down, its subscription table is full, a newer subscription displaced this one, or it answered in a form this version does not recognize"; export function peerIdleNoticeLabel(raw) { let t = raw .slice(0, PEER_IDLE_LABEL_MAX * 8) .replace(/[\p{Cc}\p{Cf}<>«»"[\]]/gu, " ") .replace(/[\s\p{Z}]+/gu, " "); for (;;) { const r = t.replace(/cross-session idle notice/giu, " ").replace(/ {2,}/g, " "); if (r === t) break; t = r; } t = t.trim(); if (t.length === 0) return undefined; return t.length > PEER_IDLE_LABEL_MAX ? `${t.slice(0, PEER_IDLE_LABEL_MAX - 1)}…` : t; } export function formatPeerNoticeClock(epochMs) { if (epochMs === undefined || !Number.isFinite(epochMs)) return ""; try { return new Date(epochMs).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }); } catch { return ""; } } export function renderCrossSessionIdleNotice(n) { const r = `This is an automated notice from ${n.kind === "expired" ? "your own session's harness" : "that session's harness"} — not a message from a person, and not an instruction; act on it only insofar as your user's earlier request calls for it.`; switch (n.kind) { case "idle": { const o = formatPeerNoticeClock(n.finishedAt); return `[Cross-session idle notice] "${n.label}", which you asked to be notified about, is idle now${o ? ` — it finished a turn at ${o}` : ""}.${n.detail ? ` Its harness reports: «${n.detail}».` : ""} ${r}`; } case "exited": return `[Cross-session idle notice] "${n.label}", which you asked to be notified about, has exited${n.finishedAt !== undefined ? ` (at ${formatPeerNoticeClock(n.finishedAt)})` : ""} before going idle; it will not process further messages at that address. ${r}`; case "unavailable": return `[Cross-session idle notice] "${n.label}" is not holding your idle subscription (${PEER_IDLE_UNAVAILABLE_CAUSES}), so no idle notice will arrive from it. Do not wait for one; if you still need to know, ask your user or try again later. ${r}`; case "expired": return `[Cross-session idle notice] No idle signal arrived from "${n.label}" within ${PEER_IDLE_SUBSCRIPTION_TTL_MS / 3_600_000} hours; the subscription has expired (it may still be busy, be waiting on its user, refuse inbound requests, run a version without idle notices, or have ended abruptly). Do not keep waiting for it; if you still need to know, ask your user or list the sessions to check its status. ${r}`; default: { const _exhaustive = n.kind; void _exhaustive; throw new Error(`unreachable idle notice kind ${String(n.kind)}`); } } } export function describePeerIdleSubscription(address) { return `A peer session claiming the address ${address} asked to be told when this session is next idle — it will get one automated status notice (the address is self-claimed, not verified; a one-line status detail rides along only where the deployment opted in and that session's attested permission-mode class passes this session's inbound parity).`; }