feat: give every Hermes instance a Home thread for proactive delivery

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]>
This commit is contained in:
Ben DavisandClaude Opus 5 committed 2026-07-26 13:10:35 -07:00
1 parent 5bfb90db61
commit 784fcb71e6
73 files changed
+5907 -119

No files matched your search

@@ -444,6 +444,88 @@ describe("applyThreadDetailEvent", () => {
});
});
describe("thread.notification-delivered", () => {
const deliveryEvent = {
...baseEventFields,
sequence: 20,
occurredAt: "2026-04-01T07:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.notification-delivered",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("msg-notify"),
text: "Digest ready.",
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: "2026-04-01T07:00:00.000Z",
updatedAt: "2026-04-01T07:00:00.000Z",
},
} as const;
it("appends the delivery as a turnless assistant message carrying provenance", () => {
const result = applyThreadDetailEvent(baseThread, deliveryEvent);
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.messages).toHaveLength(1);
expect(result.thread.messages[0]).toEqual({
id: "msg-notify",
role: "assistant",
text: "Digest ready.",
turnId: null,
streaming: false,
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: "2026-04-01T07:00:00.000Z",
updatedAt: "2026-04-01T07:00:00.000Z",
});
expect(result.thread.updatedAt).toBe("2026-04-01T07:00:00.000Z");
}
});
it("leaves an unrelated live turn untouched", () => {
// A delivery can land mid-turn; attributing it to that turn would fold
// it away behind the turn's summary and mis-settle the turn state.
const threadWithRunningTurn: OrchestrationThread = {
...baseThread,
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "running",
requestedAt: "2026-04-01T06:00:00.000Z",
startedAt: "2026-04-01T06:00:00.000Z",
completedAt: null,
assistantMessageId: null,
},
};
const result = applyThreadDetailEvent(threadWithRunningTurn, deliveryEvent);
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.latestTurn).toEqual(threadWithRunningTurn.latestTurn);
}
});
it("replaces rather than duplicates on a replayed delivery", () => {
const first = applyThreadDetailEvent(baseThread, deliveryEvent);
expect(first.kind).toBe("updated");
if (first.kind !== "updated") return;
const second = applyThreadDetailEvent(first.thread, { ...deliveryEvent, sequence: 21 });
expect(second.kind).toBe("updated");
if (second.kind === "updated") {
expect(second.thread.messages).toHaveLength(1);
expect(second.thread.messages[0]).toEqual(first.thread.messages[0]);
}
});
});
describe("thread.session-set", () => {
it("settles a running latestTurn when the session leaves the running status", () => {
const threadWithRunningTurn: OrchestrationThread = {
@@ -325,6 +325,36 @@ export function applyThreadDetailEvent(
};
}
case "thread.notification-delivered": {
// A proactive delivery is an ordinary transcript message carrying
// provenance. It binds to no turn, so latestTurn and the checkpoint
// rebinding that `thread.message-sent` performs are deliberately
// untouched — attributing it to the live turn would fold it away
// behind that turn's summary.
const message: OrchestrationMessage = {
id: event.payload.messageId,
role: "assistant",
text: event.payload.text,
turnId: null,
streaming: false,
notification: event.payload.notification,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
};
// Replays re-emit the persisted row verbatim, so replacing in place
// keeps the transcript stable instead of duplicating the delivery.
const existingMessage = thread.messages.find((entry) => entry.id === message.id);
const messages = existingMessage
? Arr.map(thread.messages, (entry) => (entry.id === message.id ? message : entry))
: Arr.append(thread.messages, message);
return {
kind: "updated",
thread: { ...thread, messages, updatedAt: event.occurredAt },
};
}
// ── Session ─────────────────────────────────────────────────────
case "thread.session-set": {
// Leaving the "running" session status is the turn-end signal: settle a
@@ -68,4 +68,44 @@ describe("sortThreads", () => {
expect(sorted.map((thread) => thread.id)).toEqual(["thread-1", "thread-2"]);
});
it("pins the requested thread first regardless of its timestamp", () => {
// The agent home thread: a designated destination, not a conversation the
// user started, so staleness must not demote it.
const sorted = sortThreads(
[
makeThread({ id: "thread-newest", updatedAt: "2026-03-09T12:00:00.000Z" }),
makeThread({ id: "thread-home", updatedAt: "2026-01-01T00:00:00.000Z" }),
makeThread({ id: "thread-middle", updatedAt: "2026-03-09T10:00:00.000Z" }),
],
"updated_at",
"thread-home",
);
expect(sorted.map((thread) => thread.id)).toEqual([
"thread-home",
"thread-newest",
"thread-middle",
]);
});
it("sorts unchanged when no thread is pinned or the pinned id is unknown", () => {
const threads = [
makeThread({ id: "thread-newest", updatedAt: "2026-03-09T12:00:00.000Z" }),
makeThread({ id: "thread-oldest", updatedAt: "2026-01-01T00:00:00.000Z" }),
];
expect(sortThreads(threads, "updated_at").map((thread) => thread.id)).toEqual([
"thread-newest",
"thread-oldest",
]);
expect(sortThreads(threads, "updated_at", null).map((thread) => thread.id)).toEqual([
"thread-newest",
"thread-oldest",
]);
expect(sortThreads(threads, "updated_at", "thread-gone").map((thread) => thread.id)).toEqual([
"thread-newest",
"thread-oldest",
]);
});
});
@@ -69,18 +69,35 @@ export function getThreadSortTimestamp(
return getLatestUserMessageTimestamp(thread);
}
/**
* Sort threads for a list, optionally pinning one thread to the top.
*
* `pinnedThreadId` exists for the agent home thread: it is a designated
* destination rather than a conversation the user started, so it must hold
* position one no matter how stale it looks — an agent whose last cron ran a
* month ago still has to be the first row of its instance. The pin is a
* leading sort key rather than a splice so a single pass produces the whole
* ordering, and every downstream consumer of that ordering (preview slice,
* keyboard traversal, prewarming) inherits it for free.
*
* A pinned id that matches no thread changes nothing.
*/
export function sortThreads<T extends { readonly id: string } & ThreadSortInput>(
threads: readonly T[],
sortOrder: SidebarThreadSortOrder,
pinnedThreadId?: string | null,
): T[] {
return Arr.sort(
threads,
Order.mapInput(
Order.Struct({
// `Order.Boolean` puts `false` first; flipped, the pinned row leads.
pinned: Order.flip(Order.Boolean),
timestamp: Order.flip(Order.Number),
id: Order.flip(Order.String),
}),
(thread: T) => ({
pinned: pinnedThreadId != null && thread.id === pinnedThreadId,
timestamp: getThreadSortTimestamp(thread, sortOrder),
id: thread.id,
}),