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:
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,
|
||||
}),
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
} from "./model.ts";
|
||||
import {
|
||||
HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
HermesGatewayCapabilities,
|
||||
HermesGatewayConnectionHello,
|
||||
HermesGatewayCreateEnrollmentInput,
|
||||
@@ -72,9 +73,9 @@ describe("Hermes gateway management contracts", () => {
|
||||
model: "gpt-5.6-terra",
|
||||
connectionGeneration: 3,
|
||||
activeSessionCount: 2,
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
capabilities: {
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
@@ -107,11 +108,11 @@ describe("Hermes gateway handshake", () => {
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-1",
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
pluginVersion: "0.2.0",
|
||||
hermesVersion: "1.2.3",
|
||||
capabilities: {
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
@@ -131,11 +132,11 @@ describe("Hermes gateway handshake", () => {
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-2",
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
pluginVersion: "0.2.0",
|
||||
hermesVersion: "1.2.3",
|
||||
capabilities: {
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
@@ -161,11 +162,11 @@ describe("Hermes gateway handshake", () => {
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-no-model",
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
pluginVersion: "0.2.0",
|
||||
hermesVersion: "1.2.3",
|
||||
capabilities: {
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
@@ -210,7 +211,7 @@ describe("Hermes gateway handshake", () => {
|
||||
it("reserves attachments for a future protocol version", () => {
|
||||
expect(() =>
|
||||
decodeCapabilities({
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
@@ -221,12 +222,12 @@ describe("Hermes gateway handshake", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("T3 to Hermes v2 messages", () => {
|
||||
describe("T3 to Hermes messages", () => {
|
||||
it("decodes session creation and opaque resume cursors", () => {
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "session.ensure",
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: "ensure-1",
|
||||
threadId: "thread-1",
|
||||
resumeSessionId: "opaque/hermes/session/value",
|
||||
@@ -235,7 +236,7 @@ describe("T3 to Hermes v2 messages", () => {
|
||||
|
||||
expect(
|
||||
decodeResumeCursor({
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
sessionId: "opaque/hermes/session/value",
|
||||
}).sessionId,
|
||||
).toBe("opaque/hermes/session/value");
|
||||
@@ -243,7 +244,7 @@ describe("T3 to Hermes v2 messages", () => {
|
||||
|
||||
it("decodes start and steering as distinct turn operations", () => {
|
||||
const context = {
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: "turn-command-1",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
@@ -257,7 +258,7 @@ describe("T3 to Hermes v2 messages", () => {
|
||||
|
||||
it("decodes interrupt, approval, structured input, stop, and ping", () => {
|
||||
const turnContext = {
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
turnId: "turn-1",
|
||||
@@ -289,7 +290,7 @@ describe("T3 to Hermes v2 messages", () => {
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "session.stop",
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: "stop-1",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
@@ -298,7 +299,7 @@ describe("T3 to Hermes v2 messages", () => {
|
||||
expect(
|
||||
decodeT3Message({
|
||||
type: "ping",
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: "ping-1",
|
||||
sentAt: "2026-07-23T12:00:00.000Z",
|
||||
}).type,
|
||||
@@ -316,11 +317,103 @@ describe("T3 to Hermes v2 messages", () => {
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("defaults an unstated connection role to gateway", () => {
|
||||
// The field is about intent, not tolerance: a hello that says nothing is
|
||||
// the ordinary live plugin, which must never be read as a throwaway
|
||||
// delivery socket.
|
||||
const hello = decodeHello({
|
||||
type: "connection.hello",
|
||||
requestId: "hello-role-default",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
pluginVersion: "0.2.0",
|
||||
hermesVersion: "1.2.3",
|
||||
capabilities: {
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
streaming: true,
|
||||
activity: true,
|
||||
approvals: true,
|
||||
userInput: true,
|
||||
attachments: false,
|
||||
},
|
||||
authentication: { type: "instance-credential", instanceId: "hermes", credential: "secret" },
|
||||
});
|
||||
|
||||
expect(hello.role).toBe("gateway");
|
||||
});
|
||||
|
||||
it("carries the home thread designation on acceptance", () => {
|
||||
const accepted = decodeT3Message({
|
||||
type: "connection.accepted",
|
||||
requestId: "hello-1",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
instanceId: "hermes",
|
||||
nickname: "Remote Hermes",
|
||||
homeThreadId: "thread-home-1",
|
||||
});
|
||||
|
||||
expect(accepted.type).toBe("connection.accepted");
|
||||
if (accepted.type === "connection.accepted") {
|
||||
expect(accepted.homeThreadId).toBe("thread-home-1");
|
||||
}
|
||||
|
||||
// Optional: a handshake whose home-thread resolution failed still accepts
|
||||
// the plugin rather than refusing an authenticated connection.
|
||||
const withoutHome = decodeT3Message({
|
||||
type: "connection.accepted",
|
||||
requestId: "hello-2",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
instanceId: "hermes",
|
||||
nickname: "Remote Hermes",
|
||||
});
|
||||
expect(withoutHome.type).toBe("connection.accepted");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes to T3 v2 events", () => {
|
||||
describe("Hermes home deliveries", () => {
|
||||
const delivery = {
|
||||
type: "home.deliver",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
deliveryId: "delivery-1",
|
||||
threadId: "thread-home-1",
|
||||
kind: "cron",
|
||||
label: "Cron: daily-digest",
|
||||
text: "Your digest is ready.",
|
||||
createdAt: "2026-07-25T12:00:00.000Z",
|
||||
} as const;
|
||||
|
||||
it("decodes a delivery and its acknowledgement", () => {
|
||||
const decoded = decodePluginMessage(delivery);
|
||||
expect(decoded.type).toBe("home.deliver");
|
||||
if (decoded.type === "home.deliver") {
|
||||
expect(decoded.kind).toBe("cron");
|
||||
expect(decoded.deliveryId).toBe("delivery-1");
|
||||
}
|
||||
|
||||
const ack = decodeT3Message({
|
||||
type: "home.deliver.ack",
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
deliveryId: "delivery-1",
|
||||
});
|
||||
expect(ack.type).toBe("home.deliver.ack");
|
||||
});
|
||||
|
||||
it("requires a delivery id, since it is the dedupe key for retries", () => {
|
||||
expect(() => decodePluginMessage({ ...delivery, deliveryId: "" })).toThrow();
|
||||
});
|
||||
|
||||
it("rejects an unknown delivery kind rather than guessing a badge", () => {
|
||||
expect(() => decodePluginMessage({ ...delivery, kind: "surprise" })).toThrow();
|
||||
});
|
||||
|
||||
it("rejects empty delivery text", () => {
|
||||
expect(() => decodePluginMessage({ ...delivery, text: "" })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes to T3 events", () => {
|
||||
const turnContext = {
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
turnId: "turn-1",
|
||||
@@ -329,7 +422,7 @@ describe("Hermes to T3 v2 events", () => {
|
||||
it("decodes session readiness, turn start, streaming text, and completion", () => {
|
||||
const legacyReady = decodePluginMessage({
|
||||
type: "session.ready",
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: "ensure-1",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
@@ -338,7 +431,7 @@ describe("Hermes to T3 v2 events", () => {
|
||||
expect(legacyReady.type).toBe("session.ready");
|
||||
const activeReady = decodePluginMessage({
|
||||
type: "session.ready",
|
||||
protocolVersion: 2,
|
||||
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
|
||||
requestId: "ensure-2",
|
||||
threadId: "thread-1",
|
||||
sessionId: "session-1",
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*
|
||||
* @module hermesGateway
|
||||
*/
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
@@ -21,7 +22,7 @@ import { ProviderApprovalDecision, ProviderUserInputAnswers } from "./orchestrat
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
import { CanonicalItemType, CanonicalRequestType, UserInputQuestion } from "./providerRuntime.ts";
|
||||
|
||||
export const HERMES_GATEWAY_PROTOCOL_VERSION = 2 as const;
|
||||
export const HERMES_GATEWAY_PROTOCOL_VERSION = 3 as const;
|
||||
|
||||
export const HermesGatewayProtocolVersion = Schema.Literal(HERMES_GATEWAY_PROTOCOL_VERSION);
|
||||
export type HermesGatewayProtocolVersion = typeof HermesGatewayProtocolVersion.Type;
|
||||
@@ -87,7 +88,7 @@ export type HermesGatewayCapabilities = typeof HermesGatewayCapabilities.Type;
|
||||
*
|
||||
* This deliberately permits capability shapes from a newer protocol so T3 can
|
||||
* return a structured `version-incompatible` rejection instead of failing the
|
||||
* WebSocket frame decoder. Accepted v2 connections must subsequently validate
|
||||
* WebSocket frame decoder. Accepted connections must subsequently validate
|
||||
* this advertisement with `HermesGatewayCapabilities`.
|
||||
*/
|
||||
export const HermesGatewayHelloCapabilities = Schema.Struct({
|
||||
@@ -256,10 +257,23 @@ export const HermesGatewayAuthentication = Schema.Union([
|
||||
]);
|
||||
export type HermesGatewayAuthentication = typeof HermesGatewayAuthentication.Type;
|
||||
|
||||
/**
|
||||
* What a connecting socket intends to be.
|
||||
*
|
||||
* `gateway` is the instance's one live plugin connection: registered under
|
||||
* generation fencing, pinged for liveness, and displacing any predecessor.
|
||||
* `delivery` is a short-lived socket — an out-of-process cron run dialing in
|
||||
* only to hand over a `home.deliver` and leave. Delivery connections are
|
||||
* authenticated identically but are never registered as the primary
|
||||
* connection, so they cannot kick a healthy gateway socket off its instance.
|
||||
*/
|
||||
export const HermesGatewayConnectionRole = Schema.Literals(["gateway", "delivery"]);
|
||||
export type HermesGatewayConnectionRole = typeof HermesGatewayConnectionRole.Type;
|
||||
|
||||
/**
|
||||
* `protocolVersion` accepts any positive integer at the initial boundary so
|
||||
* T3 can reject incompatible plugins with a structured upgrade response.
|
||||
* Once accepted, all remaining v2 frames use the literal v2 schema.
|
||||
* Once accepted, all remaining frames use the literal current-version schema.
|
||||
*/
|
||||
export const HermesGatewayConnectionHello = Schema.Struct({
|
||||
type: Schema.Literal("connection.hello"),
|
||||
@@ -278,6 +292,12 @@ export const HermesGatewayConnectionHello = Schema.Struct({
|
||||
* value degrades to the generic label rather than failing the handshake.
|
||||
*/
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
/**
|
||||
* Defaults to `"gateway"` on decode so the field stays honest about intent
|
||||
* rather than making every caller repeat the common case. v3 requires both
|
||||
* sides updated regardless, so this default is ergonomics, not tolerance.
|
||||
*/
|
||||
role: HermesGatewayConnectionRole.pipe(Schema.withDecodingDefault(Effect.succeed("gateway"))),
|
||||
});
|
||||
export type HermesGatewayConnectionHello = typeof HermesGatewayConnectionHello.Type;
|
||||
|
||||
@@ -288,6 +308,17 @@ export const HermesGatewayConnectionAccepted = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
nickname: HermesGatewayNickname,
|
||||
credential: Schema.optional(HermesGatewayCredential),
|
||||
/**
|
||||
* The instance's durable home thread — where Hermes' proactive output lands
|
||||
* when nothing named a destination. Sent on every successful handshake so
|
||||
* the plugin reconciles its `T3_HOME_CHANNEL` cache each connect; T3's
|
||||
* settings blob is the authoritative designation.
|
||||
*
|
||||
* Optional because resolving it must never fail a handshake: if the thread
|
||||
* could not be created this connect, the plugin keeps whatever it had and
|
||||
* reconciles on the next one.
|
||||
*/
|
||||
homeThreadId: Schema.optional(ThreadId),
|
||||
});
|
||||
export type HermesGatewayConnectionAccepted = typeof HermesGatewayConnectionAccepted.Type;
|
||||
|
||||
@@ -633,6 +664,68 @@ export const HermesGatewayPong = Schema.Struct({
|
||||
});
|
||||
export type HermesGatewayPong = typeof HermesGatewayPong.Type;
|
||||
|
||||
/**
|
||||
* Plugin-minted, stable across retries. T3 dedupes on it, which is what makes
|
||||
* the plugin's queue safe to flush more than once.
|
||||
*/
|
||||
export const HermesGatewayDeliveryId = TrimmedNonEmptyString.pipe(
|
||||
Schema.brand("HermesGatewayDeliveryId"),
|
||||
);
|
||||
export type HermesGatewayDeliveryId = typeof HermesGatewayDeliveryId.Type;
|
||||
|
||||
/**
|
||||
* What produced a home delivery. Drives both the rendered badge and whether
|
||||
* the delivery raises its hand: everything except `lifecycle` un-settles the
|
||||
* thread and pushes; gateway online/shutdown notices land quietly.
|
||||
*
|
||||
* Classification is best-effort on the plugin side — Hermes' `adapter.send()`
|
||||
* contract carries no structured provenance marker on every path — so a
|
||||
* misclassification costs a wrong badge, never a lost delivery.
|
||||
*/
|
||||
export const HermesGatewayHomeDeliveryKind = Schema.Literals([
|
||||
"cron",
|
||||
"message",
|
||||
"lifecycle",
|
||||
"handoff",
|
||||
"other",
|
||||
]);
|
||||
export type HermesGatewayHomeDeliveryKind = typeof HermesGatewayHomeDeliveryKind.Type;
|
||||
|
||||
/**
|
||||
* Hermes-initiated delivery into the instance's home thread.
|
||||
*
|
||||
* Deliberately not a turn: there is no provider session, no turn id, and no
|
||||
* request the delivery answers. A delivery may arrive while the home thread
|
||||
* has a live user turn and must not disturb it.
|
||||
*/
|
||||
export const HermesGatewayHomeDeliver = Schema.Struct({
|
||||
type: Schema.Literal("home.deliver"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
deliveryId: HermesGatewayDeliveryId,
|
||||
threadId: ThreadId,
|
||||
kind: HermesGatewayHomeDeliveryKind,
|
||||
/** Human source label rendered as the badge — "Cron: daily-digest". */
|
||||
label: TrimmedNonEmptyString.check(Schema.isMaxLength(200)),
|
||||
text: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(120_000)),
|
||||
/**
|
||||
* When Hermes produced the content, not when it reached T3. These diverge
|
||||
* whenever a queued delivery flushes after a reconnect.
|
||||
*/
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
export type HermesGatewayHomeDeliver = typeof HermesGatewayHomeDeliver.Type;
|
||||
|
||||
/**
|
||||
* Sent only after the delivery is durably written. The plugin purges its
|
||||
* queued copy on this frame and nothing else, so acking early loses messages.
|
||||
*/
|
||||
export const HermesGatewayHomeDeliverAck = Schema.Struct({
|
||||
type: Schema.Literal("home.deliver.ack"),
|
||||
protocolVersion: HermesGatewayProtocolVersion,
|
||||
deliveryId: HermesGatewayDeliveryId,
|
||||
});
|
||||
export type HermesGatewayHomeDeliverAck = typeof HermesGatewayHomeDeliverAck.Type;
|
||||
|
||||
export const HermesGatewayProtocolErrorCode = Schema.Literals([
|
||||
"invalid-message",
|
||||
"unsupported-message",
|
||||
@@ -666,6 +759,7 @@ export const HermesGatewayT3ToPluginMessage = Schema.Union([
|
||||
HermesGatewayDescribeRequest,
|
||||
HermesGatewaySkillBodyRequest,
|
||||
HermesGatewayPing,
|
||||
HermesGatewayHomeDeliverAck,
|
||||
]);
|
||||
export type HermesGatewayT3ToPluginMessage = typeof HermesGatewayT3ToPluginMessage.Type;
|
||||
|
||||
@@ -690,6 +784,7 @@ export const HermesGatewayPluginToT3Message = Schema.Union([
|
||||
HermesGatewaySkillBodyResponse,
|
||||
HermesGatewayPong,
|
||||
HermesGatewayProtocolError,
|
||||
HermesGatewayHomeDeliver,
|
||||
]);
|
||||
export type HermesGatewayPluginToT3Message = typeof HermesGatewayPluginToT3Message.Type;
|
||||
|
||||
|
||||
@@ -238,6 +238,27 @@ export type OrchestrationProject = typeof OrchestrationProject.Type;
|
||||
export const OrchestrationMessageRole = Schema.Literals(["user", "assistant", "system"]);
|
||||
export type OrchestrationMessageRole = typeof OrchestrationMessageRole.Type;
|
||||
|
||||
/**
|
||||
* Provenance for a message an agent delivered on its own initiative rather
|
||||
* than as the answer to a turn.
|
||||
*
|
||||
* Present only on proactive deliveries (a cron result, an agent-initiated
|
||||
* `send_message`, a gateway lifecycle notice). Its absence is what makes a
|
||||
* message an ordinary one, so consumers must treat "no notification" as the
|
||||
* normal case and never synthesize a default.
|
||||
*/
|
||||
export const OrchestrationMessageNotification = Schema.Struct({
|
||||
kind: Schema.Literals(["cron", "message", "lifecycle", "handoff", "other"]),
|
||||
/** Human source label rendered as the badge — "Cron: daily-digest". */
|
||||
label: TrimmedNonEmptyString,
|
||||
/**
|
||||
* The delivering agent's idempotency key. Retained on the row so a replayed
|
||||
* delivery is recognized as one already written rather than appended twice.
|
||||
*/
|
||||
deliveryId: TrimmedNonEmptyString,
|
||||
});
|
||||
export type OrchestrationMessageNotification = typeof OrchestrationMessageNotification.Type;
|
||||
|
||||
export const OrchestrationMessage = Schema.Struct({
|
||||
id: MessageId,
|
||||
role: OrchestrationMessageRole,
|
||||
@@ -245,6 +266,11 @@ export const OrchestrationMessage = Schema.Struct({
|
||||
attachments: Schema.optional(Schema.Array(ChatAttachment)),
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
streaming: Schema.Boolean,
|
||||
/**
|
||||
* Set only on proactive agent deliveries. Optional so every existing
|
||||
* producer, cached snapshot, and persisted row decodes unchanged.
|
||||
*/
|
||||
notification: Schema.optional(OrchestrationMessageNotification),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
@@ -417,6 +443,24 @@ export const OrchestrationProjectShell = Schema.Struct({
|
||||
});
|
||||
export type OrchestrationProjectShell = typeof OrchestrationProjectShell.Type;
|
||||
|
||||
/**
|
||||
* The most recent proactive delivery in a thread, flattened onto the shell.
|
||||
*
|
||||
* Shell consumers (sidebar rows, the awareness/push projection) never load a
|
||||
* thread's messages, so the notification provenance that lives on the message
|
||||
* row has to be materialized here or those surfaces cannot see it at all.
|
||||
* `deliveredAt` is the delivering message's `createdAt`, which is what lets a
|
||||
* reader decide whether the notification is still the newest thing that
|
||||
* happened to the thread or has been overtaken by a later turn.
|
||||
*/
|
||||
export const OrchestrationThreadNotificationSummary = Schema.Struct({
|
||||
kind: OrchestrationMessageNotification.fields.kind,
|
||||
label: TrimmedNonEmptyString,
|
||||
deliveredAt: IsoDateTime,
|
||||
});
|
||||
export type OrchestrationThreadNotificationSummary =
|
||||
typeof OrchestrationThreadNotificationSummary.Type;
|
||||
|
||||
export const OrchestrationThreadShell = Schema.Struct({
|
||||
id: ThreadId,
|
||||
projectId: ProjectId,
|
||||
@@ -443,6 +487,12 @@ export const OrchestrationThreadShell = Schema.Struct({
|
||||
hasPendingApprovals: Schema.Boolean,
|
||||
hasPendingUserInput: Schema.Boolean,
|
||||
hasActionableProposedPlan: Schema.Boolean,
|
||||
/**
|
||||
* Newest proactive delivery, or `null`/absent on every thread that has never
|
||||
* received one. Optional (like `snoozedUntil`) so shells produced by
|
||||
* pre-notification servers and every existing cached snapshot still decode.
|
||||
*/
|
||||
latestNotification: Schema.optional(Schema.NullOr(OrchestrationThreadNotificationSummary)),
|
||||
});
|
||||
export type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type;
|
||||
|
||||
@@ -883,6 +933,28 @@ const ThreadActivityAppendCommand = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
/**
|
||||
* A proactive delivery from a connected agent into its home thread.
|
||||
*
|
||||
* Internal-only and deliberately outside the turn machinery: there is no
|
||||
* provider session or turn behind it, and it may arrive while the thread has
|
||||
* a live user turn, which it must not disturb. `deliveryId` is the agent's
|
||||
* idempotency key — the decider drops a repeat rather than appending twice,
|
||||
* which is what lets the plugin retry an unacked delivery safely.
|
||||
*/
|
||||
const ThreadNotificationDeliverCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.notification.deliver"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
deliveryId: TrimmedNonEmptyString,
|
||||
kind: Schema.Literals(["cron", "message", "lifecycle", "handoff", "other"]),
|
||||
label: TrimmedNonEmptyString,
|
||||
text: Schema.String,
|
||||
/** When the agent produced the content, which may predate its arrival. */
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadRevertCompleteCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.revert.complete"),
|
||||
commandId: CommandId,
|
||||
@@ -899,6 +971,7 @@ const InternalOrchestrationCommand = Schema.Union([
|
||||
ThreadProposedPlanUpsertCommand,
|
||||
ThreadTurnDiffCompleteCommand,
|
||||
ThreadActivityAppendCommand,
|
||||
ThreadNotificationDeliverCommand,
|
||||
ThreadRevertCompleteCommand,
|
||||
]);
|
||||
export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;
|
||||
@@ -936,6 +1009,7 @@ export const OrchestrationEventType = Schema.Literals([
|
||||
"thread.proposed-plan-upserted",
|
||||
"thread.turn-diff-completed",
|
||||
"thread.activity-appended",
|
||||
"thread.notification-delivered",
|
||||
]);
|
||||
export type OrchestrationEventType = typeof OrchestrationEventType.Type;
|
||||
|
||||
@@ -1179,6 +1253,23 @@ export const ThreadActivityAppendedPayload = Schema.Struct({
|
||||
activity: OrchestrationThreadActivity,
|
||||
});
|
||||
|
||||
/**
|
||||
* A proactive agent delivery, materialized as an assistant message row.
|
||||
*
|
||||
* It is a real transcript message — selectable, copyable, part of history —
|
||||
* distinguished only by carrying `notification` provenance. It has no
|
||||
* `turnId`: nothing about it belongs to a turn, and attributing it to the
|
||||
* thread's live turn would fold it away behind that turn's "Worked for …".
|
||||
*/
|
||||
export const ThreadNotificationDeliveredPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
text: Schema.String,
|
||||
notification: OrchestrationMessageNotification,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const OrchestrationEventMetadata = Schema.Struct({
|
||||
providerTurnId: Schema.optional(TrimmedNonEmptyString),
|
||||
providerItemId: Schema.optional(ProviderItemId),
|
||||
@@ -1331,6 +1422,11 @@ export const OrchestrationEvent = Schema.Union([
|
||||
type: Schema.Literal("thread.activity-appended"),
|
||||
payload: ThreadActivityAppendedPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.notification-delivered"),
|
||||
payload: ThreadNotificationDeliveredPayload,
|
||||
}),
|
||||
]);
|
||||
export type OrchestrationEvent = typeof OrchestrationEvent.Type;
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ export const RelayAgentAwarenessPhase = Schema.Literals([
|
||||
"running",
|
||||
"waiting_for_approval",
|
||||
"waiting_for_input",
|
||||
// A proactive agent delivery (cron result, agent-initiated message).
|
||||
"notification",
|
||||
"completed",
|
||||
"failed",
|
||||
"stale",
|
||||
|
||||
@@ -203,6 +203,15 @@ export const ServerProvider = Schema.Struct({
|
||||
skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
|
||||
versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory),
|
||||
updateState: Schema.optionalKey(ServerProviderUpdateState),
|
||||
/**
|
||||
* The instance's designated home thread, where its agent's proactive output
|
||||
* lands. Clients use it to pin the thread first in the instance's list and
|
||||
* to withhold Delete.
|
||||
*
|
||||
* Only Hermes instances designate one; absent everywhere else, and absent on
|
||||
* a Hermes instance that has not completed a handshake yet.
|
||||
*/
|
||||
homeThreadId: Schema.optional(ThreadId),
|
||||
});
|
||||
export type ServerProvider = typeof ServerProvider.Type;
|
||||
|
||||
|
||||
@@ -429,6 +429,19 @@ export const HermesSettings = makeProviderSettingsSchema({
|
||||
revoked: Schema.optionalKey(Schema.Boolean).pipe(
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
/**
|
||||
* The instance's durable home thread — the authoritative designation for
|
||||
* where Hermes' proactive output lands.
|
||||
*
|
||||
* Kept here rather than in a dedicated table for the same reason as the
|
||||
* fields above: it is per-instance enrollment metadata, and settings avoids
|
||||
* a migration. Absent means "not yet designated"; the next handshake
|
||||
* converges it on read. The plugin's `T3_HOME_CHANNEL` env var is a synced
|
||||
* cache of this value, never the source of truth.
|
||||
*/
|
||||
homeThreadId: Schema.optionalKey(TrimmedString).pipe(
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
});
|
||||
export type HermesSettings = typeof HermesSettings.Type;
|
||||
|
||||
|
||||
@@ -29,6 +29,8 @@ function thread(
|
||||
| "updatedAt"
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingUserInput"
|
||||
| "latestNotification"
|
||||
| "latestUserMessageAt"
|
||||
> {
|
||||
return {
|
||||
id: "thread-1" as ThreadId,
|
||||
@@ -39,6 +41,8 @@ function thread(
|
||||
updatedAt: NOW,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
latestNotification: null,
|
||||
latestUserMessageAt: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -102,6 +106,76 @@ describe("projectThreadAwareness", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("projects a fresh proactive delivery with the delivery's own label as the headline", () => {
|
||||
const state = projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({
|
||||
latestNotification: {
|
||||
kind: "cron",
|
||||
label: "Cron: daily-digest",
|
||||
deliveredAt: NOW,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(state?.phase).toBe("notification");
|
||||
// A generic headline would strip the only information the delivery carries.
|
||||
expect(state?.headline).toBe("Cron: daily-digest");
|
||||
});
|
||||
|
||||
it("stops reporting a delivery once later thread activity supersedes it", () => {
|
||||
const delivered = "2026-05-22T11:00:00.000Z";
|
||||
const later = "2026-05-22T11:30:00.000Z";
|
||||
const notification = {
|
||||
kind: "message" as const,
|
||||
label: "Hermes",
|
||||
deliveredAt: delivered,
|
||||
};
|
||||
|
||||
// A user reply after the delivery: the ordinary ladder takes over again.
|
||||
expect(
|
||||
projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({ latestNotification: notification, latestUserMessageAt: later }),
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
// A turn that started after it likewise wins — otherwise "notification"
|
||||
// would pin forever, since nothing ever marks it read.
|
||||
expect(
|
||||
projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({
|
||||
latestNotification: notification,
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as TurnId,
|
||||
state: "running",
|
||||
requestedAt: later,
|
||||
startedAt: later,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
}),
|
||||
})?.phase,
|
||||
).toBe("running");
|
||||
});
|
||||
|
||||
it("keeps blocked-on-you phases ahead of a delivery", () => {
|
||||
const state = projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({
|
||||
hasPendingApprovals: true,
|
||||
latestNotification: { kind: "cron", label: "Cron: nightly", deliveredAt: NOW },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(state?.phase).toBe("waiting_for_approval");
|
||||
});
|
||||
|
||||
it("projects completed turns as completed even when teardown settled them as interrupted", () => {
|
||||
const finishedTurn = {
|
||||
turnId: "turn-1" as TurnId,
|
||||
|
||||
@@ -10,6 +10,7 @@ export type AgentAwarenessPhase =
|
||||
| "running"
|
||||
| "waiting_for_approval"
|
||||
| "waiting_for_input"
|
||||
| "notification"
|
||||
| "completed"
|
||||
| "failed"
|
||||
| "stale";
|
||||
@@ -40,6 +41,8 @@ export interface ProjectThreadAwarenessInput {
|
||||
| "updatedAt"
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingUserInput"
|
||||
| "latestNotification"
|
||||
| "latestUserMessageAt"
|
||||
>;
|
||||
}
|
||||
|
||||
@@ -66,7 +69,7 @@ export function projectThreadAwareness(
|
||||
projectTitle: project.title,
|
||||
threadTitle: thread.title,
|
||||
phase,
|
||||
headline: headlineForPhase(phase),
|
||||
headline: headlineForPhase(phase, thread),
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
modelTitle: thread.modelSelection.model,
|
||||
updatedAt: thread.updatedAt,
|
||||
@@ -83,6 +86,14 @@ function resolveThreadAwarenessPhase(
|
||||
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";
|
||||
}
|
||||
@@ -116,7 +127,42 @@ function resolveThreadAwarenessPhase(
|
||||
return null;
|
||||
}
|
||||
|
||||
function headlineForPhase(phase: AgentAwarenessPhase): string {
|
||||
/**
|
||||
* 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";
|
||||
@@ -126,6 +172,10 @@ function headlineForPhase(phase: AgentAwarenessPhase): string {
|
||||
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":
|
||||
|
||||
Reference in new issue
Block a user