Hermes has a first-class "home channel": the default destination for output nobody asked for at a specific address — a cron result, an agent-initiated `send_message`, a gateway lifecycle notice, a `/handoff`. The T3 plugin opted out, suppressing Hermes' "Type /sethome" nudge without designating anything. A cron job with `deliver=t3` went nowhere, `send_message` to a bare `t3` target errored, and `/handoff t3` hard-failed. Each enrolled instance now gets one Home thread, pinned first in its agent project, fully conversational, undeletable, created automatically. Protocol v3. `connection.hello` gains `role: "gateway" | "delivery"`; `connection.accepted` carries `homeThreadId`. Two new frames: `home.deliver` and `home.deliver.ack`. Designation converges on read, like agent projects — a precondition every handshake runs rather than an event one caller owns, so an instance enrolled before this shipped, or one whose thread creation failed once, heals on the next connect. It lives in the instance's settings blob beside `connectorUrl` and `revoked`; the plugin's `T3_HOME_CHANNEL` is a cache of it, reconciled every handshake. The existence check deliberately ignores archive state. Every other thread read filters `archived_at IS NULL`, which is right for "what should the user see" and wrong for "does this row exist" — an archived Home read as deleted and the self-healing path replaced it, stranding the history in a thread the user had merely parked. A delivery to an archived Home now un-archives it, the same way incoming activity wakes a settled or snoozed thread. Deliveries bypass the turn machinery entirely. One may arrive while the home thread has a live user turn, so it appends as a turnless assistant message carrying `notification` provenance rather than joining the turn — attributing it would fold it away behind that turn's "Worked for …". Everything except a lifecycle notice un-settles the thread and pushes; lifecycle notices land quietly. Idempotency is load-bearing, because the plugin's durable queue retries anything it has not seen acked. T3 dedupes on `deliveryId` against `projection_thread_messages` before dispatching — the decider's own scan sees the in-memory read model, which is built with `messages: []`, so it cannot catch a replay after a restart. The ack is sent only after the write lands. An out-of-process cron run dials in with `role: "delivery"`: authenticated identically, but never registered as the instance's primary connection, so it cannot displace a live gateway socket or answer its pending requests. Plugin side, the proactive branch in `send()` gates on provenance rather than turn absence. The naive rule — "no active turn, so deliver" — would let a notify-stamped cron delivery complete a user's live turn with cron output as its answer. A bare session-key mismatch is not enough either, since `HERMES_SESSION_KEY` resolves empty whenever the context did not propagate; that would tear a genuine reply out of its turn. Bypassing a live turn requires positively identified cron/lifecycle/handoff provenance. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
203 lines
6.3 KiB
TypeScript
203 lines
6.3 KiB
TypeScript
import type {
|
|
EnvironmentId,
|
|
OrchestrationProjectShell,
|
|
OrchestrationThreadShell,
|
|
ThreadId,
|
|
} from "@t3tools/contracts";
|
|
|
|
export type AgentAwarenessPhase =
|
|
| "starting"
|
|
| "running"
|
|
| "waiting_for_approval"
|
|
| "waiting_for_input"
|
|
| "notification"
|
|
| "completed"
|
|
| "failed"
|
|
| "stale";
|
|
|
|
export interface AgentAwarenessState {
|
|
readonly environmentId: EnvironmentId;
|
|
readonly threadId: ThreadId;
|
|
readonly projectTitle: string;
|
|
readonly threadTitle: string;
|
|
readonly phase: AgentAwarenessPhase;
|
|
readonly headline: string;
|
|
readonly detail?: string;
|
|
readonly modelTitle: string;
|
|
readonly updatedAt: string;
|
|
readonly deepLink: string;
|
|
}
|
|
|
|
export interface ProjectThreadAwarenessInput {
|
|
readonly environmentId: EnvironmentId;
|
|
readonly project: Pick<OrchestrationProjectShell, "title">;
|
|
readonly thread: Pick<
|
|
OrchestrationThreadShell,
|
|
| "id"
|
|
| "title"
|
|
| "modelSelection"
|
|
| "session"
|
|
| "latestTurn"
|
|
| "updatedAt"
|
|
| "hasPendingApprovals"
|
|
| "hasPendingUserInput"
|
|
| "latestNotification"
|
|
| "latestUserMessageAt"
|
|
>;
|
|
}
|
|
|
|
export function buildAgentAwarenessDeepLink(input: {
|
|
readonly environmentId: EnvironmentId;
|
|
readonly threadId: ThreadId;
|
|
}): string {
|
|
return `/threads/${encodeURIComponent(input.environmentId)}/${encodeURIComponent(input.threadId)}`;
|
|
}
|
|
|
|
export function projectThreadAwareness(
|
|
input: ProjectThreadAwarenessInput,
|
|
): AgentAwarenessState | null {
|
|
const { environmentId, project, thread } = input;
|
|
const phase = resolveThreadAwarenessPhase(thread);
|
|
if (!phase) {
|
|
return null;
|
|
}
|
|
|
|
const detail = detailForPhase(phase, thread);
|
|
return {
|
|
environmentId,
|
|
threadId: thread.id,
|
|
projectTitle: project.title,
|
|
threadTitle: thread.title,
|
|
phase,
|
|
headline: headlineForPhase(phase, thread),
|
|
...(detail === undefined ? {} : { detail }),
|
|
modelTitle: thread.modelSelection.model,
|
|
updatedAt: thread.updatedAt,
|
|
deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }),
|
|
};
|
|
}
|
|
|
|
function resolveThreadAwarenessPhase(
|
|
thread: ProjectThreadAwarenessInput["thread"],
|
|
): AgentAwarenessPhase | null {
|
|
if (thread.hasPendingApprovals) {
|
|
return "waiting_for_approval";
|
|
}
|
|
if (thread.hasPendingUserInput) {
|
|
return "waiting_for_input";
|
|
}
|
|
// A proactive delivery is news the user has not seen, but only while it is
|
|
// still the newest thing on the thread: once a turn or a user message lands
|
|
// after it, the ordinary ladder describes the thread better and pinning it
|
|
// to "notification" would suppress the real completion/running state
|
|
// indefinitely (there is no read state to clear it).
|
|
if (isLatestNotificationCurrent(thread)) {
|
|
return "notification";
|
|
}
|
|
if (thread.session?.status === "error" || thread.latestTurn?.state === "error") {
|
|
return "failed";
|
|
}
|
|
if (thread.session?.status === "starting") {
|
|
return "starting";
|
|
}
|
|
if (thread.session?.status === "running" || thread.latestTurn?.state === "running") {
|
|
return "running";
|
|
}
|
|
if (thread.latestTurn?.state === "completed") {
|
|
return "completed";
|
|
}
|
|
// A turn that finished can still read as "interrupted" here: session
|
|
// teardown settles still-running turns by session status, and that write
|
|
// can race the turn.completed one. completedAt survives the race — a turn
|
|
// that has a completion timestamp finished, whatever the state column says.
|
|
// Without this, quick finish-then-teardown threads resolve to null
|
|
// persistently and get tombstoned instead of published as completed.
|
|
if (thread.latestTurn?.state === "interrupted" && thread.latestTurn.completedAt !== null) {
|
|
return "completed";
|
|
}
|
|
// Threads whose turns never produce a checkpoint (no code changes) have no
|
|
// materialized latestTurn in the shell at all, and the session-set
|
|
// projection clears latest_turn_id the moment the session settles. The
|
|
// session status is then the only surviving completion signal: a live
|
|
// session at "ready"/"idle" with nothing pending and nothing running means
|
|
// the agent finished and is waiting for the next prompt — Done.
|
|
if (thread.session?.status === "ready" || thread.session?.status === "idle") {
|
|
return "completed";
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* True while the thread's newest proactive delivery is also the newest thing
|
|
* that happened to the thread — nothing the user sent and no turn activity
|
|
* postdates it.
|
|
*/
|
|
function isLatestNotificationCurrent(thread: ProjectThreadAwarenessInput["thread"]): boolean {
|
|
const notification = thread.latestNotification ?? null;
|
|
if (!notification) {
|
|
return false;
|
|
}
|
|
const deliveredAtMs = Date.parse(notification.deliveredAt);
|
|
if (Number.isNaN(deliveredAtMs)) {
|
|
return false;
|
|
}
|
|
const supersedingTimestamps = [
|
|
thread.latestUserMessageAt,
|
|
thread.latestTurn?.completedAt ?? null,
|
|
thread.latestTurn?.startedAt ?? null,
|
|
thread.latestTurn?.requestedAt ?? null,
|
|
];
|
|
for (const timestamp of supersedingTimestamps) {
|
|
if (timestamp === null) {
|
|
continue;
|
|
}
|
|
const timestampMs = Date.parse(timestamp);
|
|
if (!Number.isNaN(timestampMs) && timestampMs > deliveredAtMs) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function headlineForPhase(
|
|
phase: AgentAwarenessPhase,
|
|
thread: ProjectThreadAwarenessInput["thread"],
|
|
): string {
|
|
switch (phase) {
|
|
case "starting":
|
|
return "Starting agent";
|
|
case "running":
|
|
return "Agent is working";
|
|
case "waiting_for_approval":
|
|
return "Approval needed";
|
|
case "waiting_for_input":
|
|
return "Waiting for input";
|
|
// The delivering agent's own label ("Cron: daily-digest") is the headline:
|
|
// a generic one would strip the only information the delivery carries.
|
|
case "notification":
|
|
return thread.latestNotification?.label ?? "New message";
|
|
case "completed":
|
|
return "Agent finished";
|
|
case "failed":
|
|
return "Agent failed";
|
|
case "stale":
|
|
return "Update delayed";
|
|
}
|
|
}
|
|
|
|
function detailForPhase(
|
|
phase: AgentAwarenessPhase,
|
|
thread: ProjectThreadAwarenessInput["thread"],
|
|
): string | undefined {
|
|
if (phase === "failed") {
|
|
return thread.session?.lastError ?? undefined;
|
|
}
|
|
if (phase === "completed") {
|
|
return "Review the completed task.";
|
|
}
|
|
if (phase === "running" && thread.session?.providerName) {
|
|
return `${thread.session.providerName} is active.`;
|
|
}
|
|
return undefined;
|
|
}
|